319 challenges in the catalogue. Browse freely; sign in to open the editor and submit.
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique.
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation: Start at station 3 (index 3) and fill up with 4 units of gas. Tank = 0 + 4 = 4.
Travel to station 4. Tank = 4 - 1 + 5 = 8.
Travel to station 0. Tank = 8 - 2 + 1 = 7.
Travel to station 1. Tank = 7 - 3 + 2 = 6.
Travel to station 2. Tank = 6 - 4 + 3 = 5.
Travel to station 3. Tank = 5 - 5 = 0. You arrive back with 0 gas left.
Example 2:
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation: No matter which station you start at, you cannot complete the circuit.
Total gas = 9, total cost = 10. Not enough gas overall.
Example 3:
Input: gas = [5,1,2,3,4], cost = [4,4,1,5,1]
Output: 4
Explanation: Start at station 4, travel around the circuit successfully.
n == gas.length == cost.length1 <= n <= 10^50 <= gas[i], cost[i] <= 10^4You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.
For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression "+2-1".
Return the number of different expressions that you can build, which evaluates to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 3
Output: 5
Explanation: There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
Example 2:
Input: nums = [1], target = 1
Output: 1
1 <= nums.length <= 200 <= nums[i] <= 10000 <= sum(nums[i]) <= 1000-1000 <= target <= 1000Given 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.
| Digit | Letters | | :--- | :--- | | 2 | abc | | 3 | def | | 4 | ghi | | 5 | jkl | | 6 | mno | | 7 | pqrs | | 8 | tuv | | 9 | wxyz |
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Input: digits = ""
Output: []
Input: digits = "2"
Output: ["a","b","c"]
0 <= digits.length <= 4digits[i] is a digit in the range ['2', '9'].Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
Example 3:
Input: intervals = [[1,4],[0,4]]
Output: [[0,4]]
Explanation: After sorting by start, [0,4] comes first and absorbs [1,4].
1 <= intervals.length <= 10^4intervals[i].length == 20 <= start_i <= end_i <= 10^4At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.
Note that you do not have any change in hand at first.
Given an integer array bills where bills[i] is the bill the i-th customer pays, return true if you can provide every customer with the correct change, or false otherwise.
Input: bills = [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5 bill.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Input: bills = [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give the change of $15 back because we only have two $10 bills.
Since not every customer received the correct change, the answer is false.
1 <= bills.length <= 10^5bills[i] is either 5, 10, or 20.Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1-9 must occur exactly once in each row.1-9 must occur exactly once in each column.1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.The '.' character indicates empty cells.
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: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
board.length == 9board[i].length == 9board[i][j] is a digit or '.'.Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The largest rectangle has area = 10 (heights 5 and 6, width 2).
Example 2:
Input: heights = [2,4]
Output: 4
Explanation: The largest rectangle is bar of height 4, width 1.
Example 3:
Input: heights = [2,1,2]
Output: 3
Explanation: Rectangle of height 1, width 3.
1 <= heights.length <= 10^50 <= heights[i] <= 10^4Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5
Output:
[
[1,2,2],
[5]
]
1 <= candidates.length <= 1001 <= candidates[i] <= 501 <= target <= 30Design a mechanism to ensure that three functions (first, second, third) always execute in order, regardless of the order they are called in. Each function accepts a callback that prints its respective word.
The same instance of OrderedPrinter will be used, and the three functions will be called on separate async contexts (simulating threads). You need to ensure first completes before second starts, and second completes before third starts.
class OrderedPrinter {
first(printFirst: () => void): Promise<void>;
second(printSecond: () => void): Promise<void>;
third(printThird: () => void): Promise<void>;
}
Input: order = [2, 1, 3]
Output: "firstsecondthird"
Explanation: Even though second() is called first,
it waits until first() completes before executing.
order is always a permutation of [1, 2, 3]Build a job queue system that supports background processing of tasks. The system should handle job creation, priority-based processing, retries with exponential backoff, delayed scheduling, concurrency control, and status tracking.
WAITING -> ACTIVE -> COMPLETED
-> FAILED -> WAITING (retry)
-> DEAD (max retries exceeded)
DELAYED -> WAITING (when delay expires)
interface Job {
id: string;
type: string;
payload: any;
status: 'waiting' | 'active' | 'completed' | 'failed' | 'delayed' | 'dead';
priority: number; // Higher = more urgent
attempts: number;
maxRetries: number;
result?: any;
error?: string;
createdAt: string;
startedAt?: string;
completedAt?: string;
nextRetryAt?: string;
delay?: number; // ms to wait before processing
}
interface JobOptions {
priority?: number; // Default: 0
retries?: number; // Default: 3
delay?: number; // ms
backoff?: 'exponential' | 'linear';
timeout?: number; // ms
}
queue.process('send-email', async (job) => {
await sendEmail(job.payload.to, job.payload.subject, job.payload.body);
return { sent: true };
});
const job = await queue.add('send-email', {
to: 'user@test.com',
subject: 'Welcome',
body: 'Hello!'
}, { priority: 10, retries: 3 });
// Job processes and completes
// job.status === 'completed'
// job.result === { sent: true }
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
function convert(s: string, numRows: number): string {}
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
1 <= s.length <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.1 <= numRows <= 1000You have a graph of n nodes labeled from 0 to n - 1. You are given an integer n and a list of edges where edges[i] = [ai, bi] indicates that there is an undirected edge between nodes ai and bi in the graph.
Return true if the edges of the given graph make up a valid tree, and false otherwise.
Example 1:
Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true
Explanation: The edges form a valid tree (connected, no cycles).
Example 2:
Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false
Explanation: The edges form a cycle between nodes 1, 2, and 3.
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= ai, bi < nai != bi// Handler that fails
queue.process('flaky-task', async (job) => {
if (Math.random() < 0.5) throw new Error('Temporary failure');
return { success: true };
});
const job = await queue.add('flaky-task', {}, { retries: 3, backoff: 'exponential' });
// Attempt 1: fails, retry after 1s
// Attempt 2: fails, retry after 2s
// Attempt 3: fails, retry after 4s
// Attempt 4: succeeds or moves to 'dead' status
const job = await queue.add('send-reminder', {
userId: '123',
message: 'Your trial expires tomorrow'
}, { delay: 86400000 }); // 24 hours from now
// job.status === 'delayed'
// After 24 hours: job.status transitions to 'waiting' -> 'active' -> 'completed'