319 challenges in the catalogue. Browse freely; sign in to open the editor and submit.
Implementing "Offline-First" capability is one of the most challenging parts of mobile development. A robust sync engine must handle local changes, remote updates, and resolve conflicts when the same data is modified on both sides.
In this challenge, you will implement a synchronization function syncData that reconciles a local state with a remote state based on a lastSync timestamp.
interface SyncItem {
id: number;
data: string;
timestamp: number; // Unix timestamp in milliseconds
deleted?: boolean; // Flag for soft deletions
}
interface SyncResult {
merged: SyncItem[]; // Final reconciled list of items (excluding deleted ones)
conflicts: {
id: number;
local: SyncItem;
remote: SyncItem;
winner: "local" | "remote";
}[];
toUpload: SyncItem[]; // Local modifications that need to be sent to server
toDownload: SyncItem[]; // Remote modifications that need to be saved locally
}
timestamp is greater than lastSync.lastSync, keep the item as is in merged.merged (unless deleted) and toUpload.merged (unless deleted) and toDownload.timestamp wins.conflicts array.merged (unless deleted).local wins, add it to toUpload. If remote wins, add it to toDownload.Input:
{
"local": [{"id": 1, "data": "local_v", "timestamp": 100}],
"remote": [{"id": 1, "data": "remote_v", "timestamp": 90}],
"lastSync": 80
}
Output:
{
"merged": [{"id": 1, "data": "local_v", "timestamp": 100}],
"conflicts": [{"id": 1, "local": {...}, "remote": {...}, "winner": "local"}],
"toUpload": [{"id": 1, "data": "local_v", "timestamp": 100}],
"toDownload": []
}
1 <= local.length, remote.length <= 1000Given the head of a singly linked list, reverse the list, and return the reversed list.
Example 1:
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:
Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
[0, 5000].-5000 <= Node.val <= 5000A linked list can be reversed either iteratively or recursively. Could you implement both?
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
Explanation: '(' must be closed by ')' not ']'.
Example 4:
Input: s = "([)]"
Output: false
Explanation: Brackets are interleaved — invalid order.
Example 5:
Input: s = "{[]}"
Output: true
Explanation: Properly nested.
1 <= s.length <= 10^4s consists of parentheses only '()[]{}'OAuth 2.0 is the industry-standard protocol for authorization. The Authorization Code Flow is the most commonly used flow, designed for secure server-side applications.
In this challenge, you will implement the logic for an Authorization Server that handles two main endpoints:
/authorize: Validates the request and returns an authorization_code./token: Exchanges the authorization_code for an access_token.client_id and redirect_uri, then issues an authorization_code./token endpoint with the authorization_code, client_secret, and redirect_uri.access_token.state parameter to prevent CSRF.redirect_uri in the token phase matches the one used in the authorization phase.Input (Authorize):
{ "client_id": "abc", "redirect_uri": "https://callback.com", "state": "xyz" }
Output:
{ "code": "AUTH_CODE_123", "state": "xyz" }
Input (Token):
{ "client_id": "abc", "client_secret": "secret123", "code": "AUTH_CODE_123", "redirect_uri": "https://callback.com" }
Output:
{ "access_token": "JWT_TOKEN_456", "token_type": "Bearer", "expires_in": 3600 }
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
1 <= s1.length, s2.length <= 10^4s1 and s2 consist of lowercase English letters.Design a distributed, durable, and highly scalable message queue system similar to Apache Kafka or RabbitMQ. The system must support asynchronous communication between multiple producers and consumers through a Publish-Subscribe (Pub-Sub) or Point-to-Point model.
Example Scenario:
{ "type": "order", "id": 123 } to topic orders.Implement the K-Nearest Neighbors (KNN) classification algorithm from scratch. Given labeled training data, classify new test points by finding the K closest training points and using majority voting.
function knn(
X_train: number[][],
y_train: number[],
X_test: number[][],
k: number
): { predictions: number[] }
X_train: 2D array of training features (n_samples x n_features)y_train: 1D array of class labels (integers)X_test: 2D array of test featuresk: Number of neighbors to considerInput:
X_train = [[1,1],[2,2],[3,3],[6,6],[7,7],[8,8]]
y_train = [0,0,0,1,1,1]
X_test = [[4,4],[7,6]]
k = 3
Output:
predictions = [0, 1]
Explanation:
For [4,4]: 3 nearest are [3,3],[2,2],[1,1] -> labels [0,0,0] -> predict 0
For [7,6]: 3 nearest are [7,7],[6,6],[8,8] -> labels [1,1,1] -> predict 1
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Implementation the MyCircularQueue class:
MyCircularQueue(k) Initializes the object with the size of the queue to be k.boolean enQueue(value) Inserts an element into the circular queue. Return true if the operation is successful.boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.int Front() Gets the front item from the queue. If the queue is empty, return -1.int Rear() Gets the last item from the queue. If the queue is empty, return -1.boolean isEmpty() Checks whether the circular queue is empty or not.boolean isFull() Checks whether the circular queue is full or not.Input: ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output: [null, true, true, true, false, 3, true, true, true, 4]
1 <= k <= 10000 <= value <= 10003000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
1 <= nums.length <= 2001 <= nums[i] <= 100Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown: 5 -> 4 -> 11 -> 2
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There are two root-to-leaf paths: 1->2 (sum = 3) and 1->3 (sum = 4). Neither equals targetSum = 5.
Example 3:
Input: root = [], targetSum = 0
Output: false
[0, 5000].-1000 <= Node.val <= 1000-1000 <= targetSum <= 1000Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity) Initializes the object with the capacity of the data structure.int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.
When a key is first inserted into the cache, its use counter is set to 1. Any get or put operation on an existing key increments the use counter.
The functions get and put must each run in O(1) average time complexity.
Input: ["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [1], [4, 4], [1], [3], [4]]
Output: [null, null, null, 1, null, -1, 3, null, -1, 3, 4]
1 <= capacity <= 10^40 <= key <= 10^50 <= value <= 10^92 * 10^5 calls will be made to and .You are tasked with creating a production-ready multi-stage Dockerfile for a Node.js TypeScript application. Multi-stage builds allow you to use multiple FROM statements in your Dockerfile, each starting a new build stage. You can selectively copy artifacts from one stage to another, leaving behind everything you don't need in the final image.
Given a configuration object describing an application, generate a complete multi-stage Dockerfile as a string. The Dockerfile must:
node:20-alpine as the base image for both stages (unless overridden by config)buildernpm ci (not npm install) for reproducible buildspackage.json and package-lock.json first (leverage Docker layer caching)node_modules (production) and compiled output from the builderNODE_ENV environment variable to productionCMD to start the applicationExample 1:
Input: {
baseImage: "node:20-alpine",
buildCmd: "npm run build",
startCmd: "node dist/index.js",
port: 3000
}
Output:
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force
COPY --from=builder /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/index.js"]
ordersorders and receives the message.orders and receives the same message.getputExample 2:
Input: {
baseImage: "node:18-slim",
buildCmd: "npm run compile",
startCmd: "node build/server.js",
port: 8080
}
Output: (similar structure with node:18-slim base, compile command, build/ directory, port 8080)
latest)WORKDIR, ENV, EXPOSE, USER, and CMD directivesCan you add a third stage for running tests before the production build?