id int64 1 2.61k | slug stringlengths 3 79 | title stringlengths 3 79 | difficulty stringclasses 3
values | content stringlengths 230 5.69k | java stringlengths 392 4.13k | prompt stringlengths 290 4.05k |
|---|---|---|---|---|---|---|
1,181 | before-and-after-puzzle | Before and After Puzzle | Medium | Given a list of `phrases`, generate a list of Before and After puzzles.
A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase.
_Before and After puzzles_ are phrases that are formed by mergin... |
```java
import java.util.*;
public List<String> beforeAndAfterPuzzles(String[] phrases) {
Map<String, Set<String>> firstWordMap = new HashMap<>();
Set<String> result = new TreeSet<>();
for (String phrase : phrases) {
String firstWord = phrase.substring(0, phrase.indexOf(' '));
firstWo... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given a list of `phrases`, generate a list of Before and After puzzles.
A _phrase_ is a string that consists of lowercase English letters and spaces only. No space appears in the start or the... |
2,464 | minimum-subarrays-in-a-valid-split | Minimum Subarrays in a Valid Split | Medium | You are given an integer array `nums`.
Splitting of an integer array `nums` into **subarrays** is **valid** if:
* the _greatest common divisor_ of the first and last elements of each subarray is **greater** than `1`, and
* each element of `nums` belongs to exactly one subarray.
Return _the **minimum** number of ... |
```java
public int minValidSubarrays(int[] nums) {
int count = 0;
while(nums.length > 0) {
int i;
for (i = 0; i < nums.length; i++) {
if (gcd(nums[i], nums[nums.length - 1]) > 1) {
break;
}
}
if (i == nums.length) {
nums = ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an integer array `nums`.
Splitting of an integer array `nums` into **subarrays** is **valid** if:
* the _greatest common divisor_ of the first and last elements of each subar... |
214 | shortest-palindrome | Shortest Palindrome | Hard | You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return _the shortest palindrome you can find by performing this transformation_.
**Example 1:**
**Input:** s = "aacecaaa"
**Output:** "aaacecaaa"
**Example 2:**
**Input:** s = "abcd"
**Output:** "dcbabcd"
**Constr... |
```java
public String shortestPalindrome(String s) {
int n = s.length();
String rev_s = new StringBuilder(s).reverse().toString();
for (int i = 0; i < n; ++i) {
if(s.substring(0, n - i).equals(rev_s.substring(i)))
return rev_s.substring(0, i) + s;
}
return "";
}
```
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return _the shortest palindrome you can find by performing this transformation_.
### Solut... |
1,861 | rotating-the-box | Rotating the Box | Medium | You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following:
* A stone `'#'`
* A stationary obstacle `'*'`
* Empty `'.'`
The box is rotated **90 degrees clockwise**, causing some of the stones to fall due to gravity. Each stone falls down u... |
```java
public int minBoxesTouchingFloor(int n) {
return (n + 1) / 2;
}
```
The algorithm is fairly simple, since the room is a perfect cube, we can place the boxes on the floor in an alternating pattern. We place a box in one corner, then skip one unit and place another box, then skip another unit an... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an `m x n` matrix of characters `box` representing a side-view of a box. Each cell of the box is one of the following:
* A stone `'#'`
* A stationary obstacle `'*'`
* Empt... |
1,870 | minimum-speed-to-arrive-on-time | Minimum Speed to Arrive on Time | Medium | You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
E... |
```java
public int minSpeedOnTime(int[] dist, double hour) {
double max_time = hour - dist.length + 1;
double lower = 1.0, upper = 1e7;
while (upper - lower >= 1e-9) {
double mid = (lower + upper) / 2;
double time_taken = 0.0;
for (int i = 0; i < dist.length; ++i) {
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also... |
1,772 | sort-features-by-popularity | Sort Features by Popularity | Medium | You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users have reported which features they like. You are given a string array `responses`, where each `responses[i]` is a string containi... |
```java
import java.util.TreeSet;
class Solution {
final int MOD = 1000000007;
public int createSortedArray(int[] instructions) {
TreeSet<Integer> set = new TreeSet<>();
int cost = 0;
for (int i : instructions) {
set.add(i);
int less_than = set.headSet... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a string array `features` where `features[i]` is a single word that represents the name of a feature of the latest product you are working on. You have made a survey where users ... |
939 | minimum-area-rectangle | Minimum Area Rectangle | Medium | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
**Example 1:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]... |
```java
public int findValidPermutations(String s) {
int n = s.length();
long[] dp = new long[n + 2];
dp[0] = 1;
int MOD = 1000000007;
for (char c : s.toCharArray()) {
long[] new_dp = new long[n + 2];
if (c == 'I') {
for (int i = 0; i < n; ++i) {
new... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and... |
2,338 | count-the-number-of-ideal-arrays | Count the Number of Ideal Arrays | Hard | You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.
A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold:
* Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`.
* Every `arr[i]` is divisible by `arr[i - ... |
```java
public int numOfArrays(int n, int maxValue) {
final int mod = 1_000_000_007;
int[] dp = new int[maxValue + 1];
for (int i = 1; i <= maxValue; i++) {
dp[i] = i;
}
for (int i = 1; i < n; i++) {
for (int j = maxValue; j > 0; j--) {
dp[j] = (dp[j] + dp[... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array.
A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following condit... |
1,682 | longest-palindromic-subsequence-ii | Longest Palindromic Subsequence II | Medium | A subsequence of a string `s` is considered a **good palindromic subsequence** if:
* It is a subsequence of `s`.
* It is a palindrome (has the same value if reversed).
* It has an **even** length.
* No two consecutive characters are equal, except the two middle ones.
For example, if `s = "abcabcabb "`, then `... |
```java
import java.util.*;
public List<Integer> mostVisited(int n, int[] rounds) {
int[] visited = new int[n + 1];
for (int i = 1; i < rounds.length; ++i) {
for (int start = rounds[i - 1], end = rounds[i]; start != end; start = start % n + 1) {
++visited[start];
}
}
++... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
A subsequence of a string `s` is considered a **good palindromic subsequence** if:
* It is a subsequence of `s`.
* It is a palindrome (has the same value if reversed).
* It has an **eve... |
503 | next-greater-element-ii | Next Greater Element II | Medium | Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circu... |
```java
import java.util.Stack;
public int[] nextGreaterElements(int[] nums) {
int n = nums.length;
int[] result = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n * 2; i++) {
int index = i % n;
while (!stack.isEmpty() && nums[stack.peek()] < nums[index]... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater nu... |
2,536 | increment-submatrices-by-one | Increment Submatrices by One | Medium | You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For each `query[i] = [row1i, col1i, row2i, col2i]`, you should do the following operation:
* Add `1` to **every element** in the su... |
```java
import java.util.*;
public int[][] applyQueries(int n, int[][] queries) {
int[][] mat = new int[n][n];
for (int[] query : queries) {
for (int i = query[0]; i <= query[2]; i++) {
for (int j = query[1]; j <= query[3]; j++) {
mat[i][j]++;
}
}
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a positive integer `n`, indicating that we initially have an `n x n` **0-indexed** integer matrix `mat` filled with zeroes.
You are also given a 2D integer array `query`. For ea... |
2,185 | counting-words-with-a-given-prefix | Counting Words With a Given Prefix | Easy | You are given an array of strings `words` and a string `pref`.
Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
A **prefix** of a string `s` is any leading contiguous substring of `s`.
**Example 1:**
**Input:** words = \[ "pay ", "**at**tention ", "practice ", "**at**tend "\], `pre... |
```java
public int count_prefixes(String[] words, String pref) {
int count = 0;
for(String word : words) {
if(word.startsWith(pref)) {
count++;
}
}
return count;
}
```
The algorithm iterates through the list of words and checks if the word starts with the given ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array of strings `words` and a string `pref`.
Return _the number of strings in_ `words` _that contain_ `pref` _as a **prefix**_.
A **prefix** of a string `s` is any leading ... |
1,668 | maximum-repeating-substring | Maximum Repeating Substring | Easy | For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value `k` where `word` is `k`\-repeating in `sequence`. If `word` is not a substring of `sequence`, `word`'s maximum `k`\-repeating v... |
```java
int longestAwesomeSubstring(String s) {
int n = s.length();
int maxLen = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j <= n; ++j) {
String substr = s.substring(i, j);
if (isAwesome(substr)) {
maxLen = Math.max(maxLen, j - i);
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
For a string `sequence`, a string `word` is **`k`\-repeating** if `word` concatenated `k` times is a substring of `sequence`. The `word`'s **maximum `k`\-repeating value** is the highest value... |
1,258 | synonymous-sentences | Synonymous Sentences | Medium | You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`.
Return _all possible synonymous sentences **sorted lexicographically**_.
**Example 1:**
**Input:** synonyms = \[\[ "happy ", "joy "\],\[... |
```java
import java.util.*;
public List<String> generateSentences(List<List<String>> synonyms, String text) {
Map<String, Set<String>> synonymMap = new HashMap<>();
for (List<String> synPair : synonyms) {
synonymMap.putIfAbsent(synPair.get(0), new HashSet<>());
synonymMap.putIfAbsent(synP... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a list of equivalent string pairs `synonyms` where `synonyms[i] = [si, ti]` indicates that `si` and `ti` are equivalent strings. You are also given a sentence `text`.
Return _al... |
1,673 | find-the-most-competitive-subsequence | Find the Most Competitive Subsequence | Medium | Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.
We define that a subsequence `a` is more **competitive** than a subsequence ... |
```java
import java.util.Stack;
public int[] mostCompetitive(int[] nums, int k) {
Stack<Integer> stack = new Stack<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
while (!stack.empty() && stack.peek() > nums[i] && stack.size() + n - i > k) {
stack.pop();
}
i... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`.
An array's subsequence is a resulting sequence obtained by era... |
2,156 | find-substring-with-given-hash-value | Find Substring With Given Hash Value | Hard | The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:
* `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m`.
Where `val(s[i])` represents the index of `s[i]` in the alphabet from `val('a') = 1` to `val('z') = 26`.... |
```java
public boolean aliceWins(int[] stones) {
int sum = 0, count[] = new int[3];
for (int stone : stones) {
sum += stone;
count[stone % 3]++;
}
if (sum % 3 != 0) {
return count[sum % 3] % 2 == 1;
}
return count[1] % 2 == 0 || count[2] % 2 == 0 || count[1] == 0 || ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
The hash of a **0-indexed** string `s` of length `k`, given integers `p` and `m`, is computed using the following function:
* `hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s... |
694 | number-of-distinct-islands | Number of Distinct Islands | Medium | You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
An island is considered to be the same as another if and only if one island can be translated (and ... |
```java
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Collections;
public int numDistinctIslands(int[][] grid) {
HashSet<ArrayList<ArrayList<Integer>>> uniqueIslands = new HashSet<>();
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the gr... |
1,660 | correct-a-binary-tree | Correct a Binary Tree | Medium | You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's right**.
Given the root of the binary tree with this defect, `root`, return _the root of the binary tree after **removing** this i... |
```java
public String thousandSeparator(int n) {
String result = Integer.toString(n);
int count = 0;
for (int i = result.length() - 1; i > 0; --i) {
count++;
if (count % 3 == 0) {
result = result.substring(0, i) + "." + result.substring(i);
}
}
return result;... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You have a binary tree with a small defect. There is **exactly one** invalid node where its right child incorrectly points to another node at the **same depth** but to the **invalid node's rig... |
1,268 | search-suggestions-system | Search Suggestions System | Medium | You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed. Suggested products should have common prefix with `searchWord`. If there are more than three products with a common prefix ret... |
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public List<List<String>> suggestedProducts(String[] products, String searchWord) {
List<List<String>> result = new ArrayList<>();
Arrays.sort(products);
for (int i = 0; i < searchWord.length(); ++i) {
Lis... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array of strings `products` and a string `searchWord`.
Design a system that suggests at most three product names from `products` after each character of `searchWord` is typed... |
1,697 | checking-existence-of-edge-length-limited-paths | Checking Existence of Edge Length Limited Paths | Hard | An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for e... |
```java
import java.util.*;
public class Solution {
public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {
Map<Integer, List<int[]>> graph = new HashMap<>();
for (int[] edge : edgeList) {
graph.putIfAbsent(edge[0], new ArrayList<>());
gr... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multi... |
2,503 | maximum-number-of-points-from-grid-queries | Maximum Number of Points From Grid Queries | Hard | You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cell of the matrix and repeat the following process:
* If `queries[i]` is **strictly** greater than the value of the current cel... |
```java
import java.util.*;
public List<Integer> maxPoints(int[][] grid, int[] queries) {
int m = grid.length;
int n = grid[0].length;
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
List<Integer> result = new ArrayList<>();
for (int query : queries) {
int points = 0;
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`.
Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the **top left** cel... |
2,322 | minimum-score-after-removals-on-a-tree | Minimum Score After Removals on a Tree | Hard | There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indica... |
```java
import java.util.ArrayList;
import java.util.List;
public int dfs(int node, int parent, int[] xor_values, List<Integer>[] tree) {
int xor_value = xor_values[node];
for (int child : tree[node]) {
if (child != parent) {
xor_value ^= dfs(child, node, xor_values, tree);
}
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges.
You are given a **0-indexed** integer array `nums` of length `n` where `nums[i]` represents... |
2,243 | calculate-digit-sum-of-a-string | Calculate Digit Sum of a String | Easy | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... |
```java
boolean isAOnlyBeforeB(String s) {
int lastIndexA = -1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'a') {
lastIndexA = i;
} else if (s.charAt(i) == 'b' && lastIndexA > -1) {
return false;
}
}
return true;
}
```
The algo... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` ... |
988 | smallest-string-starting-from-leaf | Smallest String Starting From Leaf | Medium | You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.
As a reminder, any shorter prefix of a string is **lexicographically smaller... |
```java
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public boolean flipEquiv... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.
Return _the **lexicographically smallest** string that st... |
1,655 | distribute-repeating-integers | Distribute Repeating Integers | Hard | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that:
* Th... |
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public boolean canDistribute(int[] nums, int[] quantity) {
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
counts.put(num, counts.getOrDef... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quanti... |
850 | rectangle-area-ii | Rectangle Area II | Hard | You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**.
Calculate the **total area** covered by all `rectangles` ... |
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public int rectangleArea(int[][] rectangles) {
final int mod = 1000000007;
int n = rectangles.length;
Set<Integer> X = new HashSet<>();
Set<Integer> Y = new HashSet<>();
for (int[] rect : rectangles) {
X.a... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner... |
2,423 | remove-letter-to-equalize-frequency | Remove Letter To Equalize Frequency | Easy | You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequency** of every letter present in `word` is equal.
Return `true` _if it is possible to remove one letter so that the frequency of... |
```java
import java.util.HashMap;
public boolean canEqualFrequency(String word) {
HashMap<Character, Integer> freq = new HashMap<>();
for (char c : word.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
HashMap<Integer, Integer> count_freq = new HashMap<>();
for (int f : fr... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a **0-indexed** string `word`, consisting of lowercase English letters. You need to select **one** index and **remove** the letter at that index from `word` so that the **frequen... |
2,285 | maximum-total-importance-of-roads | Maximum Total Importance of Roads | Medium | You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]` denotes that there exists a **bidirectional** road connecting cities `ai` and `bi`.
You need to assign each city with an integ... |
```java
class BitSet {
private int[] bits;
public BitSet(int size) {
bits = new int[(size + 31) / 32];
}
public void set(int index) {
bits[index / 32] |= (1 << (index % 32));
}
public boolean get(int index) {
return (bits[index / 32] & (1 << (index % 32))) !... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an integer `n` denoting the number of cities in a country. The cities are numbered from `0` to `n - 1`.
You are also given a 2D integer array `roads` where `roads[i] = [ai, bi]`... |
728 | self-dividing-numbers | Self Dividing Numbers | Easy | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... |
```java
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static boolean isSelfDividing(int num) {
int n = num;
while (n != 0) {
int digit = n % 10;
if (digit == 0 || num % digit != 0)
return false;
n /= 10;
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 ... |
1,005 | maximize-sum-of-array-after-k-negations | Maximize Sum Of Array After K Negations | Easy | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it i... |
```java
public boolean isUnivalued(TreeNode root) {
return isUnivalued(root, -1);
}
private boolean isUnivalued(TreeNode root, int val) {
if (root == null) return true;
if (val == -1) val = root.val;
return root.val == val && isUnivalued(root.left, val) && isUnivalued(root.right, val);
}
```
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly ... |
1,753 | maximum-score-from-removing-stones | Maximum Score From Removing Stones | Medium | You are playing a solitaire game with **three piles** of stones of sizes `a`ββββββ, `b`,ββββββ and `c`ββββββ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there ar... |
```java
import java.util.PriorityQueue;
class Solution {
private int[][] directions = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
public int minimumEffortPath(int[][] heights) {
int rows = heights.length;
int cols = heights[0].length;
int[][] efforts = new int[rows][cols];
for... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are playing a solitaire game with **three piles** of stones of sizes `a`ββββββ, `b`,ββββββ and `c`ββββββ respectively. Each turn you choose two **different non-empty** piles, take one ston... |
438 | find-all-anagrams-in-a-string | Find All Anagrams in a String | Medium | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
*... |
```java
import java.util.List;
import java.util.ArrayList;
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
if (s.length() < p.length()) return result;
int[] s_count = new int[26];
int[] p_count = new int[26];
for (char c : p.toCharArray()) p_c... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by ... |
82 | remove-duplicates-from-sorted-list-ii | Remove Duplicates from Sorted List II | Medium | Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
**Example 1:**
**Input:** head = \[1,2,3,3,4,4,5\]
**Output:** \[1,2,5\]
**Example 2:**
**Input:** head = \[1,1,1,2,3\]
**Outpu... |
```java
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy, curr = head;
while (curr != null) {
while (curr.next != null && curr.val... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_.
###... |
374 | guess-number-higher-or-lower | Guess Number Higher or Lower | Easy | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible re... |
```java
public int guessNumber(int n) {
int low = 1, high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
int result = guess(mid);
if (result == 0) {
return mid;
} else if (result < 0) {
high = mid - 1;
} else {
low = ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the numbe... |
1,814 | count-nice-pairs-in-an-array | Count Nice Pairs in an Array | Medium | You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions:
* `0 <= i < j < nums.length`
* `nu... |
```java
public int maxResult(int[] nums, int k) {
int n = nums.length;
Deque<Integer> dq = new ArrayDeque<>();
int[] dp = new int[n];
dp[0] = nums[0];
dq.offerLast(0);
for (int i = 1; i < n; i++) {
while (!dq.isEmpty() && dq.peekFirst() < i - k) {
dq.pollFirst(... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`.... |
322 | coin-change | Coin Change | Medium | You 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 a... |
```java
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
return dp[amount]... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You 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 ... |
1,560 | most-visited-sector-in-a-circular-track | Most Visited Sector in a Circular Track | Easy | Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at ... |
```java
public int busyStudent(int[] startTime, int[] endTime, int queryTime) {
int count = 0;
for (int i = 0; i < startTime.length; i++) {
if (startTime[i] <= queryTime && endTime[i] >= queryTime) {
count++;
}
}
return count;
}
```
The algorithm consists of ite... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists... |
2,018 | check-if-word-can-be-placed-in-crossword | Check if Word Can Be Placed In Crossword | Medium | You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any **empty** cells, and `'#'` to represent any **blocked** cells.
A word can be placed **horizontally** (left to right **or** righ... |
```java
import java.util.Arrays;
class Solution {
public int minWastedSpace(int[] packages, int[][] boxes) {
final int MOD = 1_000_000_007;
Arrays.sort(packages);
long total_package_size = 0;
for (int package_size : packages) {
total_package_size += package_size;
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an `m x n` matrix `board`, representing the **current** state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), `' '` to represent any ... |
937 | reorder-data-in-log-files | Reorder Data in Log Files | Medium | You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (except the identifier) consist of lowercase English letters.
* **Digit-logs**: All words (except the identifier) consist of digits... |
```java
import java.util.Stack;
class StockSpanner {
private final Stack<Integer> indexStack;
private final List<Integer> prices;
public StockSpanner() {
indexStack = new Stack<>();
prices = new ArrayList<>();
}
public int next(int price) {
while (!indexStack.isEmpty(... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**.
There are two types of logs:
* **Letter-logs**: All words (exce... |
897 | increasing-order-search-tree | Increasing Order Search Tree | Easy | 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:**
**Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\]
**Output:** \[1,null,2,null,3,null,4,nul... |
```java
boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
boolean isPalindrome(int n) {
int rev = 0, orig = n;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return orig ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
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 ri... |
312 | burst-balloons | Burst Balloons | Hard | You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the `ith` balloon, you will get `nums[i - 1] * nums[i] * nums[i + 1]` coins. If `i - 1` or `i + 1` goes out of bounds of the array, ... |
```java
public int maxCoins(int[] nums) {
int n = nums.length;
int[] newNums = new int[n + 2];
newNums[0] = 1;
newNums[n + 1] = 1;
for (int i = 1; i <= n; i++) {
newNums[i] = nums[i - 1];
}
int[][] dp = new int[n + 2][n + 2];
for (int len = 1; len <= n; len++) {
for... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given `n` balloons, indexed from `0` to `n - 1`. Each balloon is painted with a number on it represented by an array `nums`. You are asked to burst all the balloons.
If you burst the ... |
1,461 | check-if-a-string-contains-all-binary-codes-of-size-k | Check If a String Contains All Binary Codes of Size K | Medium | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all f... |
```java
int countOrders(int n) {
long MOD = 1000000007;
long ans = 1;
for (int i = 1; i <= n; ++i) {
ans = ans * (2 * i - 1) * i % MOD;
}
return (int) ans;
}
```
We need to arrange n pickup and n delivery services in a valid order. For the first order, we have 1 pickup and 1 de... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
### Solution
```java
import java.ut... |
1,732 | find-the-highest-altitude | Find the Highest Altitude | Easy | There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`ββββββ and `i + 1` for all (`0 <=... |
```java
int minOperations(int n) {
int operations = 0;
while (n > 0) {
if (n % 2 == 0) {
n /= 2;
} else {
n--;
}
operations++;
}
return operations;
}
```
The algorithm initializes a variable `operations` to store the number of operati... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`.
You are given an intege... |
272 | closest-binary-search-tree-value-ii | Closest Binary Search Tree Value II | Hard | Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**.
You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`.
**Example 1:*... |
```java
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
public List<Integer> closestKValues(TreeNode root, double target, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> Double.comp... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order*... |
348 | design-tic-tac-toe | Design Tic-Tac-Toe | Medium | Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players:
1. A move is guaranteed to be valid and is placed on an empty block.
2. Once a winning condition is reached, no more moves are allowed.
3. A player who succeeds in placing `n` of their marks in a horizontal, vertical, o... |
```java
class TicTacToe {
int[] rows, cols;
int diagonal, anti_diagonal, n;
public TicTacToe(int n) {
this.n = n;
rows = new int[n];
cols = new int[n];
diagonal = 0;
anti_diagonal = 0;
}
public int move(int row, int col, int player) {
int toAdd ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Assume the following rules are for the tic-tac-toe game on an `n x n` board between two players:
1. A move is guaranteed to be valid and is placed on an empty block.
2. Once a winning condi... |
682 | baseball-game | Baseball Game | Easy | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... |
```java
import java.util.*;
class Solution {
public int calPoints(String[] ops) {
LinkedList<Integer> record = new LinkedList<>();
for (String op : ops) {
if (op.equals("+")) {
record.add(record.getLast() + record.get(record.size() - 2));
} else if (op.e... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operation... |
2,387 | median-of-a-row-wise-sorted-matrix | Median of a Row Wise Sorted Matrix | Medium | Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_.
You must solve the problem in less than `O(m * n)` time complexity.
**Example 1:**
**Input:** grid = \[\[1,1,2\],\[2,3,3\],\[1,3,4\]\]
**Output:** 2
**E... |
```java
public int findMedian(int[][] grid) {
int m = grid.length, n = grid[0].length;
int low = 1, high = 1000000;
while (low < high) {
int mid = low + (high - low) / 2;
int count = 0;
for (int i = 0; i < m; ++i) {
count += countElements(grid[i], mid);
}
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given an `m x n` matrix `grid` containing an **odd** number of integers where each row is sorted in **non-decreasing** order, return _the **median** of the matrix_.
You must solve the problem... |
1,237 | find-positive-integer-solution-for-a-given-equation | Find Positive Integer Solution for a Given Equation | Medium | Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
* `f(x, y... |
```java
import java.util.ArrayList;
import java.util.List;
public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
List<List<Integer>> results = new ArrayList<>();
for (int x = 1; x <= 1000; x++) {
for (int y = 1; y <= 1000; y++) {
if (customfunction.f(x, y) == ... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given a callable function `f(x, y)` **with a hidden formula** and a value `z`, reverse engineer the formula and return _all positive integer pairs_ `x` _and_ `y` _where_ `f(x,y) == z`. You may... |
2,366 | minimum-replacements-to-sort-the-array | Minimum Replacements to Sort the Array | Hard | You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [5,6,7]`. In one operation, we can replace `nums[1]` with `2` and `4` and convert `nums` to `[5,2,4,7]`.
Return _the minimum num... |
```java
public int minOperations(int[] nums) {
int operations = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] <= nums[i - 1]) {
int diff = nums[i - 1] - nums[i] + 1;
operations += Math.ceil(Math.log(diff) / Math.log(2));
nums[i] += diff;
}
}
... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a **0-indexed** integer array `nums`. In one operation you can replace any element of the array with **any two** elements that **sum** to it.
* For example, consider `nums = [... |
409 | longest-palindrome | Longest Palindrome | Easy | Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters.
Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here.
**Example 1:**
**Input:** s = "abccccdd "
**Output:** 7
**Explanation... |
```java
public int longestPalindrome(String s) {
int[] charCount = new int[128];
int result = 0;
for (char c : s.toCharArray())
charCount[c]++;
for (int count : charCount) {
result += count / 2 * 2;
if (result % 2 == 0 && count % 2 == 1)
result++;
}
retur... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters.
Letters are **case sensitive**, fo... |
2,146 | k-highest-ranked-items-within-a-price-range | K Highest Ranked Items Within a Price Range | Medium | You are given a **0-indexed** 2D integer array `grid` of size `m x n` that represents a map of the items in a shop. The integers in the grid represent the following:
* `0` represents a wall that you cannot pass through.
* `1` represents an empty cell that you can freely move to and from.
* All other positive int... |
```java
public boolean canPlaceWord(char[][] board, String word) {
int m = board.length, n = board[0].length;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == word.charAt(0)) {
if (checkWord(board, word, i, j, 0, 1) || checkWord(board, word,... | Write only the code. Do not include explanations, markdown text, or reasoning outside the code block.
Solve the following task:
You are given a **0-indexed** 2D integer array `grid` of size `m x n` that represents a map of the items in a shop. The integers in the grid represent the following:
* `0` represents a wall... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 141