diff --git a/.github/workflows/daily_download.yml b/.github/workflows/daily_download.yml
index 7331073..6699a98 100644
--- a/.github/workflows/daily_download.yml
+++ b/.github/workflows/daily_download.yml
@@ -23,7 +23,7 @@ jobs:
- name: Run download.py
env:
GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}
- run: python src/utils/download.py
+ run: python -m src.utils.download
- name: Commit and Push changes
run: |
diff --git a/README.md b/README.md
index 18be006..d3702d3 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,18 @@
-# LeetCode API
+# LeetCode API / LeetCode Sorted
[](https://leetcode-api-pied.vercel.app) [](https://fastapi.tiangolo.com) [](LICENSE)
*"Yet Another LeetCode API" - Because why reinvent the wheel? (But we did anyway ๐ ๏ธ)*
## ๐ Core Services
+
- **Live Demo**: [leetcode-api-pied.vercel.app](https://leetcode-api-pied.vercel.app)
-- **Interactive Docs**: [docs.leetcode-api.vercel.app](https://leetcode-api-pied.vercel.app/docs)
-- **Google Sheet Integration**: [View Sheet](https://docs.google.com/spreadsheets/d/1sRWp95wqo3a7lLBbtNd_3KkTyGjx_9sctTOL5JOb6pA/edit?usp=sharing)
+- **Interactive Docs**: [leetcode-api-pied.vercel.app/docs](https://leetcode-api-pied.vercel.app/docs)
+- **Google Sheet**: [View Sheet](https://docs.google.com/spreadsheets/d/1sRWp95wqo3a7lLBbtNd_3KkTyGjx_9sctTOL5JOb6pA/edit?usp=sharing)
*(Daily updated LeetCode question database with sorting/filtering)*
-A no-nonsense LeetCode API service for developers who want LeetCode data without the scraping headaches. Perfect for:
-- Building coding portfolios ๐ผ๏ธ
-- Tracking practice stats ๐
-- Creating LeetCode-powered apps ๐ป
-- Just messing around with API endpoints ๐คน
+ **Enable Filtering/Sorting:**
+ 1. Select **Row 3**.
+ 2. Go to **Data > Filter views > Create new filter view**.
## โก Quick Start
@@ -21,7 +20,8 @@ A no-nonsense LeetCode API service for developers who want LeetCode data without
# Get today's daily challenge
curl https://leetcode-api-pied.vercel.app/daily
-# Find a question by ID/slug
+# Find a problem by ID/slug
+curl https://leetcode-api-pied.vercel.app/problem/1
curl https://leetcode-api-pied.vercel.app/problem/two-sum
# Get user profile (try your LeetCode username!)
@@ -33,8 +33,9 @@ curl https://leetcode-api-pied.vercel.app/user/lee215
| Endpoint | Method | Description | Example |
|---------------------------------|--------|-------------------------------------|---------------------------------------------------------------------------------------------|
| `/problems` | GET | All LeetCode problems | [/problems](https://leetcode-api-pied.vercel.app/problems) |
-| `/problem/{id_or_slug}` | GET | Get problem by ID/slug | [/problem/two-sum](https://leetcode-api-pied.vercel.app/problem/two-sum) |
-| `/problems/{topic}` | GET | Problems by topic (arrays, DP, etc) | [/problems/array](https://leetcode-api-pied.vercel.app/problems/array) |
+| `/problem/{id_or_slug}` | GET | Get problem by ID/slug | [/problem/1](https://leetcode-api-pied.vercel.app/problem/1)
[/problem/two-sum](https://leetcode-api-pied.vercel.app/problem/two-sum) |
+| `/search/{query}` | GET | Search for problems | [/search?query=two%20sum](https://leetcode-api-pied.vercel.app/search?query=two%20sum) |
+| `/random` | GET | Random LeetCode problem | [/random](https://leetcode-api-pied.vercel.app/random) |
| `/user/{username}` | GET | User profile & stats | [/user/lee215](https://leetcode-api-pied.vercel.app/user/lee215) |
| `/user/{username}/contests` | GET | User's recent contests | [/user/lee215/contests](https://leetcode-api-pied.vercel.app/user/lee215/contests) |
| `/user/{username}/submissions` | GET | User's recent submissions | [/user/lee215/submissions](https://leetcode-api-pied.vercel.app/user/lee215/submissions) |
@@ -78,16 +79,16 @@ or download `leetcode_questions.json`(updated daily) directly from the `data` f
## ๐ค Why This API?
- Always Fresh Data ๐ฅฌ
-Auto-updating cache system (no stale LeetCode questions!)
+ Auto-updating cache system (no stale LeetCode questions!)
- Vercel-Ready โก
-One-click deployment with serverless architecture
+ One-click deployment with serverless architecture
- No API Keys ๐
-Free to use with sensible rate limits
+ Free to use with sensible rate limits
- Real LeetCode Data ๐ฅ
-Direct integration with LeetCode's GraphQL API
+ Direct integration with LeetCode's GraphQL API
---
diff --git a/data/leetcode_questions.json b/data/leetcode_questions.json
index d3837f4..697a128 100644
--- a/data/leetcode_questions.json
+++ b/data/leetcode_questions.json
@@ -6,9 +6,9 @@
"questionFrontendId": "1",
"title": "Two Sum",
"content": "
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
\n\nYou can return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,4], target = 6\nOutput: [1,2]\n\n\n
Example 3:
\n\n\nInput: nums = [3,3], target = 6\nOutput: [0,1]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
\nFollow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?",
- "likes": 60190,
- "dislikes": 2156,
- "stats": "{\"totalAccepted\": \"16.1M\", \"totalSubmission\": \"29.3M\", \"totalAcceptedRaw\": 16080681, \"totalSubmissionRaw\": 29317023, \"acRate\": \"54.9%\"}",
+ "likes": 62073,
+ "dislikes": 2248,
+ "stats": "{\"totalAccepted\": \"17.5M\", \"totalSubmission\": \"31.4M\", \"totalAcceptedRaw\": 17489997, \"totalSubmissionRaw\": 31371096, \"acRate\": \"55.8%\"}",
"similarQuestions": "[{\"title\": \"3Sum\", \"titleSlug\": \"3sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"4Sum\", \"titleSlug\": \"4sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum II - Input Array Is Sorted\", \"titleSlug\": \"two-sum-ii-input-array-is-sorted\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum III - Data structure design\", \"titleSlug\": \"two-sum-iii-data-structure-design\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum IV - Input is a BST\", \"titleSlug\": \"two-sum-iv-input-is-a-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Two Sum Less Than K\", \"titleSlug\": \"two-sum-less-than-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Max Number of K-Sum Pairs\", \"titleSlug\": \"max-number-of-k-sum-pairs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Good Meals\", \"titleSlug\": \"count-good-meals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Number of Pairs With Absolute Difference K\", \"titleSlug\": \"count-number-of-pairs-with-absolute-difference-k\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Pairs of Strings With Concatenation Equal to Target\", \"titleSlug\": \"number-of-pairs-of-strings-with-concatenation-equal-to-target\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All K-Distant Indices in an Array\", \"titleSlug\": \"find-all-k-distant-indices-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"First Letter to Appear Twice\", \"titleSlug\": \"first-letter-to-appear-twice\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Excellent Pairs\", \"titleSlug\": \"number-of-excellent-pairs\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Arithmetic Triplets\", \"titleSlug\": \"number-of-arithmetic-triplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Node With Highest Edge Score\", \"titleSlug\": \"node-with-highest-edge-score\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check Distances Between Same Letters\", \"titleSlug\": \"check-distances-between-same-letters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Subarrays With Equal Sum\", \"titleSlug\": \"find-subarrays-with-equal-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Largest Positive Integer That Exists With Its Negative\", \"titleSlug\": \"largest-positive-integer-that-exists-with-its-negative\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Distinct Averages\", \"titleSlug\": \"number-of-distinct-averages\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Pairs Whose Sum is Less than Target\", \"titleSlug\": \"count-pairs-whose-sum-is-less-than-target\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [
@@ -44,9 +44,9 @@
"questionFrontendId": "2",
"title": "Add Two Numbers",
"content": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.
\n\n\n
Example 1:
\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [7,0,8]\nExplanation: 342 + 465 = 807.\n\n\n
Example 2:
\n\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\n
Example 3:
\n\n\nInput: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput: [8,9,9,9,0,0,0,1]\n\n\n
\n
Constraints:
\n\n[1, 100]
.0 <= Node.val <= 9
Given a string s
, find the length of the longest substring without repeating characters.
\n
Example 1:
\n\n\nInput: s = "abcabcbb"\nOutput: 3\nExplanation: The answer is "abc", with the length of 3.\n\n\n
Example 2:
\n\n\nInput: s = "bbbbb"\nOutput: 1\nExplanation: The answer is "b", with the length of 1.\n\n\n
Example 3:
\n\n\nInput: s = "pwwkew"\nOutput: 3\nExplanation: The answer is "wke", with the length of 3.\nNotice that the answer must be a substring, "pwke" is a subsequence and not a substring.\n\n\n
\n
Constraints:
\n\n0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.Given a string s
, find the length of the longest substring without duplicate characters.
\n
Example 1:
\n\n\nInput: s = "abcabcbb"\nOutput: 3\nExplanation: The answer is "abc", with the length of 3.\n\n\n
Example 2:
\n\n\nInput: s = "bbbbb"\nOutput: 1\nExplanation: The answer is "b", with the length of 1.\n\n\n
Example 3:
\n\n\nInput: s = "pwwkew"\nOutput: 3\nExplanation: The answer is "wke", with the length of 3.\nNotice that the answer must be a substring, "pwke" is a subsequence and not a substring.\n\n\n
\n
Constraints:
\n\n0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n))
.
\n
Example 1:
\n\n\nInput: nums1 = [1,3], nums2 = [2]\nOutput: 2.00000\nExplanation: merged array = [1,2,3] and median is 2.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 2.50000\nExplanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n\n\n
\n
Constraints:
\n\nnums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
Given a string s
, return the longest palindromic substring in s
.
\n
Example 1:
\n\n\nInput: s = "babad"\nOutput: "bab"\nExplanation: "aba" is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: s = "cbbd"\nOutput: "bb"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consist of only digits and English letters.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)
\nP A H N\nA P L S I I G\nY I R\n\n\n
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
\n\n\nstring convert(string s, int numRows);\n\n\n
\n
Example 1:
\n\n\nInput: s = "PAYPALISHIRING", numRows = 3\nOutput: "PAHNAPLSIIGYIR"\n\n\n
Example 2:
\n\n\nInput: s = "PAYPALISHIRING", numRows = 4\nOutput: "PINALSIGYAHRPI"\nExplanation:\nP I N\nA L S I G\nY A H R\nP I\n\n\n
Example 3:
\n\n\nInput: s = "A", numRows = 1\nOutput: "A"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case), ','
and '.'
.1 <= numRows <= 1000
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
\n\n\n
Example 1:
\n\n\nInput: x = 123\nOutput: 321\n\n\n
Example 2:
\n\n\nInput: x = -123\nOutput: -321\n\n\n
Example 3:
\n\n\nInput: x = 120\nOutput: 21\n\n\n
\n
Constraints:
\n\n-231 <= x <= 231 - 1
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s)
is as follows:
" "
).'-'
or '+'
, assuming positivity if neither present.[-231, 231 - 1]
, then round the integer to remain in the range. Specifically, integers less than -231
should be rounded to -231
, and integers greater than 231 - 1
should be rounded to 231 - 1
.Return the integer as the final result.
\n\n\n
Example 1:
\n\nInput: s = "42"
\n\nOutput: 42
\n\nExplanation:
\n\n\nThe underlined characters are what is read in and the caret is the current reader position.\nStep 1: "42" (no characters read because there is no leading whitespace)\n ^\nStep 2: "42" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: "42" ("42" is read in)\n ^\n\n
Example 2:
\n\nInput: s = " -042"
\n\nOutput: -42
\n\nExplanation:
\n\n\nStep 1: " -042" (leading whitespace is read and ignored)\n ^\nStep 2: " -042" ('-' is read, so the result should be negative)\n ^\nStep 3: " -042" ("042" is read in, leading zeros ignored in the result)\n ^\n\n
Example 3:
\n\nInput: s = "1337c0d3"
\n\nOutput: 1337
\n\nExplanation:
\n\n\nStep 1: "1337c0d3" (no characters read because there is no leading whitespace)\n ^\nStep 2: "1337c0d3" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: "1337c0d3" ("1337" is read in; reading stops because the next character is a non-digit)\n ^\n\n
Example 4:
\n\nInput: s = "0-1"
\n\nOutput: 0
\n\nExplanation:
\n\n\nStep 1: "0-1" (no characters read because there is no leading whitespace)\n ^\nStep 2: "0-1" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: "0-1" ("0" is read in; reading stops because the next character is a non-digit)\n ^\n\n
Example 5:
\n\nInput: s = "words and 987"
\n\nOutput: 0
\n\nExplanation:
\n\nReading stops at the first non-digit character 'w'.
\n\n
Constraints:
\n\n0 <= s.length <= 200
s
consists of English letters (lower-case and upper-case), digits (0-9
), ' '
, '+'
, '-'
, and '.'
.Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
\n
Example 1:
\n\n\nInput: x = 121\nOutput: true\nExplanation: 121 reads as 121 from left to right and from right to left.\n\n\n
Example 2:
\n\n\nInput: x = -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n\n\n
Example 3:
\n\n\nInput: x = 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n\n\n
\n
Constraints:
\n\n-231 <= x <= 231 - 1
\nFollow up: Could you solve it without converting the integer to a string?", - "likes": 13575, - "dislikes": 2801, - "stats": "{\"totalAccepted\": \"5.9M\", \"totalSubmission\": \"10M\", \"totalAcceptedRaw\": 5864447, \"totalSubmissionRaw\": 10030922, \"acRate\": \"58.5%\"}", + "likes": 14074, + "dislikes": 2820, + "stats": "{\"totalAccepted\": \"6.4M\", \"totalSubmission\": \"10.9M\", \"totalAcceptedRaw\": 6437466, \"totalSubmissionRaw\": 10872991, \"acRate\": \"59.2%\"}", "similarQuestions": "[{\"title\": \"Palindrome Linked List\", \"titleSlug\": \"palindrome-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Palindrome With Fixed Length\", \"titleSlug\": \"find-palindrome-with-fixed-length\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Strictly Palindromic Number\", \"titleSlug\": \"strictly-palindromic-number\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \" Count Symmetric Integers\", \"titleSlug\": \"count-symmetric-integers\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Count of Good Integers\", \"titleSlug\": \"find-the-count-of-good-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find the Largest Palindrome Divisible by K\", \"titleSlug\": \"find-the-largest-palindrome-divisible-by-k\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -324,9 +324,9 @@ "questionFrontendId": "10", "title": "Regular Expression Matching", "content": "
Given an input string s
and a pattern p
, implement regular expression matching with support for '.'
and '*'
where:
'.'
Matches any single character.\u200b\u200b\u200b\u200b'*'
Matches zero or more of the preceding element.The matching should cover the entire input string (not partial).
\n\n\n
Example 1:
\n\n\nInput: s = "aa", p = "a"\nOutput: false\nExplanation: "a" does not match the entire string "aa".\n\n\n
Example 2:
\n\n\nInput: s = "aa", p = "a*"\nOutput: true\nExplanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".\n\n\n
Example 3:
\n\n\nInput: s = "ab", p = ".*"\nOutput: true\nExplanation: ".*" means "zero or more (*) of any character (.)".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 20
1 <= p.length <= 20
s
contains only lowercase English letters.p
contains only lowercase English letters, '.'
, and '*'
.'*'
, there will be a previous valid character to match.You are given an integer array height
of length n
. There are n
vertical lines drawn such that the two endpoints of the ith
line are (i, 0)
and (i, height[i])
.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
\n\nReturn the maximum amount of water a container can store.
\n\nNotice that you may not slant the container.
\n\n\n
Example 1:
\n\nInput: height = [1,8,6,2,5,4,8,3,7]\nOutput: 49\nExplanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.\n\n\n
Example 2:
\n\n\nInput: height = [1,1]\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == height.length
2 <= n <= 105
0 <= height[i] <= 104
Seven different symbols represent Roman numerals with the following values:
\n\nSymbol | \n\t\t\tValue | \n\t\t
---|---|
I | \n\t\t\t1 | \n\t\t
V | \n\t\t\t5 | \n\t\t
X | \n\t\t\t10 | \n\t\t
L | \n\t\t\t50 | \n\t\t
C | \n\t\t\t100 | \n\t\t
D | \n\t\t\t500 | \n\t\t
M | \n\t\t\t1000 | \n\t\t
Roman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:
\n\nI
) less than 5 (V
): IV
and 9 is 1 (I
) less than 10 (X
): IX
. Only the following subtractive forms are used: 4 (IV
), 9 (IX
), 40 (XL
), 90 (XC
), 400 (CD
) and 900 (CM
).I
, X
, C
, M
) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V
), 50 (L
), or 500 (D
) multiple times. If you need to append a symbol 4 times use the subtractive form.Given an integer, convert it to a Roman numeral.
\n\n\n
Example 1:
\n\nInput: num = 3749
\n\nOutput: "MMMDCCXLIX"
\n\nExplanation:
\n\n\n3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n 40 = XL as 10 (X) less of 50 (L)\n 9 = IX as 1 (I) less of 10 (X)\nNote: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places\n\n
Example 2:
\n\nInput: num = 58
\n\nOutput: "LVIII"
\n\nExplanation:
\n\n\n50 = L\n 8 = VIII\n\n
Example 3:
\n\nInput: num = 1994
\n\nOutput: "MCMXCIV"
\n\nExplanation:
\n\n\n1000 = M\n 900 = CM\n 90 = XC\n 4 = IV\n\n
\n
Constraints:
\n\n1 <= num <= 3999
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
\nSymbol Value\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000\n\n
For example, 2
is written as II
in Roman numeral, just two ones added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed before V
(5) and X
(10) to make 4 and 9. X
can be placed before L
(50) and C
(100) to make 40 and 90. C
can be placed before D
(500) and M
(1000) to make 400 and 900.Given a roman numeral, convert it to an integer.
\n\n\n
Example 1:
\n\n\nInput: s = "III"\nOutput: 3\nExplanation: III = 3.\n\n\n
Example 2:
\n\n\nInput: s = "LVIII"\nOutput: 58\nExplanation: L = 50, V= 5, III = 3.\n\n\n
Example 3:
\n\n\nInput: s = "MCMXCIV"\nOutput: 1994\nExplanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 15
s
contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
.s
is a valid roman numeral in the range [1, 3999]
.Write a function to find the longest common prefix string amongst an array of strings.
\n\nIf there is no common prefix, return an empty string ""
.
\n
Example 1:
\n\n\nInput: strs = ["flower","flow","flight"]\nOutput: "fl"\n\n\n
Example 2:
\n\n\nInput: strs = ["dog","racecar","car"]\nOutput: ""\nExplanation: There is no common prefix among the input strings.\n\n\n
\n
Constraints:
\n\n1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
consists of only lowercase English letters if it is non-empty.Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
\n\n\n
Example 1:
\n\n\nInput: nums = [-1,0,1,2,-1,-4]\nOutput: [[-1,-1,2],[-1,0,1]]\nExplanation: \nnums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\nnums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\nnums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\nThe distinct triplets are [-1,0,1] and [-1,-1,2].\nNotice that the order of the output and the order of the triplets does not matter.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,1]\nOutput: []\nExplanation: The only possible triplet does not sum up to 0.\n\n\n
Example 3:
\n\n\nInput: nums = [0,0,0]\nOutput: [[0,0,0]]\nExplanation: The only possible triplet sums up to 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 3000
-105 <= nums[i] <= 105
Given an integer array nums
of length n
and an integer target
, find three integers in nums
such that the sum is closest to target
.
Return the sum of the three integers.
\n\nYou may assume that each input would have exactly one solution.
\n\n\n
Example 1:
\n\n\nInput: nums = [-1,2,1,-4], target = 1\nOutput: 2\nExplanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,0], target = 1\nOutput: 0\nExplanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 500
-1000 <= nums[i] <= 1000
-104 <= target <= 104
Given 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.
\n\n
Example 1:
\n\n\nInput: digits = "23"\nOutput: ["ad","ae","af","bd","be","bf","cd","ce","cf"]\n\n\n
Example 2:
\n\n\nInput: digits = ""\nOutput: []\n\n\n
Example 3:
\n\n\nInput: digits = "2"\nOutput: ["a","b","c"]\n\n\n
\n
Constraints:
\n\n0 <= digits.length <= 4
digits[i]
is a digit in the range ['2', '9']
.Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
0 <= a, b, c, d < n
a
, b
, c
, and d
are distinct.nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,0,-1,0,-2,2], target = 0\nOutput: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2,2,2], target = 8\nOutput: [[2,2,2,2]]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5], n = 2\nOutput: [1,2,3,5]\n\n\n
Example 2:
\n\n\nInput: head = [1], n = 1\nOutput: []\n\n\n
Example 3:
\n\n\nInput: head = [1,2], n = 1\nOutput: [1]\n\n\n
\n
Constraints:
\n\nsz
.1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
\n
Follow up: Could you do this in one pass?
\n", - "likes": 19577, - "dislikes": 835, - "stats": "{\"totalAccepted\": \"3.2M\", \"totalSubmission\": \"6.8M\", \"totalAcceptedRaw\": 3241091, \"totalSubmissionRaw\": 6769903, \"acRate\": \"47.9%\"}", + "likes": 20041, + "dislikes": 857, + "stats": "{\"totalAccepted\": \"3.5M\", \"totalSubmission\": \"7.1M\", \"totalAcceptedRaw\": 3495135, \"totalSubmissionRaw\": 7144348, \"acRate\": \"48.9%\"}", "similarQuestions": "[{\"title\": \"Swapping Nodes in a Linked List\", \"titleSlug\": \"swapping-nodes-in-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Delete N Nodes After M Nodes of a Linked List\", \"titleSlug\": \"delete-n-nodes-after-m-nodes-of-a-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Delete the Middle Node of a Linked List\", \"titleSlug\": \"delete-the-middle-node-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -700,9 +700,9 @@ "questionFrontendId": "20", "title": "Valid Parentheses", "content": "Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
\n\n\n
Example 1:
\n\nInput: s = "()"
\n\nOutput: true
\nExample 2:
\n\nInput: s = "()[]{}"
\n\nOutput: true
\nExample 3:
\n\nInput: s = "(]"
\n\nOutput: false
\nExample 4:
\n\nInput: s = "([])"
\n\nOutput: true
\n\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of parentheses only '()[]{}'
.You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
\n\nReturn the head of the merged linked list.
\n\n\n
Example 1:
\n\nInput: list1 = [1,2,4], list2 = [1,3,4]\nOutput: [1,1,2,3,4,4]\n\n\n
Example 2:
\n\n\nInput: list1 = [], list2 = []\nOutput: []\n\n\n
Example 3:
\n\n\nInput: list1 = [], list2 = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n[0, 50]
.-100 <= Node.val <= 100
list1
and list2
are sorted in non-decreasing order.Given n
pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
\n
Example 1:
\nInput: n = 3\nOutput: [\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]\n
Example 2:
\nInput: n = 1\nOutput: [\"()\"]\n\n
\n
Constraints:
\n\n1 <= n <= 8
You are given an array of k
linked-lists lists
, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
\n\n\n
Example 1:
\n\n\nInput: lists = [[1,4,5],[1,3,4],[2,6]]\nOutput: [1,1,2,3,4,4,5,6]\nExplanation: The linked-lists are:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nmerging them into one sorted list:\n1->1->2->3->4->4->5->6\n\n\n
Example 2:
\n\n\nInput: lists = []\nOutput: []\n\n\n
Example 3:
\n\n\nInput: lists = [[]]\nOutput: []\n\n\n
\n
Constraints:
\n\nk == lists.length
0 <= k <= 104
0 <= lists[i].length <= 500
-104 <= lists[i][j] <= 104
lists[i]
is sorted in ascending order.lists[i].length
will not exceed 104
.Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
\n\n\n
Example 1:
\n\nInput: head = [1,2,3,4]
\n\nOutput: [2,1,4,3]
\n\nExplanation:
\n\nExample 2:
\n\nInput: head = []
\n\nOutput: []
\nExample 3:
\n\nInput: head = [1]
\n\nOutput: [1]
\nExample 4:
\n\nInput: head = [1,2,3]
\n\nOutput: [2,1,3]
\n\n
Constraints:
\n\n[0, 100]
.0 <= Node.val <= 100
Given the head
of a linked list, reverse the nodes of the list k
at a time, and return the modified list.
k
is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k
then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
\n\n\n
Example 1:
\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [2,1,4,3,5]\n\n\n
Example 2:
\n\nInput: head = [1,2,3,4,5], k = 3\nOutput: [3,2,1,4,5]\n\n\n
\n
Constraints:
\n\nn
.1 <= k <= n <= 5000
0 <= Node.val <= 1000
\n
Follow-up: Can you solve the problem in O(1)
extra memory space?
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums
.
Consider the number of unique elements of nums
to be k
, to get accepted, you need to do the following things:
nums
such that the first k
elements of nums
contain the unique elements in the order they were present in nums
initially. The remaining elements of nums
are not important as well as the size of nums
.k
.Custom Judge:
\n\nThe judge will test your solution with the following code:
\n\n\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}\n\n\n
If all assertions pass, then your solution will be accepted.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1,2]\nOutput: 2, nums = [1,2,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,1,1,1,2,2,3,3,4]\nOutput: 5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The order of the elements may be changed. Then return the number of elements in nums
which are not equal to val
.
Consider the number of elements in nums
which are not equal to val
be k
, to get accepted, you need to do the following things:
nums
such that the first k
elements of nums
contain the elements which are not equal to val
. The remaining elements of nums
are not important as well as the size of nums
.k
.Custom Judge:
\n\nThe judge will test your solution with the following code:
\n\n\nint[] nums = [...]; // Input array\nint val = ...; // Value to remove\nint[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n\nint k = removeElement(nums, val); // Calls your implementation\n\nassert k == expectedNums.length;\nsort(nums, 0, k); // Sort the first k elements of nums\nfor (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n}\n\n\n
If all assertions pass, then your solution will be accepted.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,2,2,3], val = 3\nOutput: 2, nums = [2,2,_,_]\nExplanation: Your function should return k = 2, with the first two elements of nums being 2.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,2,2,3,0,4,2], val = 2\nOutput: 5, nums = [0,1,4,0,3,_,_,_]\nExplanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\nNote that the five elements can be returned in any order.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
Given two strings needle
and haystack
, return the index of the first occurrence of needle
in haystack
, or -1
if needle
is not part of haystack
.
\n
Example 1:
\n\n\nInput: haystack = "sadbutsad", needle = "sad"\nOutput: 0\nExplanation: "sad" occurs at index 0 and 6.\nThe first occurrence is at index 0, so we return 0.\n\n\n
Example 2:
\n\n\nInput: haystack = "leetcode", needle = "leeto"\nOutput: -1\nExplanation: "leeto" did not occur in "leetcode", so we return -1.\n\n\n
\n
Constraints:
\n\n1 <= haystack.length, needle.length <= 104
haystack
and needle
consist of only lowercase English characters.Given two integers dividend
and divisor
, divide two integers without using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345
would be truncated to 8
, and -2.7335
would be truncated to -2
.
Return the quotient after dividing dividend
by divisor
.
Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]
. For this problem, if the quotient is strictly greater than 231 - 1
, then return 231 - 1
, and if the quotient is strictly less than -231
, then return -231
.
\n
Example 1:
\n\n\nInput: dividend = 10, divisor = 3\nOutput: 3\nExplanation: 10/3 = 3.33333.. which is truncated to 3.\n\n\n
Example 2:
\n\n\nInput: dividend = 7, divisor = -3\nOutput: -2\nExplanation: 7/-3 = -2.33333.. which is truncated to -2.\n\n\n
\n
Constraints:
\n\n-231 <= dividend, divisor <= 231 - 1
divisor != 0
You are given a string s
and an array of strings words
. All the strings of words
are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words
concatenated.
words = ["ab","cd","ef"]
, then "abcdef"
, "abefcd"
, "cdabef"
, "cdefab"
, "efabcd"
, and "efcdab"
are all concatenated strings. "acdbef"
is not a concatenated string because it is not the concatenation of any permutation of words
.Return an array of the starting indices of all the concatenated substrings in s
. You can return the answer in any order.
\n
Example 1:
\n\nInput: s = "barfoothefoobarman", words = ["foo","bar"]
\n\nOutput: [0,9]
\n\nExplanation:
\n\nThe substring starting at 0 is "barfoo"
. It is the concatenation of ["bar","foo"]
which is a permutation of words
.
\nThe substring starting at 9 is "foobar"
. It is the concatenation of ["foo","bar"]
which is a permutation of words
.
Example 2:
\n\nInput: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
\n\nOutput: []
\n\nExplanation:
\n\nThere is no concatenated substring.
\nExample 3:
\n\nInput: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
\n\nOutput: [6,9,12]
\n\nExplanation:
\n\nThe substring starting at 6 is "foobarthe"
. It is the concatenation of ["foo","bar","the"]
.
\nThe substring starting at 9 is "barthefoo"
. It is the concatenation of ["bar","the","foo"]
.
\nThe substring starting at 12 is "thefoobar"
. It is the concatenation of ["the","foo","bar"]
.
\n
Constraints:
\n\n1 <= s.length <= 104
1 <= words.length <= 5000
1 <= words[i].length <= 30
s
and words[i]
consist of lowercase English letters.A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
\n\narr = [1,2,3]
, the following are all the permutations of arr
: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]
.The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
\n\narr = [1,2,3]
is [1,3,2]
.arr = [2,3,1]
is [3,1,2]
.arr = [3,2,1]
is [1,2,3]
because [3,2,1]
does not have a lexicographical larger rearrangement.Given an array of integers nums
, find the next permutation of nums
.
The replacement must be in place and use only constant extra memory.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: [1,3,2]\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,1]\nOutput: [1,2,3]\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,5]\nOutput: [1,5,1]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 100
Given a string containing just the characters '('
and ')'
, return the length of the longest valid (well-formed) parentheses substring.
\n
Example 1:
\n\n\nInput: s = "(()"\nOutput: 2\nExplanation: The longest valid parentheses substring is "()".\n\n\n
Example 2:
\n\n\nInput: s = ")()())"\nOutput: 4\nExplanation: The longest valid parentheses substring is "()()".\n\n\n
Example 3:
\n\n\nInput: s = ""\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= s.length <= 3 * 104
s[i]
is '('
, or ')'
.There is an integer array nums
sorted in ascending order (with distinct values).
Prior to being passed to your function, nums
is possibly rotated at an unknown pivot index k
(1 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,5,6,7]
might be rotated at pivot index 3
and become [4,5,6,7,0,1,2]
.
Given the array nums
after the possible rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not in nums
.
You must write an algorithm with O(log n)
runtime complexity.
\n
Example 1:
\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutput: 4\n
Example 2:
\nInput: nums = [4,5,6,7,0,1,2], target = 3\nOutput: -1\n
Example 3:
\nInput: nums = [1], target = 0\nOutput: -1\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5000
-104 <= nums[i] <= 104
nums
are unique.nums
is an ascending array that is possibly rotated.-104 <= target <= 104
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
\n
Example 1:
\nInput: nums = [5,7,7,8,8,10], target = 8\nOutput: [3,4]\n
Example 2:
\nInput: nums = [5,7,7,8,8,10], target = 6\nOutput: [-1,-1]\n
Example 3:
\nInput: nums = [], target = 0\nOutput: [-1,-1]\n\n
\n
Constraints:
\n\n0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
is a non-decreasing array.-109 <= target <= 109
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
\n\nYou must write an algorithm with O(log n)
runtime complexity.
\n
Example 1:
\n\n\nInput: nums = [1,3,5,6], target = 5\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,5,6], target = 2\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,5,6], target = 7\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
contains distinct values sorted in ascending order.-104 <= target <= 104
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1-9
without repetition.1-9
without repetition.3 x 3
sub-boxes of the grid must contain the digits 1-9
without repetition.Note:
\n\n\n
Example 1:
\n\nInput: board = \n[["5","3",".",".","7",".",".",".","."]\n,["6",".",".","1","9","5",".",".","."]\n,[".","9","8",".",".",".",".","6","."]\n,["8",".",".",".","6",".",".",".","3"]\n,["4",".",".","8",".","3",".",".","1"]\n,["7",".",".",".","2",".",".",".","6"]\n,[".","6",".",".",".",".","2","8","."]\n,[".",".",".","4","1","9",".",".","5"]\n,[".",".",".",".","8",".",".","7","9"]]\nOutput: true\n\n\n
Example 2:
\n\n\nInput: board = \n[["8","3",".",".","7",".",".",".","."]\n,["6",".",".","1","9","5",".",".","."]\n,[".","9","8",".",".",".",".","6","."]\n,["8",".",".",".","6",".",".",".","3"]\n,["4",".",".","8",".","3",".",".","1"]\n,["7",".",".",".","2",".",".",".","6"]\n,[".","6",".",".",".",".","2","8","."]\n,[".",".",".","4","1","9",".",".","5"]\n,[".",".",".",".","8",".",".","7","9"]]\nOutput: false\nExplanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.\n\n\n
\n
Constraints:
\n\nboard.length == 9
board[i].length == 9
board[i][j]
is a digit 1-9
or '.'
.Write a program to solve a Sudoku puzzle by filling the empty cells.
\n\nA sudoku solution must satisfy all of the following rules:
\n\n1-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.
\n
Example 1:
\n\nInput: 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"]]\nOutput: [["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"]]\nExplanation: The input board is shown above and the only valid solution is shown below:\n\n\n\n\n
\n
Constraints:
\n\nboard.length == 9
board[i].length == 9
board[i][j]
is a digit or '.'
.The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
\n\ncountAndSay(1) = "1"
countAndSay(n)
is the run-length encoding of countAndSay(n - 1)
.Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251"
we replace "33"
with "23"
, replace "222"
with "32"
, replace "5"
with "15"
and replace "1"
with "11"
. Thus the compressed string becomes "23321511"
.
Given a positive integer n
, return the nth
element of the count-and-say sequence.
\n
Example 1:
\n\nInput: n = 4
\n\nOutput: "1211"
\n\nExplanation:
\n\n\ncountAndSay(1) = "1"\ncountAndSay(2) = RLE of "1" = "11"\ncountAndSay(3) = RLE of "11" = "21"\ncountAndSay(4) = RLE of "21" = "1211"\n\n
Example 2:
\n\nInput: n = 1
\n\nOutput: "1"
\n\nExplanation:
\n\nThis is the base case.
\n\n
Constraints:
\n\n1 <= n <= 30
\nFollow up: Could you solve it iteratively?", - "likes": 4264, - "dislikes": 8555, - "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 1064637, \"totalSubmissionRaw\": 1846477, \"acRate\": \"57.7%\"}", + "likes": 4761, + "dislikes": 8851, + "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1229383, \"totalSubmissionRaw\": 2032881, \"acRate\": \"60.5%\"}", "similarQuestions": "[{\"title\": \"Encode and Decode Strings\", \"titleSlug\": \"encode-and-decode-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"String Compression\", \"titleSlug\": \"string-compression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -1386,9 +1386,9 @@ "questionFrontendId": "39", "title": "Combination Sum", "content": "
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.
\n
Example 1:
\n\n\nInput: candidates = [2,3,6,7], target = 7\nOutput: [[2,2,3],[7]]\nExplanation:\n2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n7 is a candidate, and 7 = 7.\nThese are the only two combinations.\n\n\n
Example 2:
\n\n\nInput: candidates = [2,3,5], target = 8\nOutput: [[2,2,2,2],[2,3,3],[3,5]]\n\n\n
Example 3:
\n\n\nInput: candidates = [2], target = 1\nOutput: []\n\n\n
\n
Constraints:
\n\n1 <= candidates.length <= 30
2 <= candidates[i] <= 40
candidates
are distinct.1 <= target <= 40
Given 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.
\n\n\n
Example 1:
\n\n\nInput: candidates = [10,1,2,7,6,1,5], target = 8\nOutput: \n[\n[1,1,6],\n[1,2,5],\n[1,7],\n[2,6]\n]\n\n\n
Example 2:
\n\n\nInput: candidates = [2,5,2,1,2], target = 5\nOutput: \n[\n[1,2,2],\n[5]\n]\n\n\n
\n
Constraints:
\n\n1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
Given an unsorted integer array nums
. Return the smallest positive integer that is not present in nums
.
You must implement an algorithm that runs in O(n)
time and uses O(1)
auxiliary space.
\n
Example 1:
\n\n\nInput: nums = [1,2,0]\nOutput: 3\nExplanation: The numbers in the range [1,2] are all in the array.\n\n\n
Example 2:
\n\n\nInput: nums = [3,4,-1,1]\nOutput: 2\nExplanation: 1 is in the array but 2 is missing.\n\n\n
Example 3:
\n\n\nInput: nums = [7,8,9,11,12]\nOutput: 1\nExplanation: The smallest positive integer 1 is missing.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
Given n
non-negative integers representing an elevation map where the width of each bar is 1
, compute how much water it can trap after raining.
\n
Example 1:
\n\nInput: height = [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\nExplanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n\n\n
Example 2:
\n\n\nInput: height = [4,2,0,3,2,5]\nOutput: 9\n\n\n
\n
Constraints:
\n\nn == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
\n\n\n
Example 1:
\nInput: num1 = \"2\", num2 = \"3\"\nOutput: \"6\"\n
Example 2:
\nInput: num1 = \"123\", num2 = \"456\"\nOutput: \"56088\"\n\n
\n
Constraints:
\n\n1 <= num1.length, num2.length <= 200
num1
and num2
consist of digits only.num1
and num2
do not contain any leading zero, except the number 0
itself.Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
where:
'?'
Matches any single character.'*'
Matches any sequence of characters (including the empty sequence).The matching should cover the entire input string (not partial).
\n\n\n
Example 1:
\n\n\nInput: s = "aa", p = "a"\nOutput: false\nExplanation: "a" does not match the entire string "aa".\n\n\n
Example 2:
\n\n\nInput: s = "aa", p = "*"\nOutput: true\nExplanation: '*' matches any sequence.\n\n\n
Example 3:
\n\n\nInput: s = "cb", p = "?a"\nOutput: false\nExplanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n\n\n
\n
Constraints:
\n\n0 <= s.length, p.length <= 2000
s
contains only lowercase English letters.p
contains only lowercase English letters, '?'
or '*'
.You are given a 0-indexed array of integers nums
of length n
. You are initially positioned at nums[0]
.
Each element nums[i]
represents the maximum length of a forward jump from index i
. In other words, if you are at nums[i]
, you can jump to any nums[i + j]
where:
0 <= j <= nums[i]
andi + j < n
Return the minimum number of jumps to reach nums[n - 1]
. The test cases are generated such that you can reach nums[n - 1]
.
\n
Example 1:
\n\n\nInput: nums = [2,3,1,1,4]\nOutput: 2\nExplanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,0,1,4]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
0 <= nums[i] <= 1000
nums[n - 1]
.Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
\n
Example 1:
\nInput: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n
Example 2:
\nInput: nums = [0,1]\nOutput: [[0,1],[1,0]]\n
Example 3:
\nInput: nums = [1]\nOutput: [[1]]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 6
-10 <= nums[i] <= 10
nums
are unique.Given a collection of numbers, nums
, that might contain duplicates, return all possible unique permutations in any order.
\n
Example 1:
\n\n\nInput: nums = [1,1,2]\nOutput:\n[[1,1,2],\n [1,2,1],\n [2,1,1]]\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3]\nOutput: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 8
-10 <= nums[i] <= 10
You are given an n x n
2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
\n\n\n
Example 1:
\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[7,4,1],[8,5,2],[9,6,3]]\n\n\n
Example 2:
\n\nInput: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\nOutput: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n\n\n
\n
Constraints:
\n\nn == matrix.length == matrix[i].length
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
Given an array of strings strs
, group the anagrams together. You can return the answer in any order.
\n
Example 1:
\n\nInput: strs = ["eat","tea","tan","ate","nat","bat"]
\n\nOutput: [["bat"],["nat","tan"],["ate","eat","tea"]]
\n\nExplanation:
\n\n"bat"
."nat"
and "tan"
are anagrams as they can be rearranged to form each other."ate"
, "eat"
, and "tea"
are anagrams as they can be rearranged to form each other.Example 2:
\n\nInput: strs = [""]
\n\nOutput: [[""]]
\nExample 3:
\n\nInput: strs = ["a"]
\n\nOutput: [["a"]]
\n\n
Constraints:
\n\n1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
\n
Example 1:
\n\n\nInput: x = 2.00000, n = 10\nOutput: 1024.00000\n\n\n
Example 2:
\n\n\nInput: x = 2.10000, n = 3\nOutput: 9.26100\n\n\n
Example 3:
\n\n\nInput: x = 2.00000, n = -2\nOutput: 0.25000\nExplanation: 2-2 = 1/22 = 1/4 = 0.25\n\n\n
\n
Constraints:
\n\n-100.0 < x < 100.0
-231 <= n <= 231-1
n
is an integer.x
is not zero or n > 0
.-104 <= xn <= 104
The n-queens puzzle is the problem of placing n
queens on an n x n
chessboard such that no two queens attack each other.
Given an integer n
, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space, respectively.
\n
Example 1:
\n\nInput: n = 4\nOutput: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]\nExplanation: There exist two distinct solutions to the 4-queens puzzle as shown above\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: [["Q"]]\n\n\n
\n
Constraints:
\n\n1 <= n <= 9
The n-queens puzzle is the problem of placing n
queens on an n x n
chessboard such that no two queens attack each other.
Given an integer n
, return the number of distinct solutions to the n-queens puzzle.
\n
Example 1:
\n\nInput: n = 4\nOutput: 2\nExplanation: There are two distinct solutions to the 4-queens puzzle as shown.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 9
Given an integer array nums
, find the subarray with the largest sum, and return its sum.
\n
Example 1:
\n\n\nInput: nums = [-2,1,-3,4,-1,2,1,-5,4]\nOutput: 6\nExplanation: The subarray [4,-1,2,1] has the largest sum 6.\n\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: 1\nExplanation: The subarray [1] has the largest sum 1.\n\n\n
Example 3:
\n\n\nInput: nums = [5,4,-1,7,8]\nOutput: 23\nExplanation: The subarray [5,4,-1,7,8] has the largest sum 23.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
\n
Follow up: If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
\n
Example 1:
\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,2,3,6,9,8,7,4,5]\n\n\n
Example 2:
\n\nInput: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\nOutput: [1,2,3,4,8,12,11,10,9,5,6,7]\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [2,3,1,1,4]\nOutput: true\nExplanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,1,0,4]\nOutput: false\nExplanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
0 <= nums[i] <= 105
Given an array of intervals
where intervals[i] = [starti, endi]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
\n
Example 1:
\n\n\nInput: intervals = [[1,3],[2,6],[8,10],[15,18]]\nOutput: [[1,6],[8,10],[15,18]]\nExplanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,4],[4,5]]\nOutput: [[1,5]]\nExplanation: Intervals [1,4] and [4,5] are considered overlapping.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 104
You are given an array of non-overlapping intervals intervals
where intervals[i] = [starti, endi]
represent the start and the end of the ith
interval and intervals
is sorted in ascending order by starti
. You are also given an interval newInterval = [start, end]
that represents the start and end of another interval.
Insert newInterval
into intervals
such that intervals
is still sorted in ascending order by starti
and intervals
still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals
after the insertion.
Note that you don't need to modify intervals
in-place. You can make a new array and return it.
\n
Example 1:
\n\n\nInput: intervals = [[1,3],[6,9]], newInterval = [2,5]\nOutput: [[1,5],[6,9]]\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\nOutput: [[1,2],[3,10],[12,16]]\nExplanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n\n\n
\n
Constraints:
\n\n0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti <= endi <= 105
intervals
is sorted by starti
in ascending order.newInterval.length == 2
0 <= start <= end <= 105
Given a string s
consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
\n\n\n
Example 1:
\n\n\nInput: s = "Hello World"\nOutput: 5\nExplanation: The last word is "World" with length 5.\n\n\n
Example 2:
\n\n\nInput: s = " fly me to the moon "\nOutput: 4\nExplanation: The last word is "moon" with length 4.\n\n\n
Example 3:
\n\n\nInput: s = "luffy is still joyboy"\nOutput: 6\nExplanation: The last word is "joyboy" with length 6.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of only English letters and spaces ' '
.s
.Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n2
in spiral order.
\n
Example 1:
\n\nInput: n = 3\nOutput: [[1,2,3],[8,9,4],[7,6,5]]\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: [[1]]\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
The set [1, 2, 3, ..., n]
contains a total of n!
unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3
:
"123"
"132"
"213"
"231"
"312"
"321"
Given n
and k
, return the kth
permutation sequence.
\n
Example 1:
\nInput: n = 3, k = 3\nOutput: \"213\"\n
Example 2:
\nInput: n = 4, k = 9\nOutput: \"2314\"\n
Example 3:
\nInput: n = 3, k = 1\nOutput: \"123\"\n\n
\n
Constraints:
\n\n1 <= n <= 9
1 <= k <= n!
Given the head
of a linked list, rotate the list to the right by k
places.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [4,5,1,2,3]\n\n\n
Example 2:
\n\nInput: head = [0,1,2], k = 4\nOutput: [2,0,1]\n\n\n
\n
Constraints:
\n\n[0, 500]
.-100 <= Node.val <= 100
0 <= k <= 2 * 109
There is a robot on an m x n
grid. The robot is initially located at the top-left corner (i.e., grid[0][0]
). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]
). The robot can only move either down or right at any point in time.
Given the two integers m
and n
, return the number of possible unique paths that the robot can take to reach the bottom-right corner.
The test cases are generated so that the answer will be less than or equal to 2 * 109
.
\n
Example 1:
\n\nInput: m = 3, n = 7\nOutput: 28\n\n\n
Example 2:
\n\n\nInput: m = 3, n = 2\nOutput: 3\nExplanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n1. Right -> Down -> Down\n2. Down -> Down -> Right\n3. Down -> Right -> Down\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 100
You are given an m x n
integer array grid
. There is a robot initially located at the top-left corner (i.e., grid[0][0]
). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]
). The robot can only move either down or right at any point in time.
An obstacle and space are marked as 1
or 0
respectively in grid
. A path that the robot takes cannot include any square that is an obstacle.
Return the number of possible unique paths that the robot can take to reach the bottom-right corner.
\n\nThe testcases are generated so that the answer will be less than or equal to 2 * 109
.
\n
Example 1:
\n\nInput: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\nOutput: 2\nExplanation: There is one obstacle in the middle of the 3x3 grid above.\nThere are two ways to reach the bottom-right corner:\n1. Right -> Right -> Down -> Down\n2. Down -> Down -> Right -> Right\n\n\n
Example 2:
\n\nInput: obstacleGrid = [[0,1],[0,0]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nm == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
obstacleGrid[i][j]
is 0
or 1
.Given a m x n
grid
filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
\n\n\n
Example 1:
\n\nInput: grid = [[1,3,1],[1,5,1],[4,2,1]]\nOutput: 7\nExplanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.\n\n\n
Example 2:
\n\n\nInput: grid = [[1,2,3],[4,5,6]]\nOutput: 12\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 200
Given a string s
, return whether s
is a valid number.
\n
\nFor example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"
, while the following are not valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"
.
Formally, a valid number is defined using one of the following definitions:
\n\nAn integer number is defined with an optional sign '-'
or '+'
followed by digits.
A decimal number is defined with an optional sign '-'
or '+'
followed by one of the following definitions:
'.'
.'.'
followed by digits.'.'
followed by digits.An exponent is defined with an exponent notation 'e'
or 'E'
followed by an integer number.
The digits are defined as one or more digits.
\n\n\n
Example 1:
\n\nInput: s = "0"
\n\nOutput: true
\nExample 2:
\n\nInput: s = "e"
\n\nOutput: false
\nExample 3:
\n\nInput: s = "."
\n\nOutput: false
\n\n
Constraints:
\n\n1 <= s.length <= 20
s
consists of only English letters (both uppercase and lowercase), digits (0-9
), plus '+'
, minus '-'
, or dot '.'
.You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
Increment the large integer by one and return the resulting array of digits.
\n\n\n
Example 1:
\n\n\nInput: digits = [1,2,3]\nOutput: [1,2,4]\nExplanation: The array represents the integer 123.\nIncrementing by one gives 123 + 1 = 124.\nThus, the result should be [1,2,4].\n\n\n
Example 2:
\n\n\nInput: digits = [4,3,2,1]\nOutput: [4,3,2,2]\nExplanation: The array represents the integer 4321.\nIncrementing by one gives 4321 + 1 = 4322.\nThus, the result should be [4,3,2,2].\n\n\n
Example 3:
\n\n\nInput: digits = [9]\nOutput: [1,0]\nExplanation: The array represents the integer 9.\nIncrementing by one gives 9 + 1 = 10.\nThus, the result should be [1,0].\n\n\n
\n
Constraints:
\n\n1 <= digits.length <= 100
0 <= digits[i] <= 9
digits
does not contain any leading 0
's.Given two binary strings a
and b
, return their sum as a binary string.
\n
Example 1:
\nInput: a = \"11\", b = \"1\"\nOutput: \"100\"\n
Example 2:
\nInput: a = \"1010\", b = \"1011\"\nOutput: \"10101\"\n\n
\n
Constraints:
\n\n1 <= a.length, b.length <= 104
a
and b
consist only of '0'
or '1'
characters.Given an array of strings words
and a width maxWidth
, format the text such that each line has exactly maxWidth
characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactly maxWidth
characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
\n\nFor the last line of text, it should be left-justified, and no extra space is inserted between words.
\n\nNote:
\n\n0
and not exceed maxWidth
.words
contains at least one word.\n
Example 1:
\n\n\nInput: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16\nOutput:\n[\n "This is an",\n "example of text",\n "justification. "\n]\n\n
Example 2:
\n\n\nInput: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16\nOutput:\n[\n "What must be",\n "acknowledgment ",\n "shall be "\n]\nExplanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.\nNote that the second line is also left-justified because it contains only one word.\n\n
Example 3:
\n\n\nInput: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20\nOutput:\n[\n "Science is what we",\n "understand well",\n "enough to explain to",\n "a computer. Art is",\n "everything else we",\n "do "\n]\n\n
\n
Constraints:
\n\n1 <= words.length <= 300
1 <= words[i].length <= 20
words[i]
consists of only English letters and symbols.1 <= maxWidth <= 100
words[i].length <= maxWidth
Given a non-negative integer x
, return the square root of x
rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
\n\npow(x, 0.5)
in c++ or x ** 0.5
in python.\n
Example 1:
\n\n\nInput: x = 4\nOutput: 2\nExplanation: The square root of 4 is 2, so we return 2.\n\n\n
Example 2:
\n\n\nInput: x = 8\nOutput: 2\nExplanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.\n\n\n
\n
Constraints:
\n\n0 <= x <= 231 - 1
You are climbing a staircase. It takes n
steps to reach the top.
Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 2\nExplanation: There are two ways to climb to the top.\n1. 1 step + 1 step\n2. 2 steps\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: 3\nExplanation: There are three ways to climb to the top.\n1. 1 step + 1 step + 1 step\n2. 1 step + 2 steps\n3. 2 steps + 1 step\n\n\n
\n
Constraints:
\n\n1 <= n <= 45
You are given an absolute path for a Unix-style file system, which always begins with a slash '/'
. Your task is to transform this absolute path into its simplified canonical path.
The rules of a Unix-style file system are as follows:
\n\n'.'
represents the current directory.'..'
represents the previous/parent directory.'//'
and '///'
are treated as a single slash '/'
.'...'
and '....'
are valid directory or file names.The simplified canonical path should follow these rules:
\n\n'/'
.'/'
.'/'
, unless it is the root directory.'.'
and '..'
) used to denote current or parent directories.Return the simplified canonical path.
\n\n\n
Example 1:
\n\nInput: path = "/home/"
\n\nOutput: "/home"
\n\nExplanation:
\n\nThe trailing slash should be removed.
\nExample 2:
\n\nInput: path = "/home//foo/"
\n\nOutput: "/home/foo"
\n\nExplanation:
\n\nMultiple consecutive slashes are replaced by a single one.
\nExample 3:
\n\nInput: path = "/home/user/Documents/../Pictures"
\n\nOutput: "/home/user/Pictures"
\n\nExplanation:
\n\nA double period ".."
refers to the directory up a level (the parent directory).
Example 4:
\n\nInput: path = "/../"
\n\nOutput: "/"
\n\nExplanation:
\n\nGoing one level up from the root directory is not possible.
\nExample 5:
\n\nInput: path = "/.../a/../b/c/../d/./"
\n\nOutput: "/.../b/d"
\n\nExplanation:
\n\n"..."
is a valid name for a directory in this problem.
\n
Constraints:
\n\n1 <= path.length <= 3000
path
consists of English letters, digits, period '.'
, slash '/'
or '_'
.path
is a valid absolute Unix path.Given two strings word1
and word2
, return the minimum number of operations required to convert word1
to word2
.
You have the following three operations permitted on a word:
\n\n\n
Example 1:
\n\n\nInput: word1 = "horse", word2 = "ros"\nOutput: 3\nExplanation: \nhorse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')\n\n\n
Example 2:
\n\n\nInput: word1 = "intention", word2 = "execution"\nOutput: 5\nExplanation: \nintention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')\n\n\n
\n
Constraints:
\n\n0 <= word1.length, word2.length <= 500
word1
and word2
consist of lowercase English letters.Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
's.
You must do it in place.
\n\n\n
Example 1:
\n\nInput: matrix = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: [[1,0,1],[0,0,0],[1,0,1]]\n\n\n
Example 2:
\n\nInput: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\nOutput: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
\n
Follow up:
\n\nO(mn)
space is probably a bad idea.O(m + n)
space, but still not the best solution.You are given an m x n
integer matrix matrix
with the following two properties:
Given an integer target
, return true
if target
is in matrix
or false
otherwise.
You must write a solution in O(log(m * n))
time complexity.
\n
Example 1:
\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\nOutput: true\n\n\n
Example 2:
\n\nInput: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\nOutput: false\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
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.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\n\n
Example 2:
\n\n\nInput: nums = [2,0,1]\nOutput: [0,1,2]\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 300
nums[i]
is either 0
, 1
, or 2
.\n
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
\n", - "likes": 19383, - "dislikes": 689, - "stats": "{\"totalAccepted\": \"2.6M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 2617538, \"totalSubmissionRaw\": 3958421, \"acRate\": \"66.1%\"}", + "likes": 20145, + "dislikes": 716, + "stats": "{\"totalAccepted\": \"3M\", \"totalSubmission\": \"4.4M\", \"totalAcceptedRaw\": 2978532, \"totalSubmissionRaw\": 4409360, \"acRate\": \"67.6%\"}", "similarQuestions": "[{\"title\": \"Sort List\", \"titleSlug\": \"sort-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort\", \"titleSlug\": \"wiggle-sort\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort II\", \"titleSlug\": \"wiggle-sort-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -2736,9 +2736,9 @@ "questionFrontendId": "76", "title": "Minimum Window Substring", "content": "Given two strings s
and t
of lengths m
and n
respectively, return the minimum window substring of s
such that every character in t
(including duplicates) is included in the window. If there is no such substring, return the empty string ""
.
The testcases will be generated such that the answer is unique.
\n\n\n
Example 1:
\n\n\nInput: s = "ADOBECODEBANC", t = "ABC"\nOutput: "BANC"\nExplanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.\n\n\n
Example 2:
\n\n\nInput: s = "a", t = "a"\nOutput: "a"\nExplanation: The entire string s is the minimum window.\n\n\n
Example 3:
\n\n\nInput: s = "a", t = "aa"\nOutput: ""\nExplanation: Both 'a's from t must be included in the window.\nSince the largest window of s only has one 'a', return empty string.\n\n\n
\n
Constraints:
\n\nm == s.length
n == t.length
1 <= m, n <= 105
s
and t
consist of uppercase and lowercase English letters.\n
Follow up: Could you find an algorithm that runs in O(m + n)
time?
Given two integers n
and k
, return all possible combinations of k
numbers chosen from the range [1, n]
.
You may return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: n = 4, k = 2\nOutput: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nExplanation: There are 4 choose 2 = 6 total combinations.\nNote that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.\n\n\n
Example 2:
\n\n\nInput: n = 1, k = 1\nOutput: [[1]]\nExplanation: There is 1 choose 1 = 1 total combination.\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
1 <= k <= n
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.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n\n\n
Example 2:
\n\n\nInput: nums = [0]\nOutput: [[],[0]]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums
are unique.Given an m x n
grid of characters board
and a string word
, return true
if word
exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
\n\n\n
Example 1:
\n\nInput: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"\nOutput: true\n\n\n
Example 2:
\n\nInput: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"\nOutput: true\n\n\n
Example 3:
\n\nInput: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"\nOutput: false\n\n\n
\n
Constraints:
\n\nm == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board
and word
consists of only lowercase and uppercase English letters.\n
Follow up: Could you use search pruning to make your solution faster with a larger board
?
Given an integer array nums
sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
Return k
after placing the final result in the first k
slots of nums
.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
\n\nCustom Judge:
\n\nThe judge will test your solution with the following code:
\n\n\nint[] nums = [...]; // Input array\nint[] expectedNums = [...]; // The expected answer with correct length\n\nint k = removeDuplicates(nums); // Calls your implementation\n\nassert k == expectedNums.length;\nfor (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n}\n\n\n
If all assertions pass, then your solution will be accepted.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1,1,2,2,3]\nOutput: 5, nums = [1,1,2,2,3,_]\nExplanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,1,1,1,1,2,3,3]\nOutput: 7, nums = [0,0,1,1,2,3,3,_,_]\nExplanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\nIt does not matter what you leave beyond the returned k (hence they are underscores).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums
is sorted in non-decreasing order.There is an integer array nums
sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums
is rotated at an unknown pivot index k
(0 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,4,4,5,6,6,7]
might be rotated at pivot index 5
and become [4,5,6,6,7,0,1,2,4,4]
.
Given the array nums
after the rotation and an integer target
, return true
if target
is in nums
, or false
if it is not in nums
.
You must decrease the overall operation steps as much as possible.
\n\n\n
Example 1:
\nInput: nums = [2,5,6,0,0,1,2], target = 0\nOutput: true\n
Example 2:
\nInput: nums = [2,5,6,0,0,1,2], target = 3\nOutput: false\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5000
-104 <= nums[i] <= 104
nums
is guaranteed to be rotated at some pivot.-104 <= target <= 104
\n
Follow up: This problem is similar to Search in Rotated Sorted Array, but nums
may contain duplicates. Would this affect the runtime complexity? How and why?
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.
\n
Example 1:
\n\nInput: head = [1,2,3,3,4,4,5]\nOutput: [1,2,5]\n\n\n
Example 2:
\n\nInput: head = [1,1,1,2,3]\nOutput: [2,3]\n\n\n
\n
Constraints:
\n\n[0, 300]
.-100 <= Node.val <= 100
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
\n
Example 1:
\n\nInput: head = [1,1,2]\nOutput: [1,2]\n\n\n
Example 2:
\n\nInput: head = [1,1,2,3,3]\nOutput: [1,2,3]\n\n\n
\n
Constraints:
\n\n[0, 300]
.-100 <= Node.val <= 100
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.
\n
Example 1:
\n\nInput: heights = [2,1,5,6,2,3]\nOutput: 10\nExplanation: The above is a histogram where width of each bar is 1.\nThe largest rectangle is shown in the red area, which has an area = 10 units.\n\n\n
Example 2:
\n\nInput: heights = [2,4]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= heights.length <= 105
0 <= heights[i] <= 104
Given a rows x cols
binary matrix
filled with 0
's and 1
's, find the largest rectangle containing only 1
's and return its area.
\n
Example 1:
\n\nInput: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]\nOutput: 6\nExplanation: The maximal rectangle is shown in the above picture.\n\n\n
Example 2:
\n\n\nInput: matrix = [["0"]]\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: matrix = [["1"]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nrows == matrix.length
cols == matrix[i].length
1 <= row, cols <= 200
matrix[i][j]
is '0'
or '1'
.Given the head
of a linked list and a value x
, partition it such that all nodes less than x
come before nodes greater than or equal to x
.
You should preserve the original relative order of the nodes in each of the two partitions.
\n\n\n
Example 1:
\n\nInput: head = [1,4,3,2,5,2], x = 3\nOutput: [1,2,2,4,3,5]\n\n\n
Example 2:
\n\n\nInput: head = [2,1], x = 2\nOutput: [1,2]\n\n\n
\n
Constraints:
\n\n[0, 200]
.-100 <= Node.val <= 100
-200 <= x <= 200
We can scramble a string s to get a string t using the following algorithm:
\n\ns
, divide it to x
and y
where s = x + y
.s
may become s = x + y
or s = y + x
.x
and y
.Given two strings s1
and s2
of the same length, return true
if s2
is a scrambled string of s1
, otherwise, return false
.
\n
Example 1:
\n\n\nInput: s1 = "great", s2 = "rgeat"\nOutput: true\nExplanation: One possible scenario applied on s1 is:\n"great" --> "gr/eat" // divide at random index.\n"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.\n"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.\n"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.\n"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".\n"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.\nThe algorithm stops now, and the result string is "rgeat" which is s2.\nAs one possible scenario led s1 to be scrambled to s2, we return true.\n\n\n
Example 2:
\n\n\nInput: s1 = "abcde", s2 = "caebd"\nOutput: false\n\n\n
Example 3:
\n\n\nInput: s1 = "a", s2 = "a"\nOutput: true\n\n\n
\n
Constraints:
\n\ns1.length == s2.length
1 <= s1.length <= 30
s1
and s2
consist of lowercase English letters.You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
Merge nums1
and nums2
into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1
. To accommodate this, nums1
has a length of m + n
, where the first m
elements denote the elements that should be merged, and the last n
elements are set to 0
and should be ignored. nums2
has a length of n
.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\nOutput: [1,2,2,3,5,6]\nExplanation: The arrays we are merging are [1,2,3] and [2,5,6].\nThe result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1], m = 1, nums2 = [], n = 0\nOutput: [1]\nExplanation: The arrays we are merging are [1] and [].\nThe result of the merge is [1].\n\n\n
Example 3:
\n\n\nInput: nums1 = [0], m = 0, nums2 = [1], n = 1\nOutput: [1]\nExplanation: The arrays we are merging are [] and [1].\nThe result of the merge is [1].\nNote that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.\n\n\n
\n
Constraints:
\n\nnums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109
\n
Follow up: Can you come up with an algorithm that runs in O(m + n)
time?
An n-bit gray code sequence is a sequence of 2n
integers where:
[0, 2n - 1]
,0
,Given an integer n
, return any valid n-bit gray code sequence.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: [0,1,3,2]\nExplanation:\nThe binary representation of [0,1,3,2] is [00,01,11,10].\n- 00 and 01 differ by one bit\n- 01 and 11 differ by one bit\n- 11 and 10 differ by one bit\n- 10 and 00 differ by one bit\n[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n- 00 and 10 differ by one bit\n- 10 and 11 differ by one bit\n- 11 and 01 differ by one bit\n- 01 and 00 differ by one bit\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: [0,1]\n\n\n
\n
Constraints:
\n\n1 <= n <= 16
Given an integer array nums
that may contain duplicates, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
\n\n\n
Example 1:
\nInput: nums = [1,2,2]\nOutput: [[],[1],[1,2],[1,2,2],[2],[2,2]]\n
Example 2:
\nInput: nums = [0]\nOutput: [[],[0]]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 10
-10 <= nums[i] <= 10
You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:
\n\n"1" -> 'A'
\n"2" -> 'B'
\n...
\n"25" -> 'Y'
\n"26" -> 'Z'
However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2"
and "5"
vs "25"
).
For example, "11106"
can be decoded into:
"AAJF"
with the grouping (1, 1, 10, 6)
"KJF"
with the grouping (11, 10, 6)
(1, 11, 06)
is invalid because "06"
is not a valid code (only "6"
is valid).Note: there may be strings that are impossible to decode.
\n
\nGiven a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0
.
The test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\nInput: s = "12"
\n\nOutput: 2
\n\nExplanation:
\n\n"12" could be decoded as "AB" (1 2) or "L" (12).
\nExample 2:
\n\nInput: s = "226"
\n\nOutput: 3
\n\nExplanation:
\n\n"226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
\nExample 3:
\n\nInput: s = "06"
\n\nOutput: 0
\n\nExplanation:
\n\n"06" cannot be mapped to "F" because of the leading zero ("6" is different from "06"). In this case, the string is not a valid encoding, so return 0.
\n\n
Constraints:
\n\n1 <= s.length <= 100
s
contains only digits and may contain leading zero(s).Given the head
of a singly linked list and two integers left
and right
where left <= right
, reverse the nodes of the list from position left
to position right
, and return the reversed list.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5], left = 2, right = 4\nOutput: [1,4,3,2,5]\n\n\n
Example 2:
\n\n\nInput: head = [5], left = 1, right = 1\nOutput: [5]\n\n\n
\n
Constraints:
\n\nn
.1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
\nFollow up: Could you do it in one pass?", - "likes": 12033, - "dislikes": 681, - "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1020317, \"totalSubmissionRaw\": 2084668, \"acRate\": \"48.9%\"}", + "likes": 12280, + "dislikes": 713, + "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1098477, \"totalSubmissionRaw\": 2215919, \"acRate\": \"49.6%\"}", "similarQuestions": "[{\"title\": \"Reverse Linked List\", \"titleSlug\": \"reverse-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -3349,9 +3349,9 @@ "questionFrontendId": "93", "title": "Restore IP Addresses", "content": "
A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0
and 255
(inclusive) and cannot have leading zeros.
"0.1.2.201"
and "192.168.1.1"
are valid IP addresses, but "0.011.255.245"
, "192.168.1.312"
and "192.168@1.1"
are invalid IP addresses.Given a string s
containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s
. You are not allowed to reorder or remove any digits in s
. You may return the valid IP addresses in any order.
\n
Example 1:
\n\n\nInput: s = "25525511135"\nOutput: ["255.255.11.135","255.255.111.35"]\n\n\n
Example 2:
\n\n\nInput: s = "0000"\nOutput: ["0.0.0.0"]\n\n\n
Example 3:
\n\n\nInput: s = "101023"\nOutput: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 20
s
consists of digits only.Given the root
of a binary tree, return the inorder traversal of its nodes' values.
\n
Example 1:
\n\nInput: root = [1,null,2,3]
\n\nOutput: [1,3,2]
\n\nExplanation:
\n\nExample 2:
\n\nInput: root = [1,2,3,4,5,null,8,null,null,6,7,9]
\n\nOutput: [4,2,6,5,7,1,3,9,8]
\n\nExplanation:
\n\nExample 3:
\n\nInput: root = []
\n\nOutput: []
\nExample 4:
\n\nInput: root = [1]
\n\nOutput: [1]
\n\n
Constraints:
\n\n[0, 100]
.-100 <= Node.val <= 100
\nFollow up: Recursive solution is trivial, could you do it iteratively?", - "likes": 13886, - "dislikes": 826, - "stats": "{\"totalAccepted\": \"2.9M\", \"totalSubmission\": \"3.8M\", \"totalAcceptedRaw\": 2937418, \"totalSubmissionRaw\": 3773031, \"acRate\": \"77.9%\"}", + "likes": 14168, + "dislikes": 843, + "stats": "{\"totalAccepted\": \"3.1M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 3141576, \"totalSubmissionRaw\": 3998989, \"acRate\": \"78.6%\"}", "similarQuestions": "[{\"title\": \"Validate Binary Search Tree\", \"titleSlug\": \"validate-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Preorder Traversal\", \"titleSlug\": \"binary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Postorder Traversal\", \"titleSlug\": \"binary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Element in a BST\", \"titleSlug\": \"kth-smallest-element-in-a-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Closest Binary Search Tree Value II\", \"titleSlug\": \"closest-binary-search-tree-value-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Inorder Successor in BST\", \"titleSlug\": \"inorder-successor-in-bst\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Convert Binary Search Tree to Sorted Doubly Linked List\", \"titleSlug\": \"convert-binary-search-tree-to-sorted-doubly-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Distance Between BST Nodes\", \"titleSlug\": \"minimum-distance-between-bst-nodes\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -3423,9 +3423,9 @@ "questionFrontendId": "95", "title": "Unique Binary Search Trees II", "content": "
Given an integer n
, return all the structurally unique BST's (binary search trees), which has exactly n
nodes of unique values from 1
to n
. Return the answer in any order.
\n
Example 1:
\n\nInput: n = 3\nOutput: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: [[1]]\n\n\n
\n
Constraints:
\n\n1 <= n <= 8
Given an integer n
, return the number of structurally unique BST's (binary search trees) which has exactly n
nodes of unique values from 1
to n
.
\n
Example 1:
\n\nInput: n = 3\nOutput: 5\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 19
Given strings s1
, s2
, and s3
, find whether s3
is formed by an interleaving of s1
and s2
.
An interleaving of two strings s
and t
is a configuration where s
and t
are divided into n
and m
substrings respectively, such that:
s = s1 + s2 + ... + sn
t = t1 + t2 + ... + tm
|n - m| <= 1
s1 + t1 + s2 + t2 + s3 + t3 + ...
or t1 + s1 + t2 + s2 + t3 + s3 + ...
Note: a + b
is the concatenation of strings a
and b
.
\n
Example 1:
\n\nInput: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"\nOutput: true\nExplanation: One way to obtain s3 is:\nSplit s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a".\nInterleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac".\nSince s3 can be obtained by interleaving s1 and s2, we return true.\n\n\n
Example 2:
\n\n\nInput: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"\nOutput: false\nExplanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.\n\n\n
Example 3:
\n\n\nInput: s1 = "", s2 = "", s3 = ""\nOutput: true\n\n\n
\n
Constraints:
\n\n0 <= s1.length, s2.length <= 100
0 <= s3.length <= 200
s1
, s2
, and s3
consist of lowercase English letters.\n
Follow up: Could you solve it using only O(s2.length)
additional memory space?
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
\n\n\n
Example 1:
\n\nInput: root = [2,1,3]\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [5,1,4,null,null,3,6]\nOutput: false\nExplanation: The root node's value is 5 but its right child's value is 4.\n\n\n
\n
Constraints:
\n\n[1, 104]
.-231 <= Node.val <= 231 - 1
You are given the root
of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.
\n
Example 1:
\n\nInput: root = [1,3,null,null,2]\nOutput: [3,1,null,null,2]\nExplanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.\n\n\n
Example 2:
\n\nInput: root = [3,1,4,null,null,2]\nOutput: [2,1,4,null,null,3]\nExplanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.\n\n\n
\n
Constraints:
\n\n[2, 1000]
.-231 <= Node.val <= 231 - 1
\nFollow up: A solution using
O(n)
space is pretty straight-forward. Could you devise a constant O(1)
space solution?",
- "likes": 8108,
- "dislikes": 263,
- "stats": "{\"totalAccepted\": \"514.9K\", \"totalSubmission\": \"931.5K\", \"totalAcceptedRaw\": 514907, \"totalSubmissionRaw\": 931524, \"acRate\": \"55.3%\"}",
+ "likes": 8247,
+ "dislikes": 268,
+ "stats": "{\"totalAccepted\": \"548.9K\", \"totalSubmission\": \"975.4K\", \"totalAcceptedRaw\": 548921, \"totalSubmissionRaw\": 975431, \"acRate\": \"56.3%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -3623,9 +3623,9 @@
"questionFrontendId": "100",
"title": "Same Tree",
"content": "Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
\n\n\n
Example 1:
\n\nInput: p = [1,2,3], q = [1,2,3]\nOutput: true\n\n\n
Example 2:
\n\nInput: p = [1,2], q = [1,null,2]\nOutput: false\n\n\n
Example 3:
\n\nInput: p = [1,2,1], q = [1,1,2]\nOutput: false\n\n\n
\n
Constraints:
\n\n[0, 100]
.-104 <= Node.val <= 104
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
\n
Example 1:
\n\nInput: root = [1,2,2,3,4,4,3]\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [1,2,2,null,3,null,3]\nOutput: false\n\n\n
\n
Constraints:
\n\n[1, 1000]
.-100 <= Node.val <= 100
\nFollow up: Could you solve it both recursively and iteratively?", - "likes": 15813, - "dislikes": 401, - "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"4M\", \"totalAcceptedRaw\": 2311310, \"totalSubmissionRaw\": 3954730, \"acRate\": \"58.4%\"}", + "likes": 16132, + "dislikes": 418, + "stats": "{\"totalAccepted\": \"2.5M\", \"totalSubmission\": \"4.2M\", \"totalAcceptedRaw\": 2468888, \"totalSubmissionRaw\": 4167014, \"acRate\": \"59.2%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -3703,9 +3703,9 @@ "questionFrontendId": "102", "title": "Binary Tree Level Order Traversal", "content": "
Given the root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[9,20],[15,7]]\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: [[1]]\n\n\n
Example 3:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 2000]
.-1000 <= Node.val <= 1000
Given the root
of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[20,9],[15,7]]\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: [[1]]\n\n\n
Example 3:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 2000]
.-100 <= Node.val <= 100
Given the root
of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
\n\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 3\n\n\n
Example 2:
\n\n\nInput: root = [1,null,2]\nOutput: 2\n\n\n
\n
Constraints:
\n\n[0, 104]
.-100 <= Node.val <= 100
Given two integer arrays preorder
and inorder
where preorder
is the preorder traversal of a binary tree and inorder
is the inorder traversal of the same tree, construct and return the binary tree.
\n
Example 1:
\n\nInput: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput: [3,9,20,null,null,15,7]\n\n\n
Example 2:
\n\n\nInput: preorder = [-1], inorder = [-1]\nOutput: [-1]\n\n\n
\n
Constraints:
\n\n1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
and inorder
consist of unique values.inorder
also appears in preorder
.preorder
is guaranteed to be the preorder traversal of the tree.inorder
is guaranteed to be the inorder traversal of the tree.Given two integer arrays inorder
and postorder
where inorder
is the inorder traversal of a binary tree and postorder
is the postorder traversal of the same tree, construct and return the binary tree.
\n
Example 1:
\n\nInput: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput: [3,9,20,null,null,15,7]\n\n\n
Example 2:
\n\n\nInput: inorder = [-1], postorder = [-1]\nOutput: [-1]\n\n\n
\n
Constraints:
\n\n1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder
and postorder
consist of unique values.postorder
also appears in inorder
.inorder
is guaranteed to be the inorder traversal of the tree.postorder
is guaranteed to be the postorder traversal of the tree.Given the root
of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).
\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[15,7],[9,20],[3]]\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: [[1]]\n\n\n
Example 3:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 2000]
.-1000 <= Node.val <= 1000
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
\n
Example 1:
\n\nInput: nums = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: [0,-10,5,null,-3,null,9] is also accepted:\n\n\n\n
Example 2:
\n\nInput: nums = [1,3]\nOutput: [3,1]\nExplanation: [1,null,3] and [3,1] are both height-balanced BSTs.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in a strictly increasing order.Given the head
of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.
\n
Example 1:
\n\nInput: head = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.\n\n\n
Example 2:
\n\n\nInput: head = []\nOutput: []\n\n\n
\n
Constraints:
\n\nhead
is in the range [0, 2 * 104]
.-105 <= Node.val <= 105
Given a binary tree, determine if it is height-balanced.
\n\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [1,2,2,3,3,null,null,4,4]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: root = []\nOutput: true\n\n\n
\n
Constraints:
\n\n[0, 5000]
.-104 <= Node.val <= 104
Given a binary tree, find its minimum depth.
\n\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
\n\nNote: A leaf is a node with no children.
\n\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: root = [2,null,3,null,4,null,5,null,6]\nOutput: 5\n\n\n
\n
Constraints:
\n\n[0, 105]
.-1000 <= Node.val <= 1000
Given 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.
\n\n\n
Example 1:
\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput: true\nExplanation: The root-to-leaf path with the target sum is shown.\n\n\n
Example 2:
\n\nInput: root = [1,2,3], targetSum = 5\nOutput: false\nExplanation: There are two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.\n\n\n
Example 3:
\n\n\nInput: root = [], targetSum = 0\nOutput: false\nExplanation: Since the tree is empty, there are no root-to-leaf paths.\n\n\n
\n
Constraints:
\n\n[0, 5000]
.-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
Given the root
of a binary tree and an integer targetSum
, return all root-to-leaf paths where the sum of the node values in the path equals targetSum
. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
\n\n\n
Example 1:
\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: [[5,4,11,2],[5,8,4,5]]\nExplanation: There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\n\n\n
Example 2:
\n\nInput: root = [1,2,3], targetSum = 5\nOutput: []\n\n\n
Example 3:
\n\n\nInput: root = [1,2], targetSum = 0\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 5000]
.-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
Given the root
of a binary tree, flatten the tree into a "linked list":
TreeNode
class where the right
child pointer points to the next node in the list and the left
child pointer is always null
.\n
Example 1:
\n\nInput: root = [1,2,5,3,4,null,6]\nOutput: [1,null,2,null,3,null,4,null,5,null,6]\n\n\n
Example 2:
\n\n\nInput: root = []\nOutput: []\n\n\n
Example 3:
\n\n\nInput: root = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n[0, 2000]
.-100 <= Node.val <= 100
\nFollow up: Can you flatten the tree in-place (with
O(1)
extra space)?",
- "likes": 12730,
- "dislikes": 572,
- "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1114054, \"totalSubmissionRaw\": 1651507, \"acRate\": \"67.5%\"}",
+ "likes": 12999,
+ "dislikes": 584,
+ "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1194181, \"totalSubmissionRaw\": 1744010, \"acRate\": \"68.5%\"}",
"similarQuestions": "[{\"title\": \"Flatten a Multilevel Doubly Linked List\", \"titleSlug\": \"flatten-a-multilevel-doubly-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Correct a Binary Tree\", \"titleSlug\": \"correct-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [
@@ -4230,9 +4230,9 @@
"questionFrontendId": "115",
"title": "Distinct Subsequences",
"content": "Given two strings s and t, return the number of distinct subsequences of s which equals t.
\n\nThe test cases are generated so that the answer fits on a 32-bit signed integer.
\n\n\n
Example 1:
\n\n\nInput: s = "rabbbit", t = "rabbit"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate "rabbit" from s.\n\n\nrabbbit
\nrabbbit
\nrabbbit
\n
Example 2:
\n\n\nInput: s = "babgbag", t = "bag"\nOutput: 5\nExplanation:\nAs shown below, there are 5 ways you can generate "bag" from s.\n\n\nbabgbag
\nbabgbag
\nbabgbag
\nbabgbag
\nbabgbag
\n
Constraints:
\n\n1 <= s.length, t.length <= 1000
s
and t
consist of English letters.You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
\n\n\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n\n\n
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6,7]\nOutput: [1,#,2,3,#,4,5,6,7,#]\nExplanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\n\n\n
Example 2:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 212 - 1]
.-1000 <= Node.val <= 1000
\n
Follow-up:
\n\nGiven a binary tree
\n\n\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\n\n\n
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
\n
Example 1:
\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: [1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\n\n\n
Example 2:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 6000]
.-100 <= Node.val <= 100
\n
Follow-up:
\n\nGiven an integer numRows
, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
\n\n
Example 1:
\nInput: numRows = 5\nOutput: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n
Example 2:
\nInput: numRows = 1\nOutput: [[1]]\n\n
\n
Constraints:
\n\n1 <= numRows <= 30
Given an integer rowIndex
, return the rowIndexth
(0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
\n\n
Example 1:
\nInput: rowIndex = 3\nOutput: [1,3,3,1]\n
Example 2:
\nInput: rowIndex = 0\nOutput: [1]\n
Example 3:
\nInput: rowIndex = 1\nOutput: [1,1]\n\n
\n
Constraints:
\n\n0 <= rowIndex <= 33
\n
Follow up: Could you optimize your algorithm to use only O(rowIndex)
extra space?
Given a triangle
array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i
on the current row, you may move to either index i
or index i + 1
on the next row.
\n
Example 1:
\n\n\nInput: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput: 11\nExplanation: The triangle looks like:\n 2\n 3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n\n\n
Example 2:
\n\n\nInput: triangle = [[-10]]\nOutput: -10\n\n\n
\n
Constraints:
\n\n1 <= triangle.length <= 200
triangle[0].length == 1
triangle[i].length == triangle[i - 1].length + 1
-104 <= triangle[i][j] <= 104
\nFollow up: Could you do this using only
O(n)
extra space, where n
is the total number of rows in the triangle?",
- "likes": 9860,
- "dislikes": 571,
- "stats": "{\"totalAccepted\": \"917.2K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 917173, \"totalSubmissionRaw\": 1568993, \"acRate\": \"58.5%\"}",
+ "likes": 10036,
+ "dislikes": 577,
+ "stats": "{\"totalAccepted\": \"994.6K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 994626, \"totalSubmissionRaw\": 1678519, \"acRate\": \"59.3%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -4452,10 +4452,10 @@
"questionFrontendId": "121",
"title": "Best Time to Buy and Sell Stock",
"content": "You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
\n\nReturn the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
\n
Example 1:
\n\n\nInput: prices = [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.\n\n\n
Example 2:
\n\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transactions are done and the max profit = 0.\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 105
0 <= prices[i] <= 104
You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
\n\nFind and return the maximum profit you can achieve.
\n\n\n
Example 1:
\n\n\nInput: prices = [7,1,5,3,6,4]\nOutput: 7\nExplanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.\n\n\n
Example 2:
\n\n\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.\n\n\n
Example 3:
\n\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
\n\n\n
Example 1:
\n\n\nInput: prices = [3,3,5,0,0,3,1,4]\nOutput: 6\nExplanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n\n
Example 2:
\n\n\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n\n\n
Example 3:
\n\n\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 105
0 <= prices[i] <= 105
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
\n\nThe path sum of a path is the sum of the node's values in the path.
\n\nGiven the root
of a binary tree, return the maximum path sum of any non-empty path.
\n
Example 1:
\n\nInput: root = [1,2,3]\nOutput: 6\nExplanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.\n\n\n
Example 2:
\n\nInput: root = [-10,9,20,null,null,15,7]\nOutput: 42\nExplanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.\n\n\n
\n
Constraints:
\n\n[1, 3 * 104]
.-1000 <= Node.val <= 1000
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
\n\nGiven a string s
, return true
if it is a palindrome, or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "A man, a plan, a canal: Panama"\nOutput: true\nExplanation: "amanaplanacanalpanama" is a palindrome.\n\n\n
Example 2:
\n\n\nInput: s = "race a car"\nOutput: false\nExplanation: "raceacar" is not a palindrome.\n\n\n
Example 3:
\n\n\nInput: s = " "\nOutput: true\nExplanation: s is an empty string "" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.A transformation sequence from word beginWord
to word endWord
using a dictionary wordList
is a sequence of words beginWord -> s1 -> s2 -> ... -> sk
such that:
si
for 1 <= i <= k
is in wordList
. Note that beginWord
does not need to be in wordList
.sk == endWord
Given two words, beginWord
and endWord
, and a dictionary wordList
, return all the shortest transformation sequences from beginWord
to endWord
, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk]
.
\n
Example 1:
\n\n\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]\nOutput: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]\nExplanation: There are 2 shortest transformation sequences:\n"hit" -> "hot" -> "dot" -> "dog" -> "cog"\n"hit" -> "hot" -> "lot" -> "log" -> "cog"\n\n\n
Example 2:
\n\n\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]\nOutput: []\nExplanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.\n\n\n
\n
Constraints:
\n\n1 <= beginWord.length <= 5
endWord.length == beginWord.length
1 <= wordList.length <= 500
wordList[i].length == beginWord.length
beginWord
, endWord
, and wordList[i]
consist of lowercase English letters.beginWord != endWord
wordList
are unique.105
.A transformation sequence from word beginWord
to word endWord
using a dictionary wordList
is a sequence of words beginWord -> s1 -> s2 -> ... -> sk
such that:
si
for 1 <= i <= k
is in wordList
. Note that beginWord
does not need to be in wordList
.sk == endWord
Given two words, beginWord
and endWord
, and a dictionary wordList
, return the number of words in the shortest transformation sequence from beginWord
to endWord
, or 0
if no such sequence exists.
\n
Example 1:
\n\n\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]\nOutput: 5\nExplanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> cog", which is 5 words long.\n\n\n
Example 2:
\n\n\nInput: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]\nOutput: 0\nExplanation: The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.\n\n\n
\n
Constraints:
\n\n1 <= beginWord.length <= 10
endWord.length == beginWord.length
1 <= wordList.length <= 5000
wordList[i].length == beginWord.length
beginWord
, endWord
, and wordList[i]
consist of lowercase English letters.beginWord != endWord
wordList
are unique.Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
\n
Example 1:
\n\n\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.\n
\n\nExample 2:
\n\n\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 105
-109 <= nums[i] <= 109
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
\n
Example 1:
\n\n\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.\n
\n\nExample 2:
\n\n\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n\n\n
Example 3:
\n\n\nInput: nums = [1,0,1,2]\nOutput: 3\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 105
-109 <= nums[i] <= 109
You are given the root
of a binary tree containing digits from 0
to 9
only.
Each root-to-leaf path in the tree represents a number.
\n\n1 -> 2 -> 3
represents the number 123
.Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.
\n\nA leaf node is a node with no children.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3]\nOutput: 25\nExplanation:\nThe root-to-leaf path\n\n1->2
represents the number12
.\nThe root-to-leaf path1->3
represents the number13
.\nTherefore, sum = 12 + 13 =25
.\n
Example 2:
\n\nInput: root = [4,9,0,5,1]\nOutput: 1026\nExplanation:\nThe root-to-leaf path\n\n4->9->5
represents the number 495.\nThe root-to-leaf path4->9->1
represents the number 491.\nThe root-to-leaf path4->0
represents the number 40.\nTherefore, sum = 495 + 491 + 40 =1026
.\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 9
10
.You are given an m x n
matrix board
containing letters 'X'
and 'O'
, capture regions that are surrounded:
'O'
cell.'X'
cells if you can connect the region with 'X'
cells and none of the region cells are on the edge of the board
.To capture a surrounded region, replace all 'O'
s with 'X'
s in-place within the original board. You do not need to return anything.
\n
Example 1:
\n\nInput: board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
\n\nOutput: [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
\n\nExplanation:
\nIn the above diagram, the bottom region is not captured because it is on the edge of the board and cannot be surrounded.
\nExample 2:
\n\nInput: board = [["X"]]
\n\nOutput: [["X"]]
\n\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
is 'X'
or 'O'
.Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
\n
Example 1:
\nInput: s = \"aab\"\nOutput: [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n
Example 2:
\nInput: s = \"a\"\nOutput: [[\"a\"]]\n\n
\n
Constraints:
\n\n1 <= s.length <= 16
s
contains only lowercase English letters.Given a string s
, partition s
such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s
.
\n
Example 1:
\n\n\nInput: s = "aab"\nOutput: 1\nExplanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.\n\n\n
Example 2:
\n\n\nInput: s = "a"\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: s = "ab"\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2000
s
consists of lowercase English letters only.Given a reference of a node in a connected undirected graph.
\n\nReturn a deep copy (clone) of the graph.
\n\nEach node in the graph contains a value (int
) and a list (List[Node]
) of its neighbors.
\nclass Node {\n public int val;\n public List<Node> neighbors;\n}\n\n\n
\n\n
Test case format:
\n\nFor simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1
, the second node with val == 2
, and so on. The graph is represented in the test case using an adjacency list.
An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
\n\nThe given node will always be the first node with val = 1
. You must return the copy of the given node as a reference to the cloned graph.
\n
Example 1:
\n\nInput: adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput: [[2,4],[1,3],[2,4],[1,3]]\nExplanation: There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n\n\n
Example 2:
\n\nInput: adjList = [[]]\nOutput: [[]]\nExplanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\n\n\n
Example 3:
\n\n\nInput: adjList = []\nOutput: []\nExplanation: This an empty graph, it does not have any nodes.\n\n\n
\n
Constraints:
\n\n[0, 100]
.1 <= Node.val <= 100
Node.val
is unique for each node.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.
\n
Example 1:
\n\n\nInput: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput: 3\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n\n\n
Example 2:
\n\n\nInput: gas = [2,3,4], cost = [3,4,3]\nOutput: -1\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n\n\n
\n
Constraints:
\n\nn == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
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.
\n
Example 1:
\n\n\nInput: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput: 3\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\n\n\n
Example 2:
\n\n\nInput: gas = [2,3,4], cost = [3,4,3]\nOutput: -1\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n\n\n
\n
Constraints:
\n\nn == gas.length == cost.length
1 <= n <= 105
0 <= gas[i], cost[i] <= 104
There are n
children standing in a line. Each child is assigned a rating value given in the integer array ratings
.
You are giving candies to these children subjected to the following requirements:
\n\nReturn the minimum number of candies you need to have to distribute the candies to the children.
\n\n\n
Example 1:
\n\n\nInput: ratings = [1,0,2]\nOutput: 5\nExplanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n\n\n
Example 2:
\n\n\nInput: ratings = [1,2,2]\nOutput: 4\nExplanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.\n\n\n
\n
Constraints:
\n\nn == ratings.length
1 <= n <= 2 * 104
0 <= ratings[i] <= 2 * 104
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
\n\n\n
Example 1:
\n\nInput: nums = [2,2,1]
\n\nOutput: 1
\nExample 2:
\n\nInput: nums = [4,1,2,1,2]
\n\nOutput: 4
\nExample 3:
\n\nInput: nums = [1]
\n\nOutput: 1
\n\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
Given an integer array nums
where every element appears three times except for one, which appears exactly once. Find the single element and return it.
You must implement a solution with a linear runtime complexity and use only constant extra space.
\n\n\n
Example 1:
\nInput: nums = [2,2,3,2]\nOutput: 3\n
Example 2:
\nInput: nums = [0,1,0,1,0,1,99]\nOutput: 99\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums
appears exactly three times except for one element which appears once.A linked list of length n
is given such that each node contains an additional random pointer, which could point to any node in the list, or null
.
Construct a deep copy of the list. The deep copy should consist of exactly n
brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next
and random
pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X
and Y
in the original list, where X.random --> Y
, then for the corresponding two nodes x
and y
in the copied list, x.random --> y
.
Return the head of the copied linked list.
\n\nThe linked list is represented in the input/output as a list of n
nodes. Each node is represented as a pair of [val, random_index]
where:
val
: an integer representing Node.val
random_index
: the index of the node (range from 0
to n-1
) that the random
pointer points to, or null
if it does not point to any node.Your code will only be given the head
of the original linked list.
\n
Example 1:
\n\nInput: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput: [[7,null],[13,0],[11,4],[10,2],[1,0]]\n\n\n
Example 2:
\n\nInput: head = [[1,1],[2,1]]\nOutput: [[1,1],[2,1]]\n\n\n
Example 3:
\n\n\nInput: head = [[3,null],[3,0],[3,null]]\nOutput: [[3,null],[3,0],[3,null]]\n\n\n
\n
Constraints:
\n\n0 <= n <= 1000
-104 <= Node.val <= 104
Node.random
is null
or is pointing to some node in the linked list.Given a string s
and a dictionary of strings wordDict
, return true
if s
can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
\n\n\n
Example 1:
\n\n\nInput: s = "leetcode", wordDict = ["leet","code"]\nOutput: true\nExplanation: Return true because "leetcode" can be segmented as "leet code".\n\n\n
Example 2:
\n\n\nInput: s = "applepenapple", wordDict = ["apple","pen"]\nOutput: true\nExplanation: Return true because "applepenapple" can be segmented as "apple pen apple".\nNote that you are allowed to reuse a dictionary word.\n\n\n
Example 3:
\n\n\nInput: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s
and wordDict[i]
consist of only lowercase English letters.wordDict
are unique.Given a string s
and a dictionary of strings wordDict
, add spaces in s
to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
\n\n\n
Example 1:
\n\n\nInput: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]\nOutput: ["cats and dog","cat sand dog"]\n\n\n
Example 2:
\n\n\nInput: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]\nOutput: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]\nExplanation: Note that you are allowed to reuse a dictionary word.\n\n\n
Example 3:
\n\n\nInput: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]\nOutput: []\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 20
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 10
s
and wordDict[i]
consist of only lowercase English letters.wordDict
are unique.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
.
\n
Example 1:
\n\nInput: head = [3,2,0,-4], pos = 1\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n\n\n
Example 2:
\n\nInput: head = [1,2], pos = 0\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 0th node.\n\n\n
Example 3:
\n\nInput: head = [1], pos = -1\nOutput: false\nExplanation: There is no cycle in the linked list.\n\n\n
\n
Constraints:
\n\n[0, 104]
.-105 <= Node.val <= 105
pos
is -1
or a valid index in the linked-list.\n
Follow up: Can you solve it using O(1)
(i.e. constant) memory?
Given the head
of a linked list, return the node where the cycle begins. If there is no cycle, return null
.
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 (0-indexed). It is -1
if there is no cycle. Note that pos
is not passed as a parameter.
Do not modify the linked list.
\n\n\n
Example 1:
\n\nInput: head = [3,2,0,-4], pos = 1\nOutput: tail connects to node index 1\nExplanation: There is a cycle in the linked list, where tail connects to the second node.\n\n\n
Example 2:
\n\nInput: head = [1,2], pos = 0\nOutput: tail connects to node index 0\nExplanation: There is a cycle in the linked list, where tail connects to the first node.\n\n\n
Example 3:
\n\nInput: head = [1], pos = -1\nOutput: no cycle\nExplanation: There is no cycle in the linked list.\n\n\n
\n
Constraints:
\n\n[0, 104]
.-105 <= Node.val <= 105
pos
is -1
or a valid index in the linked-list.\n
Follow up: Can you solve it using O(1)
(i.e. constant) memory?
You are given the head of a singly linked-list. The list can be represented as:
\n\n\nL0 → L1 → … → Ln - 1 → Ln\n\n\n
Reorder the list to be on the following form:
\n\n\nL0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …\n\n\n
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
\n\n\n
Example 1:
\n\nInput: head = [1,2,3,4]\nOutput: [1,4,2,3]\n\n\n
Example 2:
\n\nInput: head = [1,2,3,4,5]\nOutput: [1,5,2,4,3]\n\n\n
\n
Constraints:
\n\n[1, 5 * 104]
.1 <= Node.val <= 1000
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
\n
Example 1:
\n\nInput: root = [1,null,2,3]
\n\nOutput: [1,2,3]
\n\nExplanation:
\n\nExample 2:
\n\nInput: root = [1,2,3,4,5,null,8,null,null,6,7,9]
\n\nOutput: [1,2,4,5,6,7,3,8,9]
\n\nExplanation:
\n\nExample 3:
\n\nInput: root = []
\n\nOutput: []
\nExample 4:
\n\nInput: root = [1]
\n\nOutput: [1]
\n\n
Constraints:
\n\n[0, 100]
.-100 <= Node.val <= 100
\n
Follow up: Recursive solution is trivial, could you do it iteratively?
\n", - "likes": 8256, - "dislikes": 215, - "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"2.6M\", \"totalAcceptedRaw\": 1900261, \"totalSubmissionRaw\": 2637090, \"acRate\": \"72.1%\"}", + "likes": 8442, + "dislikes": 223, + "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"2.8M\", \"totalAcceptedRaw\": 2045521, \"totalSubmissionRaw\": 2795047, \"acRate\": \"73.2%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Verify Preorder Sequence in Binary Search Tree\", \"titleSlug\": \"verify-preorder-sequence-in-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Preorder Traversal\", \"titleSlug\": \"n-ary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Sum in a Binary Tree\", \"titleSlug\": \"kth-largest-sum-in-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -5362,9 +5362,9 @@ "questionFrontendId": "145", "title": "Binary Tree Postorder Traversal", "content": "Given the root
of a binary tree, return the postorder traversal of its nodes' values.
\n
Example 1:
\n\nInput: root = [1,null,2,3]
\n\nOutput: [3,2,1]
\n\nExplanation:
\n\nExample 2:
\n\nInput: root = [1,2,3,4,5,null,8,null,null,6,7,9]
\n\nOutput: [4,6,7,5,2,9,8,3,1]
\n\nExplanation:
\n\nExample 3:
\n\nInput: root = []
\n\nOutput: []
\nExample 4:
\n\nInput: root = [1]
\n\nOutput: [1]
\n\n
Constraints:
\n\n[0, 100]
.-100 <= Node.val <= 100
\nFollow up: Recursive solution is trivial, could you do it iteratively?", - "likes": 7300, - "dislikes": 209, - "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1526327, \"totalSubmissionRaw\": 2045060, \"acRate\": \"74.6%\"}", + "likes": 7430, + "dislikes": 217, + "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1643151, \"totalSubmissionRaw\": 2170585, \"acRate\": \"75.7%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Postorder Traversal\", \"titleSlug\": \"n-ary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Fuel Cost to Report to the Capital\", \"titleSlug\": \"minimum-fuel-cost-to-report-to-the-capital\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -5402,9 +5402,9 @@ "questionFrontendId": "146", "title": "LRU Cache", "content": "
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
\n\nImplement 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.
\n
Example 1:
\n\n\nInput\n["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\nExplanation\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4\n\n\n
\n
Constraints:
\n\n1 <= capacity <= 3000
0 <= key <= 104
0 <= value <= 105
2 * 105
calls will be made to get
and put
.Given the head
of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
\n\nThe following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
\n\n
Example 1:
\n\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\n\n\n
Example 2:
\n\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n\n\n
\n
Constraints:
\n\n[1, 5000]
.-5000 <= Node.val <= 5000
Given the head
of a linked list, return the list after sorting it in ascending order.
\n
Example 1:
\n\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\n\n\n
Example 2:
\n\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n\n\n
Example 3:
\n\n\nInput: head = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 5 * 104]
.-105 <= Node.val <= 105
\n
Follow up: Can you sort the linked list in O(n logn)
time and O(1)
memory (i.e. constant space)?
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
\n
Example 1:
\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 3\n\n\n
Example 2:
\n\nInput: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
points
are unique.You are given an array of strings tokens
that represents an arithmetic expression in a Reverse Polish Notation.
Evaluate the expression. Return an integer that represents the value of the expression.
\n\nNote that:
\n\n'+'
, '-'
, '*'
, and '/'
.\n
Example 1:
\n\n\nInput: tokens = ["2","1","+","3","*"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\n\n\n
Example 2:
\n\n\nInput: tokens = ["4","13","5","/","+"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\n\n\n
Example 3:
\n\n\nInput: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]\nOutput: 22\nExplanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22\n\n\n
\n
Constraints:
\n\n1 <= tokens.length <= 104
tokens[i]
is either an operator: "+"
, "-"
, "*"
, or "/"
, or an integer in the range [-200, 200]
.Given an input string s
, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
\n\nNote that s
may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
\n
Example 1:
\n\n\nInput: s = "the sky is blue"\nOutput: "blue is sky the"\n\n\n
Example 2:
\n\n\nInput: s = " hello world "\nOutput: "world hello"\nExplanation: Your reversed string should not contain leading or trailing spaces.\n\n\n
Example 3:
\n\n\nInput: s = "a good example"\nOutput: "example good a"\nExplanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
contains English letters (upper-case and lower-case), digits, and spaces ' '
.s
.\n
Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1)
extra space?
Given an integer array nums
, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,-2,4]\nOutput: 6\nExplanation: [2,3] has the largest product 6.\n\n\n
Example 2:
\n\n\nInput: nums = [-2,0,-1]\nOutput: 0\nExplanation: The result cannot be 2, because [-2,-1] is not a subarray.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums
is guaranteed to fit in a 32-bit integer.Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times. For example, the array nums = [0,1,2,4,5,6,7]
might become:
[4,5,6,7,0,1,2]
if it was rotated 4
times.[0,1,2,4,5,6,7]
if it was rotated 7
times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time
.
\n
Example 1:
\n\n\nInput: nums = [3,4,5,1,2]\nOutput: 1\nExplanation: The original array was [1,2,3,4,5] rotated 3 times.\n\n\n
Example 2:
\n\n\nInput: nums = [4,5,6,7,0,1,2]\nOutput: 0\nExplanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\n\n\n
Example 3:
\n\n\nInput: nums = [11,13,15,17]\nOutput: 11\nExplanation: The original array was [11,13,15,17] and it was rotated 4 times. \n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums
are unique.nums
is sorted and rotated between 1
and n
times.Suppose an array of length n
sorted in ascending order is rotated between 1
and n
times. For example, the array nums = [0,1,4,4,5,6,7]
might become:
[4,5,6,7,0,1,4]
if it was rotated 4
times.[0,1,4,4,5,6,7]
if it was rotated 7
times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
that may contain duplicates, return the minimum element of this array.
You must decrease the overall operation steps as much as possible.
\n\n\n
Example 1:
\nInput: nums = [1,3,5]\nOutput: 1\n
Example 2:
\nInput: nums = [2,2,2,0,1]\nOutput: 0\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
nums
is sorted and rotated between 1
and n
times.\n
Follow up: This problem is similar to Find Minimum in Rotated Sorted Array, but nums
may contain duplicates. Would this affect the runtime complexity? How and why?
\n", - "likes": 4811, - "dislikes": 501, - "stats": "{\"totalAccepted\": \"504.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 504828, \"totalSubmissionRaw\": 1148596, \"acRate\": \"44.0%\"}", + "likes": 4888, + "dislikes": 505, + "stats": "{\"totalAccepted\": \"531.9K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 531860, \"totalSubmissionRaw\": 1205819, \"acRate\": \"44.1%\"}", "similarQuestions": "[{\"title\": \"Find Minimum in Rotated Sorted Array\", \"titleSlug\": \"find-minimum-in-rotated-sorted-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -5736,9 +5736,9 @@ "questionFrontendId": "155", "title": "Min Stack", "content": "
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
\n\nImplement the MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the element val
onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.You must implement a solution with O(1)
time complexity for each function.
\n
Example 1:
\n\n\nInput\n["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]\n\nOutput\n[null,null,null,null,-3,null,0,-2]\n\nExplanation\nMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2\n\n\n
\n
Constraints:
\n\n-231 <= val <= 231 - 1
pop
, top
and getMin
operations will always be called on non-empty stacks.3 * 104
calls will be made to push
, pop
, top
, and getMin
.Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
For example, the following two linked lists begin to intersect at node c1
:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
\n\nNote that the linked lists must retain their original structure after the function returns.
\n\nCustom Judge:
\n\nThe inputs to the judge are given as follows (your program is not given these inputs):
\n\nintersectVal
- The value of the node where the intersection occurs. This is 0
if there is no intersected node.listA
- The first linked list.listB
- The second linked list.skipA
- The number of nodes to skip ahead in listA
(starting from the head) to get to the intersected node.skipB
- The number of nodes to skip ahead in listB
(starting from the head) to get to the intersected node.The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
\n
Example 1:
\n\nInput: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput: Intersected at '8'\nExplanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.\n\n\n
Example 2:
\n\nInput: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput: Intersected at '2'\nExplanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\n\n\n
Example 3:
\n\nInput: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput: No intersection\nExplanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.\n\n\n
\n
Constraints:
\n\nlistA
is in the m
.listB
is in the n
.1 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
intersectVal
is 0
if listA
and listB
do not intersect.intersectVal == listA[skipA] == listB[skipB]
if listA
and listB
intersect.\nFollow up: Could you write a solution that runs in
O(m + n)
time and use only O(1)
memory?",
- "likes": 15487,
- "dislikes": 1407,
- "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"3.1M\", \"totalAcceptedRaw\": 1849957, \"totalSubmissionRaw\": 3082042, \"acRate\": \"60.0%\"}",
+ "likes": 15795,
+ "dislikes": 1438,
+ "stats": "{\"totalAccepted\": \"2M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1988141, \"totalSubmissionRaw\": 3255008, \"acRate\": \"61.1%\"}",
"similarQuestions": "[{\"title\": \"Minimum Index Sum of Two Lists\", \"titleSlug\": \"minimum-index-sum-of-two-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -5951,9 +5951,9 @@
"questionFrontendId": "161",
"title": "One Edit Distance",
"content": null,
- "likes": 1416,
- "dislikes": 191,
- "stats": "{\"totalAccepted\": \"220.4K\", \"totalSubmission\": \"640.1K\", \"totalAcceptedRaw\": 220366, \"totalSubmissionRaw\": 640095, \"acRate\": \"34.4%\"}",
+ "likes": 1426,
+ "dislikes": 192,
+ "stats": "{\"totalAccepted\": \"225.8K\", \"totalSubmission\": \"655K\", \"totalAcceptedRaw\": 225832, \"totalSubmissionRaw\": 654985, \"acRate\": \"34.5%\"}",
"similarQuestions": "[{\"title\": \"Edit Distance\", \"titleSlug\": \"edit-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -5985,9 +5985,9 @@
"questionFrontendId": "162",
"title": "Find Peak Element",
"content": "A peak element is an element that is strictly greater than its neighbors.
\n\nGiven a 0-indexed integer array nums
, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞
. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n)
time.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,3,5,6,4]\nOutput: 5\nExplanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
nums[i] != nums[i + 1]
for all valid i
.Given an integer array nums
, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0
.
You must write an algorithm that runs in linear time and uses linear extra space.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,6,9,1]\nOutput: 3\nExplanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n\n\n
Example 2:
\n\n\nInput: nums = [10]\nOutput: 0\nExplanation: The array contains less than 2 elements, therefore return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
Given two version strings, version1
and version2
, compare them. A version string consists of revisions separated by dots '.'
. The value of the revision is its integer conversion ignoring leading zeros.
To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0
.
Return the following:
\n\nversion1 < version2
, return -1.version1 > version2
, return 1.\n
Example 1:
\n\nInput: version1 = "1.2", version2 = "1.10"
\n\nOutput: -1
\n\nExplanation:
\n\nversion1's second revision is "2" and version2's second revision is "10": 2 < 10, so version1 < version2.
\nExample 2:
\n\nInput: version1 = "1.01", version2 = "1.001"
\n\nOutput: 0
\n\nExplanation:
\n\nIgnoring leading zeroes, both "01" and "001" represent the same integer "1".
\nExample 3:
\n\nInput: version1 = "1.0", version2 = "1.0.0.0"
\n\nOutput: 0
\n\nExplanation:
\n\nversion1 has less revisions, which means every missing revision are treated as "0".
\n\n
Constraints:
\n\n1 <= version1.length, version2.length <= 500
version1
and version2
only contain digits and '.'
.version1
and version2
are valid version numbers.version1
and version2
can be stored in a 32-bit integer.Given two integers representing the numerator
and denominator
of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
\n\nIf multiple answers are possible, return any of them.
\n\nIt is guaranteed that the length of the answer string is less than 104
for all the given inputs.
\n
Example 1:
\n\n\nInput: numerator = 1, denominator = 2\nOutput: "0.5"\n\n\n
Example 2:
\n\n\nInput: numerator = 2, denominator = 1\nOutput: "2"\n\n\n
Example 3:
\n\n\nInput: numerator = 4, denominator = 333\nOutput: "0.(012)"\n\n\n
\n
Constraints:
\n\n-231 <= numerator, denominator <= 231 - 1
denominator != 0
Given a 1-indexed array of integers numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target
number. Let these two numbers be numbers[index1]
and numbers[index2]
where 1 <= index1 < index2 <= numbers.length
.
Return the indices of the two numbers, index1
and index2
, added by one as an integer array [index1, index2]
of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
\n\nYour solution must use only constant extra space.
\n\n\n
Example 1:
\n\n\nInput: numbers = [2,7,11,15], target = 9\nOutput: [1,2]\nExplanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].\n\n\n
Example 2:
\n\n\nInput: numbers = [2,3,4], target = 6\nOutput: [1,3]\nExplanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].\n\n\n
Example 3:
\n\n\nInput: numbers = [-1,0], target = -1\nOutput: [1,2]\nExplanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].\n\n\n
\n
Constraints:
\n\n2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers
is sorted in non-decreasing order.-1000 <= target <= 1000
Given an integer columnNumber
, return its corresponding column title as it appears in an Excel sheet.
For example:
\n\n\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n\n\n
\n
Example 1:
\n\n\nInput: columnNumber = 1\nOutput: "A"\n\n\n
Example 2:
\n\n\nInput: columnNumber = 28\nOutput: "AB"\n\n\n
Example 3:
\n\n\nInput: columnNumber = 701\nOutput: "ZY"\n\n\n
\n
Constraints:
\n\n1 <= columnNumber <= 231 - 1
Given an array nums
of size n
, return the majority element.
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
\n
Example 1:
\nInput: nums = [3,2,3]\nOutput: 3\n
Example 2:
\nInput: nums = [2,2,1,1,1,2,2]\nOutput: 2\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 5 * 104
-109 <= nums[i] <= 109
\nFollow-up: Could you solve the problem in linear time and in
O(1)
space?",
- "likes": 20360,
- "dislikes": 705,
- "stats": "{\"totalAccepted\": \"3.9M\", \"totalSubmission\": \"5.9M\", \"totalAcceptedRaw\": 3866505, \"totalSubmissionRaw\": 5907585, \"acRate\": \"65.4%\"}",
- "similarQuestions": "[{\"title\": \"Majority Element II\", \"titleSlug\": \"majority-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check If a Number Is Majority Element in a Sorted Array\", \"titleSlug\": \"check-if-a-number-is-majority-element-in-a-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Index of a Valid Split\", \"titleSlug\": \"minimum-index-of-a-valid-split\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Exceed Threshold Value I\", \"titleSlug\": \"minimum-operations-to-exceed-threshold-value-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Valid Pair of Adjacent Digits in String\", \"titleSlug\": \"find-valid-pair-of-adjacent-digits-in-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
+ "likes": 21019,
+ "dislikes": 737,
+ "stats": "{\"totalAccepted\": \"4.3M\", \"totalSubmission\": \"6.6M\", \"totalAcceptedRaw\": 4324201, \"totalSubmissionRaw\": 6578462, \"acRate\": \"65.7%\"}",
+ "similarQuestions": "[{\"title\": \"Majority Element II\", \"titleSlug\": \"majority-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Check If a Number Is Majority Element in a Sorted Array\", \"titleSlug\": \"check-if-a-number-is-majority-element-in-a-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Most Frequent Even Element\", \"titleSlug\": \"most-frequent-even-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Index of a Valid Split\", \"titleSlug\": \"minimum-index-of-a-valid-split\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Exceed Threshold Value I\", \"titleSlug\": \"minimum-operations-to-exceed-threshold-value-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Most Common Response\", \"titleSlug\": \"find-the-most-common-response\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Valid Pair of Adjacent Digits in String\", \"titleSlug\": \"find-valid-pair-of-adjacent-digits-in-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
"topicTags": [
@@ -6283,9 +6283,9 @@
"questionFrontendId": "170",
"title": "Two Sum III - Data structure design",
"content": null,
- "likes": 686,
- "dislikes": 453,
- "stats": "{\"totalAccepted\": \"165.8K\", \"totalSubmission\": \"430.2K\", \"totalAcceptedRaw\": 165792, \"totalSubmissionRaw\": 430226, \"acRate\": \"38.5%\"}",
+ "likes": 691,
+ "dislikes": 457,
+ "stats": "{\"totalAccepted\": \"170.3K\", \"totalSubmission\": \"440.1K\", \"totalAcceptedRaw\": 170272, \"totalSubmissionRaw\": 440145, \"acRate\": \"38.7%\"}",
"similarQuestions": "[{\"title\": \"Two Sum\", \"titleSlug\": \"two-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Unique Word Abbreviation\", \"titleSlug\": \"unique-word-abbreviation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Two Sum IV - Input is a BST\", \"titleSlug\": \"two-sum-iv-input-is-a-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -6326,9 +6326,9 @@
"questionFrontendId": "171",
"title": "Excel Sheet Column Number",
"content": "Given a string columnTitle
that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
\n\n\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n\n\n
\n
Example 1:
\n\n\nInput: columnTitle = "A"\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: columnTitle = "AB"\nOutput: 28\n\n\n
Example 3:
\n\n\nInput: columnTitle = "ZY"\nOutput: 701\n\n\n
\n
Constraints:
\n\n1 <= columnTitle.length <= 7
columnTitle
consists only of uppercase English letters.columnTitle
is in the range ["A", "FXSHRXW"]
.Given an integer n
, return the number of trailing zeroes in n!
.
Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 0\nExplanation: 3! = 6, no trailing zero.\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: 1\nExplanation: 5! = 120, one trailing zero.\n\n\n
Example 3:
\n\n\nInput: n = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= n <= 104
\n
Follow up: Could you write a solution that works in logarithmic time complexity?
\n", - "likes": 3312, - "dislikes": 1969, - "stats": "{\"totalAccepted\": \"526.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 526430, \"totalSubmissionRaw\": 1186330, \"acRate\": \"44.4%\"}", + "likes": 3368, + "dislikes": 1975, + "stats": "{\"totalAccepted\": \"561.7K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 561716, \"totalSubmissionRaw\": 1252654, \"acRate\": \"44.8%\"}", "similarQuestions": "[{\"title\": \"Number of Digit One\", \"titleSlug\": \"number-of-digit-one\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Preimage Size of Factorial Zeroes Function\", \"titleSlug\": \"preimage-size-of-factorial-zeroes-function\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Abbreviating the Product of a Range\", \"titleSlug\": \"abbreviating-the-product-of-a-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Trailing Zeros in a Cornered Path\", \"titleSlug\": \"maximum-trailing-zeros-in-a-cornered-path\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -6391,9 +6391,9 @@ "questionFrontendId": "173", "title": "Binary Search Tree Iterator", "content": "Implement the BSTIterator
class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root)
Initializes an object of the BSTIterator
class. The root
of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.boolean hasNext()
Returns true
if there exists a number in the traversal to the right of the pointer, otherwise returns false
.int next()
Moves the pointer to the right, then returns the number at the pointer.Notice that by initializing the pointer to a non-existent smallest number, the first call to next()
will return the smallest element in the BST.
You may assume that next()
calls will always be valid. That is, there will be at least a next number in the in-order traversal when next()
is called.
\n
Example 1:
\n\nInput\n["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\nOutput\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\nExplanation\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False\n\n\n
\n
Constraints:
\n\n[1, 105]
.0 <= Node.val <= 106
105
calls will be made to hasNext
, and next
.\n
Follow up:
\n\nnext()
and hasNext()
to run in average O(1)
time and use O(h)
memory, where h
is the height of the tree?The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon
. The dungeon
consists of m x n
rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon
to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0
or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
\n\nTo reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
\n\nReturn the knight's minimum initial health so that he can rescue the princess.
\n\nNote that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
\n\n\n
Example 1:
\n\nInput: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput: 7\nExplanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\n\n\n
Example 2:
\n\n\nInput: dungeon = [[0]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nm == dungeon.length
n == dungeon[i].length
1 <= m, n <= 200
-1000 <= dungeon[i][j] <= 1000
Table: Person
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| personId | int |\n| lastName | varchar |\n| firstName | varchar |\n+-------------+---------+\npersonId is the primary key (column with unique values) for this table.\nThis table contains information about the ID of some persons and their first and last names.\n\n\n
\n\n
Table: Address
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| addressId | int |\n| personId | int |\n| city | varchar |\n| state | varchar |\n+-------------+---------+\naddressId is the primary key (column with unique values) for this table.\nEach row of this table contains information about the city and state of one person with ID = PersonId.\n\n\n
\n\n
Write a solution to report the first name, last name, city, and state of each person in the Person
table. If the address of a personId
is not present in the Address
table, report null
instead.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nPerson table:\n+----------+----------+-----------+\n| personId | lastName | firstName |\n+----------+----------+-----------+\n| 1 | Wang | Allen |\n| 2 | Alice | Bob |\n+----------+----------+-----------+\nAddress table:\n+-----------+----------+---------------+------------+\n| addressId | personId | city | state |\n+-----------+----------+---------------+------------+\n| 1 | 2 | New York City | New York |\n| 2 | 3 | Leetcode | California |\n+-----------+----------+---------------+------------+\nOutput: \n+-----------+----------+---------------+----------+\n| firstName | lastName | city | state |\n+-----------+----------+---------------+----------+\n| Allen | Wang | Null | Null |\n| Bob | Alice | New York City | New York |\n+-----------+----------+---------------+----------+\nExplanation: \nThere is no address in the address table for the personId = 1 so we return null in their city and state.\naddressId = 1 contains information about the address of personId = 2.\n\n", - "likes": 3649, - "dislikes": 231, - "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 1192794, \"totalSubmissionRaw\": 1540145, \"acRate\": \"77.4%\"}", + "likes": 3779, + "dislikes": 235, + "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 1309042, \"totalSubmissionRaw\": 1676920, \"acRate\": \"78.1%\"}", "similarQuestions": "[{\"title\": \"Employee Bonus\", \"titleSlug\": \"employee-bonus\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -6505,9 +6505,9 @@ "questionFrontendId": "176", "title": "Second Highest Salary", "content": "
Table: Employee
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id | int |\n| salary | int |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n\n\n
\n\n
Write a solution to find the second highest distinct salary from the Employee
table. If there is no second highest salary, return null (return None in Pandas)
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n| 2 | 200 |\n| 3 | 300 |\n+----+--------+\nOutput: \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| 200 |\n+---------------------+\n\n\n
Example 2:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n+----+--------+\nOutput: \n+---------------------+\n| SecondHighestSalary |\n+---------------------+\n| null |\n+---------------------+\n\n", - "likes": 3754, - "dislikes": 982, - "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1051099, \"totalSubmissionRaw\": 2458975, \"acRate\": \"42.7%\"}", + "likes": 3858, + "dislikes": 993, + "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1161987, \"totalSubmissionRaw\": 2651478, \"acRate\": \"43.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6535,10 +6535,10 @@ "questionId": "177", "questionFrontendId": "177", "title": "Nth Highest Salary", - "content": "
Table: Employee
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id | int |\n| salary | int |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n\n\n
\n\n
Write a solution to find the nth
highest salary from the Employee
table. If there is no nth
highest salary, return null
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n| 2 | 200 |\n| 3 | 300 |\n+----+--------+\nn = 2\nOutput: \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| 200 |\n+------------------------+\n\n\n
Example 2:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n+----+--------+\nn = 2\nOutput: \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| null |\n+------------------------+\n\n", - "likes": 2062, - "dislikes": 1073, - "stats": "{\"totalAccepted\": \"456.5K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 456521, \"totalSubmissionRaw\": 1203682, \"acRate\": \"37.9%\"}", + "content": "
Table: Employee
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id | int |\n| salary | int |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains information about the salary of an employee.\n\n\n
\n\n
Write a solution to find the nth
highest distinct salary from the Employee
table. If there are less than n
distinct salaries, return null
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n| 2 | 200 |\n| 3 | 300 |\n+----+--------+\nn = 2\nOutput: \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| 200 |\n+------------------------+\n\n\n
Example 2:
\n\n\nInput: \nEmployee table:\n+----+--------+\n| id | salary |\n+----+--------+\n| 1 | 100 |\n+----+--------+\nn = 2\nOutput: \n+------------------------+\n| getNthHighestSalary(2) |\n+------------------------+\n| null |\n+------------------------+\n\n", + "likes": 2122, + "dislikes": 1093, + "stats": "{\"totalAccepted\": \"499.4K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 499391, \"totalSubmissionRaw\": 1313735, \"acRate\": \"38.0%\"}", "similarQuestions": "[{\"title\": \"The Number of Users That Are Eligible for Discount\", \"titleSlug\": \"the-number-of-users-that-are-eligible-for-discount\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -6567,9 +6567,9 @@ "questionFrontendId": "178", "title": "Rank Scores", "content": "
Table: Scores
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| score | decimal |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains the score of a game. Score is a floating point value with two decimal places.\n\n\n
\n\n
Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:
\n\nReturn the result table ordered by score
in descending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nScores table:\n+----+-------+\n| id | score |\n+----+-------+\n| 1 | 3.50 |\n| 2 | 3.65 |\n| 3 | 4.00 |\n| 4 | 3.85 |\n| 5 | 4.00 |\n| 6 | 3.65 |\n+----+-------+\nOutput: \n+-------+------+\n| score | rank |\n+-------+------+\n| 4.00 | 1 |\n| 4.00 | 1 |\n| 3.85 | 2 |\n| 3.65 | 3 |\n| 3.65 | 3 |\n| 3.50 | 4 |\n+-------+------+\n\n", - "likes": 2231, - "dislikes": 281, - "stats": "{\"totalAccepted\": \"457.6K\", \"totalSubmission\": \"711K\", \"totalAcceptedRaw\": 457563, \"totalSubmissionRaw\": 710968, \"acRate\": \"64.4%\"}", + "likes": 2288, + "dislikes": 284, + "stats": "{\"totalAccepted\": \"503.2K\", \"totalSubmission\": \"771K\", \"totalAcceptedRaw\": 503182, \"totalSubmissionRaw\": 770951, \"acRate\": \"65.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6598,9 +6598,9 @@ "questionFrontendId": "179", "title": "Largest Number", "content": "
Given a list of non-negative integers nums
, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [10,2]\nOutput: "210"\n\n\n
Example 2:
\n\n\nInput: nums = [3,30,34,5,9]\nOutput: "9534330"\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 109
Table: Logs
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| num | varchar |\n+-------------+---------+\nIn SQL, id is the primary key for this table.\nid is an autoincrement column starting from 1.\n\n\n
\n\n
Find all numbers that appear at least three times consecutively.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nLogs table:\n+----+-----+\n| id | num |\n+----+-----+\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 2 |\n| 5 | 1 |\n| 6 | 2 |\n| 7 | 2 |\n+----+-----+\nOutput: \n+-----------------+\n| ConsecutiveNums |\n+-----------------+\n| 1 |\n+-----------------+\nExplanation: 1 is the only number that appears consecutively for at least three times.\n\n", - "likes": 2293, - "dislikes": 334, - "stats": "{\"totalAccepted\": \"495.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 495289, \"totalSubmissionRaw\": 1096816, \"acRate\": \"45.2%\"}", + "likes": 2406, + "dislikes": 342, + "stats": "{\"totalAccepted\": \"564K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 563966, \"totalSubmissionRaw\": 1223914, \"acRate\": \"46.1%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6669,9 +6669,9 @@ "questionFrontendId": "181", "title": "Employees Earning More Than Their Managers", "content": "
Table: Employee
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n| salary | int |\n| managerId | int |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.\n\n\n
\n\n
Write a solution to find the employees who earn more than their managers.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+-------+--------+-----------+\n| id | name | salary | managerId |\n+----+-------+--------+-----------+\n| 1 | Joe | 70000 | 3 |\n| 2 | Henry | 80000 | 4 |\n| 3 | Sam | 60000 | Null |\n| 4 | Max | 90000 | Null |\n+----+-------+--------+-----------+\nOutput: \n+----------+\n| Employee |\n+----------+\n| Joe |\n+----------+\nExplanation: Joe is the only employee who earns more than his manager.\n\n", - "likes": 2715, - "dislikes": 269, - "stats": "{\"totalAccepted\": \"755.4K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 755405, \"totalSubmissionRaw\": 1065169, \"acRate\": \"70.9%\"}", + "likes": 2802, + "dislikes": 279, + "stats": "{\"totalAccepted\": \"829.1K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 829118, \"totalSubmissionRaw\": 1159288, \"acRate\": \"71.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6700,9 +6700,9 @@ "questionFrontendId": "182", "title": "Duplicate Emails", "content": "
Table: Person
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| email | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains an email. The emails will not contain uppercase letters.\n\n\n
\n\n
Write a solution to report all the duplicate emails. Note that it's guaranteed that the email field is not NULL.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nPerson table:\n+----+---------+\n| id | email |\n+----+---------+\n| 1 | a@b.com |\n| 2 | c@d.com |\n| 3 | a@b.com |\n+----+---------+\nOutput: \n+---------+\n| Email |\n+---------+\n| a@b.com |\n+---------+\nExplanation: a@b.com is repeated two times.\n\n", - "likes": 2168, - "dislikes": 75, - "stats": "{\"totalAccepted\": \"785.9K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 785857, \"totalSubmissionRaw\": 1091371, \"acRate\": \"72.0%\"}", + "likes": 2230, + "dislikes": 76, + "stats": "{\"totalAccepted\": \"862.8K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 862780, \"totalSubmissionRaw\": 1191146, \"acRate\": \"72.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6731,9 +6731,9 @@ "questionFrontendId": "183", "title": "Customers Who Never Order", "content": "
Table: Customers
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID and name of a customer.\n\n\n
\n\n
Table: Orders
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id | int |\n| customerId | int |\n+-------------+------+\nid is the primary key (column with unique values) for this table.\ncustomerId is a foreign key (reference columns) of the ID from the Customers table.\nEach row of this table indicates the ID of an order and the ID of the customer who ordered it.\n\n\n
\n\n
Write a solution to find all customers who never order anything.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCustomers table:\n+----+-------+\n| id | name |\n+----+-------+\n| 1 | Joe |\n| 2 | Henry |\n| 3 | Sam |\n| 4 | Max |\n+----+-------+\nOrders table:\n+----+------------+\n| id | customerId |\n+----+------------+\n| 1 | 3 |\n| 2 | 1 |\n+----+------------+\nOutput: \n+-----------+\n| Customers |\n+-----------+\n| Henry |\n| Max |\n+-----------+\n\n", - "likes": 2731, - "dislikes": 141, - "stats": "{\"totalAccepted\": \"938.7K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 938726, \"totalSubmissionRaw\": 1337138, \"acRate\": \"70.2%\"}", + "likes": 2801, + "dislikes": 144, + "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 1017888, \"totalSubmissionRaw\": 1440612, \"acRate\": \"70.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -6762,9 +6762,9 @@ "questionFrontendId": "184", "title": "Department Highest Salary", "content": "
Table: Employee
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| id | int |\n| name | varchar |\n| salary | int |\n| departmentId | int |\n+--------------+---------+\nid is the primary key (column with unique values) for this table.\ndepartmentId is a foreign key (reference columns) of the ID from the Department
table.\nEach row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.\n
\n\n\n\n
Table: Department
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL.
\nEach row of this table indicates the ID of a department and its name.\n
\n\n\n\n
Write a solution to find employees who have the highest salary in each of the departments.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+-------+--------+--------------+\n| id | name | salary | departmentId |\n+----+-------+--------+--------------+\n| 1 | Joe | 70000 | 1 |\n| 2 | Jim | 90000 | 1 |\n| 3 | Henry | 80000 | 2 |\n| 4 | Sam | 60000 | 2 |\n| 5 | Max | 90000 | 1 |\n+----+-------+--------+--------------+\nDepartment table:\n+----+-------+\n| id | name |\n+----+-------+\n| 1 | IT |\n| 2 | Sales |\n+----+-------+\nOutput: \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT | Jim | 90000 |\n| Sales | Henry | 80000 |\n| IT | Max | 90000 |\n+------------+----------+--------+\nExplanation: Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.\n\n", - "likes": 2141, - "dislikes": 192, - "stats": "{\"totalAccepted\": \"453.4K\", \"totalSubmission\": \"844.4K\", \"totalAcceptedRaw\": 453446, \"totalSubmissionRaw\": 844404, \"acRate\": \"53.7%\"}", + "likes": 2188, + "dislikes": 197, + "stats": "{\"totalAccepted\": \"497.6K\", \"totalSubmission\": \"908.7K\", \"totalAcceptedRaw\": 497636, \"totalSubmissionRaw\": 908685, \"acRate\": \"54.8%\"}", "similarQuestions": "[{\"title\": \"Highest Grade For Each Student\", \"titleSlug\": \"highest-grade-for-each-student\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -6793,9 +6793,9 @@ "questionFrontendId": "185", "title": "Department Top Three Salaries", "content": "
Table: Employee
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| id | int |\n| name | varchar |\n| salary | int |\n| departmentId | int |\n+--------------+---------+\nid is the primary key (column with unique values) for this table.\ndepartmentId is a foreign key (reference column) of the ID from the Department
table.\nEach row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.\n
\n\n\n\n
Table: Department
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the ID of a department and its name.\n\n\n
\n\n
A company's executives are interested in seeing who earns the most money in each of the company's departments. A high earner in a department is an employee who has a salary in the top three unique salaries for that department.
\n\nWrite a solution to find the employees who are high earners in each of the departments.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+----+-------+--------+--------------+\n| id | name | salary | departmentId |\n+----+-------+--------+--------------+\n| 1 | Joe | 85000 | 1 |\n| 2 | Henry | 80000 | 2 |\n| 3 | Sam | 60000 | 2 |\n| 4 | Max | 90000 | 1 |\n| 5 | Janet | 69000 | 1 |\n| 6 | Randy | 85000 | 1 |\n| 7 | Will | 70000 | 1 |\n+----+-------+--------+--------------+\nDepartment table:\n+----+-------+\n| id | name |\n+----+-------+\n| 1 | IT |\n| 2 | Sales |\n+----+-------+\nOutput: \n+------------+----------+--------+\n| Department | Employee | Salary |\n+------------+----------+--------+\n| IT | Max | 90000 |\n| IT | Joe | 85000 |\n| IT | Randy | 85000 |\n| IT | Will | 70000 |\n| Sales | Henry | 80000 |\n| Sales | Sam | 60000 |\n+------------+----------+--------+\nExplanation: \nIn the IT department:\n- Max earns the highest unique salary\n- Both Randy and Joe earn the second-highest unique salary\n- Will earns the third-highest unique salary\n\nIn the Sales department:\n- Henry earns the highest salary\n- Sam earns the second-highest salary\n- There is no third-highest salary as there are only two employees\n\n\n
\n
Constraints:
\n\nThe DNA sequence is composed of a series of nucleotides abbreviated as 'A'
, 'C'
, 'G'
, and 'T'
.
"ACGAATTCCG"
is a DNA sequence.When studying DNA, it is useful to identify repeated sequences within the DNA.
\n\nGiven a string s
that represents a DNA sequence, return all the 10
-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.
\n
Example 1:
\nInput: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput: [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\n
Example 2:
\nInput: s = \"AAAAAAAAAAAAA\"\nOutput: [\"AAAAAAAAAA\"]\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either 'A'
, 'C'
, 'G'
, or 'T'
.You are given an integer array prices
where prices[i]
is the price of a given stock on the ith
day, and an integer k
.
Find the maximum profit you can achieve. You may complete at most k
transactions: i.e. you may buy at most k
times and sell at most k
times.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
\n\n\n
Example 1:
\n\n\nInput: k = 2, prices = [2,4,1]\nOutput: 2\nExplanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n\n\n
Example 2:
\n\n\nInput: k = 2, prices = [3,2,6,5,0,3]\nOutput: 7\nExplanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n\n\n
\n
Constraints:
\n\n1 <= k <= 100
1 <= prices.length <= 1000
0 <= prices[i] <= 1000
Given an integer array nums
, rotate the array to the right by k
steps, where k
is non-negative.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]\n\n\n
Example 2:
\n\n\nInput: nums = [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\nExplanation: \nrotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
\n
Follow up:
\n\nO(1)
extra space?Reverse bits of a given 32 bits unsigned integer.
\n\nNote:
\n\n-3
and the output represents the signed integer -1073741825
.\n
Example 1:
\n\n\nInput: n = 00000010100101000001111010011100\nOutput: 964176192 (00111001011110000010100101000000)\nExplanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.\n\n\n
Example 2:
\n\n\nInput: n = 11111111111111111111111111111101\nOutput: 3221225471 (10111111111111111111111111111111)\nExplanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.\n\n\n
\n
Constraints:
\n\n32
\n
Follow up: If this function is called many times, how would you optimize it?
\n", - "likes": 5282, - "dislikes": 1540, - "stats": "{\"totalAccepted\": \"938K\", \"totalSubmission\": \"1.5M\", \"totalAcceptedRaw\": 938014, \"totalSubmissionRaw\": 1516507, \"acRate\": \"61.9%\"}", + "likes": 5365, + "dislikes": 1603, + "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1007562, \"totalSubmissionRaw\": 1595221, \"acRate\": \"63.2%\"}", "similarQuestions": "[{\"title\": \"Reverse Integer\", \"titleSlug\": \"reverse-integer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"A Number After a Double Reversal\", \"titleSlug\": \"a-number-after-a-double-reversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -7014,9 +7014,9 @@ "questionFrontendId": "191", "title": "Number of 1 Bits", "content": "Given a positive integer n
, write a function that returns the number of set bits in its binary representation (also known as the Hamming weight).
\n
Example 1:
\n\nInput: n = 11
\n\nOutput: 3
\n\nExplanation:
\n\nThe input binary string 1011 has a total of three set bits.
\nExample 2:
\n\nInput: n = 128
\n\nOutput: 1
\n\nExplanation:
\n\nThe input binary string 10000000 has a total of one set bit.
\nExample 3:
\n\nInput: n = 2147483645
\n\nOutput: 30
\n\nExplanation:
\n\nThe input binary string 1111111111111111111111111111101 has a total of thirty set bits.
\n\n
Constraints:
\n\n1 <= n <= 231 - 1
\nFollow up: If this function is called many times, how would you optimize it?", - "likes": 6727, - "dislikes": 1346, - "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1700081, \"totalSubmissionRaw\": 2311537, \"acRate\": \"73.5%\"}", + "likes": 6838, + "dislikes": 1348, + "stats": "{\"totalAccepted\": \"1.8M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1807767, \"totalSubmissionRaw\": 2427510, \"acRate\": \"74.5%\"}", "similarQuestions": "[{\"title\": \"Reverse Bits\", \"titleSlug\": \"reverse-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Counting Bits\", \"titleSlug\": \"counting-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Watch\", \"titleSlug\": \"binary-watch\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Hamming Distance\", \"titleSlug\": \"hamming-distance\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Number with Alternating Bits\", \"titleSlug\": \"binary-number-with-alternating-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Prime Number of Set Bits in Binary Representation\", \"titleSlug\": \"prime-number-of-set-bits-in-binary-representation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Convert Date to Binary\", \"titleSlug\": \"convert-date-to-binary\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -7048,9 +7048,9 @@ "questionFrontendId": "192", "title": "Word Frequency", "content": "
Write a bash script to calculate the frequency of each word in a text file words.txt
.
For simplicity sake, you may assume:
\n\nwords.txt
contains only lowercase characters and space ' '
characters.Example:
\n\nAssume that words.txt
has the following content:
\nthe day is sunny the the\nthe sunny is is\n\n\n
Your script should output the following, sorted by descending frequency:
\n\n\nthe 4\nis 3\nsunny 2\nday 1\n\n\n
Note:
\n\nGiven a text file file.txt
that contains a list of phone numbers (one per line), write a one-liner bash script to print all valid phone numbers.
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
\n\nYou may also assume each line in the text file must not contain leading or trailing white spaces.
\n\nExample:
\n\nAssume that file.txt
has the following content:
\n987-123-4567\n123 456 7890\n(123) 456-7890\n\n\n
Your script should output the following valid phone numbers:
\n\n\n987-123-4567\n(123) 456-7890\n\n", - "likes": 446, - "dislikes": 971, - "stats": "{\"totalAccepted\": \"96.6K\", \"totalSubmission\": \"359.5K\", \"totalAcceptedRaw\": 96570, \"totalSubmissionRaw\": 359501, \"acRate\": \"26.9%\"}", + "likes": 454, + "dislikes": 974, + "stats": "{\"totalAccepted\": \"104.6K\", \"totalSubmission\": \"381.1K\", \"totalAcceptedRaw\": 104626, \"totalSubmissionRaw\": 381063, \"acRate\": \"27.5%\"}", "similarQuestions": "[]", "categoryTitle": "Shell", "hints": [], @@ -7104,9 +7104,9 @@ "questionFrontendId": "194", "title": "Transpose File", "content": "
Given a text file file.txt
, transpose its content.
You may assume that each row has the same number of columns, and each field is separated by the ' '
character.
Example:
\n\nIf file.txt
has the following content:
\nname age\nalice 21\nryan 30\n\n\n
Output the following:
\n\n\nname alice ryan\nage 21 30\n\n", - "likes": 152, - "dislikes": 287, - "stats": "{\"totalAccepted\": \"30.2K\", \"totalSubmission\": \"109.4K\", \"totalAcceptedRaw\": 30203, \"totalSubmissionRaw\": 109368, \"acRate\": \"27.6%\"}", + "likes": 155, + "dislikes": 288, + "stats": "{\"totalAccepted\": \"33K\", \"totalSubmission\": \"116K\", \"totalAcceptedRaw\": 32994, \"totalSubmissionRaw\": 115993, \"acRate\": \"28.4%\"}", "similarQuestions": "[]", "categoryTitle": "Shell", "hints": [], @@ -7132,9 +7132,9 @@ "questionFrontendId": "195", "title": "Tenth Line", "content": "
Given a text file file.txt
, print just the 10th line of the file.
Example:
\r\n\r\nAssume that file.txt
has the following content:
\r\nLine 1\r\nLine 2\r\nLine 3\r\nLine 4\r\nLine 5\r\nLine 6\r\nLine 7\r\nLine 8\r\nLine 9\r\nLine 10\r\n\r\n\r\n
Your script should output the tenth line, which is:
\r\n\r\n\r\nLine 10\r\n\r\n\r\n
Table: Person
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| email | varchar |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains an email. The emails will not contain uppercase letters.\n\n\n
\n\n
Write a solution to delete all duplicate emails, keeping only one unique email with the smallest id
.
For SQL users, please note that you are supposed to write a DELETE
statement and not a SELECT
one.
For Pandas users, please note that you are supposed to modify Person
in place.
After running your script, the answer shown is the Person
table. The driver will first compile and run your piece of code and then show the Person
table. The final order of the Person
table does not matter.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nPerson table:\n+----+------------------+\n| id | email |\n+----+------------------+\n| 1 | john@example.com |\n| 2 | bob@example.com |\n| 3 | john@example.com |\n+----+------------------+\nOutput: \n+----+------------------+\n| id | email |\n+----+------------------+\n| 1 | john@example.com |\n| 2 | bob@example.com |\n+----+------------------+\nExplanation: john@example.com is repeated two times. We keep the row with the smallest Id = 1.\n\n", - "likes": 1743, - "dislikes": 361, - "stats": "{\"totalAccepted\": \"659K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 658997, \"totalSubmissionRaw\": 1034825, \"acRate\": \"63.7%\"}", + "likes": 1839, + "dislikes": 377, + "stats": "{\"totalAccepted\": \"732.4K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 732395, \"totalSubmissionRaw\": 1138903, \"acRate\": \"64.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -7191,9 +7191,9 @@ "questionFrontendId": "197", "title": "Rising Temperature", "content": "
Table: Weather
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| recordDate | date |\n| temperature | int |\n+---------------+---------+\nid is the column with unique values for this table.\nThere are no different rows with the same recordDate.\nThis table contains information about the temperature on a certain day.\n\n\n
\n\n
Write a solution to find all dates' id
with higher temperatures compared to its previous dates (yesterday).
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nWeather table:\n+----+------------+-------------+\n| id | recordDate | temperature |\n+----+------------+-------------+\n| 1 | 2015-01-01 | 10 |\n| 2 | 2015-01-02 | 25 |\n| 3 | 2015-01-03 | 20 |\n| 4 | 2015-01-04 | 30 |\n+----+------------+-------------+\nOutput: \n+----+\n| id |\n+----+\n| 2 |\n| 4 |\n+----+\nExplanation: \nIn 2015-01-02, the temperature was higher than the previous day (10 -> 25).\nIn 2015-01-04, the temperature was higher than the previous day (20 -> 30).\n\n", - "likes": 3408, - "dislikes": 663, - "stats": "{\"totalAccepted\": \"965.7K\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 965747, \"totalSubmissionRaw\": 1943539, \"acRate\": \"49.7%\"}", + "likes": 3655, + "dislikes": 686, + "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1118207, \"totalSubmissionRaw\": 2228992, \"acRate\": \"50.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -7222,9 +7222,9 @@ "questionFrontendId": "198", "title": "House Robber", "content": "
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
\n\nGiven an integer array nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\n
Example 2:
\n\n\nInput: nums = [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 400
Given the root
of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
\n
Example 1:
\n\nInput: root = [1,2,3,null,5,null,4]
\n\nOutput: [1,3,4]
\n\nExplanation:
\n\nExample 2:
\n\nInput: root = [1,2,3,4,null,null,null,5]
\n\nOutput: [1,3,4,5]
\n\nExplanation:
\n\nExample 3:
\n\nInput: root = [1,null,3]
\n\nOutput: [1,3]
\nExample 4:
\n\nInput: root = []
\n\nOutput: []
\n\n
Constraints:
\n\n[0, 100]
.-100 <= Node.val <= 100
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.
\n\n\n
Example 1:
\n\n\nInput: grid = [\n ["1","1","1","1","0"],\n ["1","1","0","1","0"],\n ["1","1","0","0","0"],\n ["0","0","0","0","0"]\n]\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: grid = [\n ["1","1","0","0","0"],\n ["1","1","0","0","0"],\n ["0","0","1","0","0"],\n ["0","0","0","1","1"]\n]\nOutput: 3\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j]
is '0'
or '1'
.Given two integers left
and right
that represent the range [left, right]
, return the bitwise AND of all numbers in this range, inclusive.
\n
Example 1:
\n\n\nInput: left = 5, right = 7\nOutput: 4\n\n\n
Example 2:
\n\n\nInput: left = 0, right = 0\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: left = 1, right = 2147483647\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= left <= right <= 231 - 1
Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
\n\nReturn true
if n
is a happy number, and false
if not.
\n
Example 1:
\n\n\nInput: n = 19\nOutput: true\nExplanation:\n12 + 92 = 82\n82 + 22 = 68\n62 + 82 = 100\n12 + 02 + 02 = 1\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
\n
Example 1:
\n\nInput: head = [1,2,6,3,4,5,6], val = 6\nOutput: [1,2,3,4,5]\n\n\n
Example 2:
\n\n\nInput: head = [], val = 1\nOutput: []\n\n\n
Example 3:
\n\n\nInput: head = [7,7,7,7], val = 7\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 104]
.1 <= Node.val <= 50
0 <= val <= 50
Given an integer n
, return the number of prime numbers that are strictly less than n
.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: n = 1\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= n <= 5 * 106
Given two strings s
and t
, determine if they are isomorphic.
Two strings s
and t
are isomorphic if the characters in s
can be replaced to get t
.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
\n\n\n
Example 1:
\n\nInput: s = "egg", t = "add"
\n\nOutput: true
\n\nExplanation:
\n\nThe strings s
and t
can be made identical by:
'e'
to 'a'
.'g'
to 'd'
.Example 2:
\n\nInput: s = "foo", t = "bar"
\n\nOutput: false
\n\nExplanation:
\n\nThe strings s
and t
can not be made identical as 'o'
needs to be mapped to both 'a'
and 'r'
.
Example 3:
\n\nInput: s = "paper", t = "title"
\n\nOutput: true
\n\n
Constraints:
\n\n1 <= s.length <= 5 * 104
t.length == s.length
s
and t
consist of any valid ascii character.Given the head
of a singly linked list, reverse the list, and return the reversed list.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5]\nOutput: [5,4,3,2,1]\n\n\n
Example 2:
\n\nInput: head = [1,2]\nOutput: [2,1]\n\n\n
Example 3:
\n\n\nInput: head = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 5000]
.-5000 <= Node.val <= 5000
\n
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
\n", - "likes": 22446, - "dislikes": 497, - "stats": "{\"totalAccepted\": \"4.9M\", \"totalSubmission\": \"6.3M\", \"totalAcceptedRaw\": 4929320, \"totalSubmissionRaw\": 6280557, \"acRate\": \"78.5%\"}", + "likes": 23007, + "dislikes": 530, + "stats": "{\"totalAccepted\": \"5.3M\", \"totalSubmission\": \"6.7M\", \"totalAcceptedRaw\": 5301789, \"totalSubmissionRaw\": 6695662, \"acRate\": \"79.2%\"}", "similarQuestions": "[{\"title\": \"Reverse Linked List II\", \"titleSlug\": \"reverse-linked-list-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Binary Tree Upside Down\", \"titleSlug\": \"binary-tree-upside-down\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Linked List\", \"titleSlug\": \"palindrome-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse Nodes in Even Length Groups\", \"titleSlug\": \"reverse-nodes-in-even-length-groups\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Twin Sum of a Linked List\", \"titleSlug\": \"maximum-twin-sum-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Remove Nodes From Linked List\", \"titleSlug\": \"remove-nodes-from-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Insert Greatest Common Divisors in Linked List\", \"titleSlug\": \"insert-greatest-common-divisors-in-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -7553,9 +7553,9 @@ "questionFrontendId": "207", "title": "Course Schedule", "content": "There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
first if you want to take course ai
.
[0, 1]
, indicates that to take course 0
you have to first take course 1
.Return true
if you can finish all courses. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: true\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.\n\n\n
Example 2:
\n\n\nInput: numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput: false\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.\n\n\n
\n
Constraints:
\n\n1 <= numCourses <= 2000
0 <= prerequisites.length <= 5000
prerequisites[i].length == 2
0 <= ai, bi < numCourses
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
\n\nImplement the Trie class:
\n\nTrie()
Initializes the trie object.void insert(String word)
Inserts the string word
into the trie.boolean search(String word)
Returns true
if the string word
is in the trie (i.e., was inserted before), and false
otherwise.boolean startsWith(String prefix)
Returns true
if there is a previously inserted string word
that has the prefix prefix
, and false
otherwise.\n
Example 1:
\n\n\nInput\n["Trie", "insert", "search", "search", "startsWith", "insert", "search"]\n[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]\nOutput\n[null, null, true, false, true, null, true]\n\nExplanation\nTrie trie = new Trie();\ntrie.insert("apple");\ntrie.search("apple"); // return True\ntrie.search("app"); // return False\ntrie.startsWith("app"); // return True\ntrie.insert("app");\ntrie.search("app"); // return True\n\n\n
\n
Constraints:
\n\n1 <= word.length, prefix.length <= 2000
word
and prefix
consist only of lowercase English letters.3 * 104
calls in total will be made to insert
, search
, and startsWith
.Given an array of positive integers nums
and a positive integer target
, return the minimal length of a subarray whose sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
\n
Example 1:
\n\n\nInput: target = 7, nums = [2,3,1,2,4,3]\nOutput: 2\nExplanation: The subarray [4,3] has the minimal length under the problem constraint.\n\n\n
Example 2:
\n\n\nInput: target = 4, nums = [1,4,4]\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= target <= 109
1 <= nums.length <= 105
1 <= nums[i] <= 104
\nFollow up: If you have figured out the
O(n)
solution, try coding another solution of which the time complexity is O(n log(n))
.",
- "likes": 13156,
- "dislikes": 476,
- "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1326168, \"totalSubmissionRaw\": 2730296, \"acRate\": \"48.6%\"}",
+ "likes": 13469,
+ "dislikes": 495,
+ "stats": "{\"totalAccepted\": \"1.5M\", \"totalSubmission\": \"3M\", \"totalAcceptedRaw\": 1471374, \"totalSubmissionRaw\": 2980991, \"acRate\": \"49.4%\"}",
"similarQuestions": "[{\"title\": \"Minimum Window Substring\", \"titleSlug\": \"minimum-window-substring\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Maximum Size Subarray Sum Equals k\", \"titleSlug\": \"maximum-size-subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Length of Repeated Subarray\", \"titleSlug\": \"maximum-length-of-repeated-subarray\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Reduce X to Zero\", \"titleSlug\": \"minimum-operations-to-reduce-x-to-zero\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"K Radius Subarray Averages\", \"titleSlug\": \"k-radius-subarray-averages\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Product After K Increments\", \"titleSlug\": \"maximum-product-after-k-increments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Subarray With OR at Least K I\", \"titleSlug\": \"shortest-subarray-with-or-at-least-k-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Positive Sum Subarray \", \"titleSlug\": \"minimum-positive-sum-subarray\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -7677,9 +7677,9 @@
"questionFrontendId": "210",
"title": "Course Schedule II",
"content": "There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course bi
first if you want to take course ai
.
[0, 1]
, indicates that to take course 0
you have to first take course 1
.Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
\n\n\n
Example 1:
\n\n\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: [0,1]\nExplanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].\n\n\n
Example 2:
\n\n\nInput: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput: [0,2,1,3]\nExplanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].\n\n\n
Example 3:
\n\n\nInput: numCourses = 1, prerequisites = []\nOutput: [0]\n\n\n
\n
Constraints:
\n\n1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
[ai, bi]
are distinct.Design a data structure that supports adding new words and finding if a string matches any previously added string.
\n\nImplement the WordDictionary
class:
WordDictionary()
Initializes the object.void addWord(word)
Adds word
to the data structure, it can be matched later.bool search(word)
Returns true
if there is any string in the data structure that matches word
or false
otherwise. word
may contain dots '.'
where dots can be matched with any letter.\n
Example:
\n\n\nInput\n["WordDictionary","addWord","addWord","addWord","search","search","search","search"]\n[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]\nOutput\n[null,null,null,null,false,true,true,true]\n\nExplanation\nWordDictionary wordDictionary = new WordDictionary();\nwordDictionary.addWord("bad");\nwordDictionary.addWord("dad");\nwordDictionary.addWord("mad");\nwordDictionary.search("pad"); // return False\nwordDictionary.search("bad"); // return True\nwordDictionary.search(".ad"); // return True\nwordDictionary.search("b.."); // return True\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 25
word
in addWord
consists of lowercase English letters.word
in search
consist of '.'
or lowercase English letters.2
dots in word
for search
queries.104
calls will be made to addWord
and search
.Given an m x n
board
of characters and a list of strings words
, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
\n\n\n
Example 1:
\n\nInput: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]\nOutput: ["eat","oath"]\n\n\n
Example 2:
\n\nInput: board = [["a","b"],["c","d"]], words = ["abcb"]\nOutput: []\n\n\n
\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
is a lowercase English letter.1 <= words.length <= 3 * 104
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.words
are unique.You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.
\n\nGiven an integer array nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
\n
Example 1:
\n\n\nInput: nums = [2,3,2]\nOutput: 3\nExplanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 1000
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.
\n\n\n
Example 1:
\nInput: s = \"aacecaaa\"\nOutput: \"aaacecaaa\"\n
Example 2:
\nInput: s = \"abcd\"\nOutput: \"dcbabcd\"\n\n
\n
Constraints:
\n\n0 <= s.length <= 5 * 104
s
consists of lowercase English letters only.Given an integer array nums
and an integer k
, return the kth
largest element in the array.
Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
Can you solve it without sorting?
\n\n\n
Example 1:
\nInput: nums = [3,2,1,5,6,4], k = 2\nOutput: 5\n
Example 2:
\nInput: nums = [3,2,3,1,2,4,5,5,6], k = 4\nOutput: 4\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104
Find all valid combinations of k
numbers that sum up to n
such that the following conditions are true:
1
through 9
are used.Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
\n\n\n
Example 1:
\n\n\nInput: k = 3, n = 7\nOutput: [[1,2,4]]\nExplanation:\n1 + 2 + 4 = 7\nThere are no other valid combinations.\n\n
Example 2:
\n\n\nInput: k = 3, n = 9\nOutput: [[1,2,6],[1,3,5],[2,3,4]]\nExplanation:\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\n\n\n
Example 3:
\n\n\nInput: k = 4, n = 1\nOutput: []\nExplanation: There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.\n\n\n
\n
Constraints:
\n\n2 <= k <= 9
1 <= n <= 60
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
\n
Example 1:
\n\nInput: nums = [1,2,3,1]
\n\nOutput: true
\n\nExplanation:
\n\nThe element 1 occurs at the indices 0 and 3.
\nExample 2:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: false
\n\nExplanation:
\n\nAll elements are distinct.
\nExample 3:
\n\nInput: nums = [1,1,1,3,3,4,3,2,4,2]
\n\nOutput: true
\n\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.
\n\nThe geometric information of each building is given in the array buildings
where buildings[i] = [lefti, righti, heighti]
:
lefti
is the x coordinate of the left edge of the ith
building.righti
is the x coordinate of the right edge of the ith
building.heighti
is the height of the ith
building.You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0
.
The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]
. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0
and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.
Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...]
is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]
\n
Example 1:
\n\nInput: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:\nFigure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n\n\n
Example 2:
\n\n\nInput: buildings = [[0,2,3],[2,5,3]]\nOutput: [[0,3],[5,0]]\n\n\n
\n
Constraints:
\n\n1 <= buildings.length <= 104
0 <= lefti < righti <= 231 - 1
1 <= heighti <= 231 - 1
buildings
is sorted by lefti
in non-decreasing order.Given an integer array nums
and an integer k
, return true
if there are two distinct indices i
and j
in the array such that nums[i] == nums[j]
and abs(i - j) <= k
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1], k = 3\nOutput: true\n\n\n
Example 2:
\n\n\nInput: nums = [1,0,1,1], k = 1\nOutput: true\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,1,2,3], k = 2\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
You are given an integer array nums
and two integers indexDiff
and valueDiff
.
Find a pair of indices (i, j)
such that:
i != j
,abs(i - j) <= indexDiff
.abs(nums[i] - nums[j]) <= valueDiff
, andReturn true
if such pair exists or false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0\nOutput: true\nExplanation: We can choose (i, j) = (0, 3).\nWe satisfy the three conditions:\ni != j --> 0 != 3\nabs(i - j) <= indexDiff --> abs(0 - 3) <= 3\nabs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0\n\n\n
Example 2:
\n\n\nInput: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3\nOutput: false\nExplanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
-109 <= nums[i] <= 109
1 <= indexDiff <= nums.length
0 <= valueDiff <= 109
Given an m x n
binary matrix
filled with 0
's and 1
's, find the largest square containing only 1
's and return its area.
\n
Example 1:
\n\nInput: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]\nOutput: 4\n\n\n
Example 2:
\n\nInput: matrix = [["0","1"],["1","0"]]\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: matrix = [["0"]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
is '0'
or '1'
.Given the root
of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1
and 2h
nodes inclusive at the last level h
.
Design an algorithm that runs in less than O(n)
time complexity.
\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6]\nOutput: 6\n\n\n
Example 2:
\n\n\nInput: root = []\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: root = [1]\nOutput: 1\n\n\n
\n
Constraints:
\n\n[0, 5 * 104]
.0 <= Node.val <= 5 * 104
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
\n\nThe first rectangle is defined by its bottom-left corner (ax1, ay1)
and its top-right corner (ax2, ay2)
.
The second rectangle is defined by its bottom-left corner (bx1, by1)
and its top-right corner (bx2, by2)
.
\n
Example 1:
\n\nInput: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput: 45\n\n\n
Example 2:
\n\n\nInput: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput: 16\n\n\n
\n
Constraints:
\n\n-104 <= ax1 <= ax2 <= 104
-104 <= ay1 <= ay2 <= 104
-104 <= bx1 <= bx2 <= 104
-104 <= by1 <= by2 <= 104
Given a string s
representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
\n
Example 1:
\n\n\nInput: s = "1 + 1"\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: s = " 2-1 + 2 "\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: s = "(1+(4+5+2)-3)+(6+8)"\nOutput: 23\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 3 * 105
s
consists of digits, '+'
, '-'
, '('
, ')'
, and ' '
.s
represents a valid expression.'+'
is not used as a unary operation (i.e., "+1"
and "+(2 + 3)"
is invalid).'-'
could be used as a unary operation (i.e., "-1"
and "-(2 + 3)"
is valid).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:
\n\npush to back
, peek/pop from front
, size
and is empty
operations are valid.\n
Example 1:
\n\n\nInput\n["MyStack", "push", "push", "top", "pop", "empty"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 2, 2, false]\n\nExplanation\nMyStack myStack = new MyStack();\nmyStack.push(1);\nmyStack.push(2);\nmyStack.top(); // return 2\nmyStack.pop(); // return 2\nmyStack.empty(); // return False\n\n\n
\n
Constraints:
\n\n1 <= x <= 9
100
calls will be made to push
, pop
, top
, and empty
.pop
and top
are valid.\n
Follow-up: Can you implement the stack using only one queue?
\n", - "likes": 6329, - "dislikes": 1234, - "stats": "{\"totalAccepted\": \"828.9K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 828935, \"totalSubmissionRaw\": 1250637, \"acRate\": \"66.3%\"}", + "likes": 6488, + "dislikes": 1256, + "stats": "{\"totalAccepted\": \"912.3K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 912316, \"totalSubmissionRaw\": 1355649, \"acRate\": \"67.3%\"}", "similarQuestions": "[{\"title\": \"Implement Queue using Stacks\", \"titleSlug\": \"implement-queue-using-stacks\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -8319,9 +8319,9 @@ "questionFrontendId": "226", "title": "Invert Binary Tree", "content": "Given the root
of a binary tree, invert the tree, and return its root.
\n
Example 1:
\n\nInput: root = [4,2,7,1,3,6,9]\nOutput: [4,7,2,9,6,3,1]\n\n\n
Example 2:
\n\nInput: root = [2,1,3]\nOutput: [2,3,1]\n\n\n
Example 3:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 100]
.-100 <= Node.val <= 100
Given a string s
which represents an expression, evaluate this expression and return its value.
The integer division should truncate toward zero.
\n\nYou may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
\n
Example 1:
\nInput: s = \"3+2*2\"\nOutput: 7\n
Example 2:
\nInput: s = \" 3/2 \"\nOutput: 1\n
Example 3:
\nInput: s = \" 3+5 / 2 \"\nOutput: 5\n\n
\n
Constraints:
\n\n1 <= s.length <= 3 * 105
s
consists of integers and operators ('+', '-', '*', '/')
separated by some number of spaces.s
represents a valid expression.[0, 231 - 1]
.You are given a sorted unique integer array nums
.
A range [a,b]
is the set of all integers from a
to b
(inclusive).
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums
is covered by exactly one of the ranges, and there is no integer x
such that x
is in one of the ranges but not in nums
.
Each range [a,b]
in the list should be output as:
"a->b"
if a != b
"a"
if a == b
\n
Example 1:
\n\n\nInput: nums = [0,1,2,4,5,7]\nOutput: ["0->2","4->5","7"]\nExplanation: The ranges are:\n[0,2] --> "0->2"\n[4,5] --> "4->5"\n[7,7] --> "7"\n\n\n
Example 2:
\n\n\nInput: nums = [0,2,3,4,6,8,9]\nOutput: ["0","2->4","6","8->9"]\nExplanation: The ranges are:\n[0,0] --> "0"\n[2,4] --> "2->4"\n[6,6] --> "6"\n[8,9] --> "8->9"\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
nums
are unique.nums
is sorted in ascending order.Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
\n
Example 1:
\n\n\nInput: nums = [3,2,3]\nOutput: [3]\n\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: [1]\n\n\n
Example 3:
\n\n\nInput: nums = [1,2]\nOutput: [1,2]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
-109 <= nums[i] <= 109
\n
Follow up: Could you solve the problem in linear time and in O(1)
space?
Given the root
of a binary search tree, and an integer k
, return the kth
smallest value (1-indexed) of all the values of the nodes in the tree.
\n
Example 1:
\n\nInput: root = [3,1,4,null,2], k = 1\nOutput: 1\n\n\n
Example 2:
\n\nInput: root = [5,3,6,2,4,null,null,1], k = 3\nOutput: 3\n\n\n
\n
Constraints:
\n\nn
.1 <= k <= n <= 104
0 <= Node.val <= 104
\n
Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
\n", - "likes": 11876, - "dislikes": 239, - "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1733859, \"totalSubmissionRaw\": 2326061, \"acRate\": \"74.5%\"}", + "likes": 12101, + "dislikes": 243, + "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"2.5M\", \"totalAcceptedRaw\": 1881121, \"totalSubmissionRaw\": 2498336, \"acRate\": \"75.3%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Second Minimum Node In a Binary Tree\", \"titleSlug\": \"second-minimum-node-in-a-binary-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -8516,9 +8516,9 @@ "questionFrontendId": "231", "title": "Power of Two", "content": "Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: true\nExplanation: 20 = 1\n\n\n
Example 2:
\n\n\nInput: n = 16\nOutput: true\nExplanation: 24 = 16\n\n\n
Example 3:
\n\n\nInput: n = 3\nOutput: false\n\n\n
\n
Constraints:
\n\n-231 <= n <= 231 - 1
\nFollow up: Could you solve it without loops/recursion?", - "likes": 7100, - "dislikes": 460, - "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"3.3M\", \"totalAcceptedRaw\": 1576146, \"totalSubmissionRaw\": 3272672, \"acRate\": \"48.2%\"}", + "likes": 7274, + "dislikes": 468, + "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"3.5M\", \"totalAcceptedRaw\": 1696576, \"totalSubmissionRaw\": 3507245, \"acRate\": \"48.4%\"}", "similarQuestions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Three\", \"titleSlug\": \"power-of-three\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Four\", \"titleSlug\": \"power-of-four\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -8553,9 +8553,9 @@ "questionFrontendId": "232", "title": "Implement Queue using Stacks", "content": "
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push
, peek
, pop
, and empty
).
Implement the MyQueue
class:
void push(int x)
Pushes element x to the back of the queue.int pop()
Removes the element from the front of the queue and returns it.int peek()
Returns the element at the front of the queue.boolean empty()
Returns true
if the queue is empty, false
otherwise.Notes:
\n\npush to top
, peek/pop from top
, size
, and is empty
operations are valid.\n
Example 1:
\n\n\nInput\n["MyQueue", "push", "push", "peek", "pop", "empty"]\n[[], [1], [2], [], [], []]\nOutput\n[null, null, null, 1, 1, false]\n\nExplanation\nMyQueue myQueue = new MyQueue();\nmyQueue.push(1); // queue is: [1]\nmyQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\nmyQueue.peek(); // return 1\nmyQueue.pop(); // return 1, queue is [2]\nmyQueue.empty(); // return false\n\n\n
\n
Constraints:
\n\n1 <= x <= 9
100
calls will be made to push
, pop
, peek
, and empty
.pop
and peek
are valid.\n
Follow-up: Can you implement the queue such that each operation is amortized O(1)
time complexity? In other words, performing n
operations will take overall O(n)
time even if one of those operations may take longer.
Given an integer n
, count the total number of digit 1
appearing in all non-negative integers less than or equal to n
.
\n
Example 1:
\n\n\nInput: n = 13\nOutput: 6\n\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
Given the head
of a singly linked list, return true
if it is a palindrome or false
otherwise.
\n
Example 1:
\n\nInput: head = [1,2,2,1]\nOutput: true\n\n\n
Example 2:
\n\nInput: head = [1,2]\nOutput: false\n\n\n
\n
Constraints:
\n\n[1, 105]
.0 <= Node.val <= 9
\nFollow up: Could you do it in
O(n)
time and O(1)
space?",
- "likes": 17063,
- "dislikes": 917,
- "stats": "{\"totalAccepted\": \"2.3M\", \"totalSubmission\": \"4.1M\", \"totalAcceptedRaw\": 2256588, \"totalSubmissionRaw\": 4105604, \"acRate\": \"55.0%\"}",
+ "likes": 17414,
+ "dislikes": 934,
+ "stats": "{\"totalAccepted\": \"2.4M\", \"totalSubmission\": \"4.4M\", \"totalAcceptedRaw\": 2431234, \"totalSubmissionRaw\": 4355227, \"acRate\": \"55.8%\"}",
"similarQuestions": "[{\"title\": \"Palindrome Number\", \"titleSlug\": \"palindrome-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome\", \"titleSlug\": \"valid-palindrome\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Reverse Linked List\", \"titleSlug\": \"reverse-linked-list\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Twin Sum of a Linked List\", \"titleSlug\": \"maximum-twin-sum-of-a-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -8669,9 +8669,9 @@
"questionFrontendId": "235",
"title": "Lowest Common Ancestor of a Binary Search Tree",
"content": "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
\n
Example 1:
\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput: 6\nExplanation: The LCA of nodes 2 and 8 is 6.\n\n\n
Example 2:
\n\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput: 2\nExplanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n\n\n
Example 3:
\n\n\nInput: root = [2,1], p = 2, q = 1\nOutput: 2\n\n\n
\n
Constraints:
\n\n[2, 105]
.-109 <= Node.val <= 109
Node.val
are unique.p != q
p
and q
will exist in the BST.Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
\n\nAccording to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p
and q
as the lowest node in T
that has both p
and q
as descendants (where we allow a node to be a descendant of itself).”
\n
Example 1:
\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of nodes 5 and 1 is 3.\n\n\n
Example 2:
\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n\n\n
Example 3:
\n\n\nInput: root = [1,2], p = 1, q = 2\nOutput: 1\n\n\n
\n
Constraints:
\n\n[2, 105]
.-109 <= Node.val <= 109
Node.val
are unique.p != q
p
and q
will exist in the tree.There is a singly-linked list head
and we want to delete a node node
in it.
You are given the node to be deleted node
. You will not be given access to the first node of head
.
All the values of the linked list are unique, and it is guaranteed that the given node node
is not the last node in the linked list.
Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
\n\nnode
should be in the same order.node
should be in the same order.Custom testing:
\n\nhead
and the node to be given node
. node
should not be the last node of the list and should be an actual node in the list.\n
Example 1:
\n\nInput: head = [4,5,1,9], node = 5\nOutput: [4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.\n\n\n
Example 2:
\n\nInput: head = [4,5,1,9], node = 1\nOutput: [4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.\n\n\n
\n
Constraints:
\n\n[2, 1000]
.-1000 <= Node.val <= 1000
node
to be deleted is in the list and is not a tail node.Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n)
time and without using the division operation.
\n
Example 1:
\nInput: nums = [1,2,3,4]\nOutput: [24,12,8,6]\n
Example 2:
\nInput: nums = [-1,1,0,-3,3]\nOutput: [0,0,9,0,0]\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
-30 <= nums[i] <= 30
answer[i]
is guaranteed to fit in a 32-bit integer.\n
Follow up: Can you solve the problem in O(1)
extra space complexity? (The output array does not count as extra space for space complexity analysis.)
You are given an array of integers nums
, there is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation: \nWindow position Max\n--------------- -----\n[1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\n\n\n
Example 2:
\n\n\nInput: nums = [1], k = 1\nOutput: [1]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
Write an efficient algorithm that searches for a value target
in an m x n
integer matrix matrix
. This matrix has the following properties:
\n
Example 1:
\n\nInput: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\nOutput: true\n\n\n
Example 2:
\n\nInput: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\nOutput: false\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
-109 <= target <= 109
Given a string expression
of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104
.
\n
Example 1:
\n\n\nInput: expression = "2-1-1"\nOutput: [0,2]\nExplanation:\n((2-1)-1) = 0 \n(2-(1-1)) = 2\n\n\n
Example 2:
\n\n\nInput: expression = "2*3-4*5"\nOutput: [-34,-14,-10,-10,10]\nExplanation:\n(2*(3-(4*5))) = -34 \n((2*3)-(4*5)) = -14 \n((2*(3-4))*5) = -10 \n(2*((3-4)*5)) = -10 \n(((2*3)-4)*5) = 10\n\n\n
\n
Constraints:
\n\n1 <= expression.length <= 20
expression
consists of digits and the operator '+'
, '-'
, and '*'
.[0, 99]
.'-'
or '+'
denoting the sign.Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
\n
Example 1:
\n\nInput: s = "anagram", t = "nagaram"
\n\nOutput: true
\nExample 2:
\n\nInput: s = "rat", t = "car"
\n\nOutput: false
\n\n
Constraints:
\n\n1 <= s.length, t.length <= 5 * 104
s
and t
consist of lowercase English letters.\n
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
\n", - "likes": 12711, - "dislikes": 422, - "stats": "{\"totalAccepted\": \"4.4M\", \"totalSubmission\": \"6.6M\", \"totalAcceptedRaw\": 4386611, \"totalSubmissionRaw\": 6645401, \"acRate\": \"66.0%\"}", + "likes": 13083, + "dislikes": 433, + "stats": "{\"totalAccepted\": \"4.8M\", \"totalSubmission\": \"7.2M\", \"totalAcceptedRaw\": 4826398, \"totalSubmissionRaw\": 7242885, \"acRate\": \"66.6%\"}", "similarQuestions": "[{\"title\": \"Group Anagrams\", \"titleSlug\": \"group-anagrams\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Palindrome Permutation\", \"titleSlug\": \"palindrome-permutation\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find All Anagrams in a String\", \"titleSlug\": \"find-all-anagrams-in-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Resultant Array After Removing Anagrams\", \"titleSlug\": \"find-resultant-array-after-removing-anagrams\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -8981,9 +8981,9 @@ "questionFrontendId": "243", "title": "Shortest Word Distance", "content": null, - "likes": 1283, - "dislikes": 118, - "stats": "{\"totalAccepted\": \"226.4K\", \"totalSubmission\": \"344.5K\", \"totalAcceptedRaw\": 226407, \"totalSubmissionRaw\": 344546, \"acRate\": \"65.7%\"}", + "likes": 1285, + "dislikes": 122, + "stats": "{\"totalAccepted\": \"233.1K\", \"totalSubmission\": \"353.5K\", \"totalAcceptedRaw\": 233131, \"totalSubmissionRaw\": 353506, \"acRate\": \"65.9%\"}", "similarQuestions": "[{\"title\": \"Shortest Word Distance II\", \"titleSlug\": \"shortest-word-distance-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Word Distance III\", \"titleSlug\": \"shortest-word-distance-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find All K-Distant Indices in an Array\", \"titleSlug\": \"find-all-k-distant-indices-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9015,9 +9015,9 @@ "questionFrontendId": "244", "title": "Shortest Word Distance II", "content": null, - "likes": 1068, - "dislikes": 366, - "stats": "{\"totalAccepted\": \"162.1K\", \"totalSubmission\": \"262.6K\", \"totalAcceptedRaw\": 162104, \"totalSubmissionRaw\": 262552, \"acRate\": \"61.7%\"}", + "likes": 1073, + "dislikes": 380, + "stats": "{\"totalAccepted\": \"167.7K\", \"totalSubmission\": \"269.9K\", \"totalAcceptedRaw\": 167681, \"totalSubmissionRaw\": 269900, \"acRate\": \"62.1%\"}", "similarQuestions": "[{\"title\": \"Merge Two Sorted Lists\", \"titleSlug\": \"merge-two-sorted-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Shortest Word Distance\", \"titleSlug\": \"shortest-word-distance\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Shortest Word Distance III\", \"titleSlug\": \"shortest-word-distance-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9058,9 +9058,9 @@ "questionFrontendId": "245", "title": "Shortest Word Distance III", "content": null, - "likes": 507, + "likes": 511, "dislikes": 100, - "stats": "{\"totalAccepted\": \"86.1K\", \"totalSubmission\": \"146.4K\", \"totalAcceptedRaw\": 86124, \"totalSubmissionRaw\": 146386, \"acRate\": \"58.8%\"}", + "stats": "{\"totalAccepted\": \"88.8K\", \"totalSubmission\": \"150.3K\", \"totalAcceptedRaw\": 88836, \"totalSubmissionRaw\": 150338, \"acRate\": \"59.1%\"}", "similarQuestions": "[{\"title\": \"Shortest Word Distance\", \"titleSlug\": \"shortest-word-distance\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Shortest Word Distance II\", \"titleSlug\": \"shortest-word-distance-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9092,9 +9092,9 @@ "questionFrontendId": "246", "title": "Strobogrammatic Number", "content": null, - "likes": 609, - "dislikes": 1029, - "stats": "{\"totalAccepted\": \"187.7K\", \"totalSubmission\": \"394.2K\", \"totalAcceptedRaw\": 187707, \"totalSubmissionRaw\": 394188, \"acRate\": \"47.6%\"}", + "likes": 615, + "dislikes": 1038, + "stats": "{\"totalAccepted\": \"197K\", \"totalSubmission\": \"413.9K\", \"totalAcceptedRaw\": 197015, \"totalSubmissionRaw\": 413870, \"acRate\": \"47.6%\"}", "similarQuestions": "[{\"title\": \"Strobogrammatic Number II\", \"titleSlug\": \"strobogrammatic-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Strobogrammatic Number III\", \"titleSlug\": \"strobogrammatic-number-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Confusing Number\", \"titleSlug\": \"confusing-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9129,9 +9129,9 @@ "questionFrontendId": "247", "title": "Strobogrammatic Number II", "content": null, - "likes": 935, - "dislikes": 258, - "stats": "{\"totalAccepted\": \"149.2K\", \"totalSubmission\": \"282.5K\", \"totalAcceptedRaw\": 149236, \"totalSubmissionRaw\": 282473, \"acRate\": \"52.8%\"}", + "likes": 945, + "dislikes": 261, + "stats": "{\"totalAccepted\": \"155.4K\", \"totalSubmission\": \"292.1K\", \"totalAcceptedRaw\": 155354, \"totalSubmissionRaw\": 292074, \"acRate\": \"53.2%\"}", "similarQuestions": "[{\"title\": \"Strobogrammatic Number\", \"titleSlug\": \"strobogrammatic-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Strobogrammatic Number III\", \"titleSlug\": \"strobogrammatic-number-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sum of k-Mirror Numbers\", \"titleSlug\": \"sum-of-k-mirror-numbers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -9168,9 +9168,9 @@ "questionFrontendId": "248", "title": "Strobogrammatic Number III", "content": null, - "likes": 303, - "dislikes": 190, - "stats": "{\"totalAccepted\": \"37.3K\", \"totalSubmission\": \"88.2K\", \"totalAcceptedRaw\": 37315, \"totalSubmissionRaw\": 88163, \"acRate\": \"42.3%\"}", + "likes": 305, + "dislikes": 192, + "stats": "{\"totalAccepted\": \"37.8K\", \"totalSubmission\": \"89K\", \"totalAcceptedRaw\": 37770, \"totalSubmissionRaw\": 88962, \"acRate\": \"42.5%\"}", "similarQuestions": "[{\"title\": \"Strobogrammatic Number\", \"titleSlug\": \"strobogrammatic-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Strobogrammatic Number II\", \"titleSlug\": \"strobogrammatic-number-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9202,9 +9202,9 @@ "questionFrontendId": "249", "title": "Group Shifted Strings", "content": null, - "likes": 1722, - "dislikes": 418, - "stats": "{\"totalAccepted\": \"275.8K\", \"totalSubmission\": \"412.7K\", \"totalAcceptedRaw\": 275755, \"totalSubmissionRaw\": 412744, \"acRate\": \"66.8%\"}", + "likes": 1755, + "dislikes": 431, + "stats": "{\"totalAccepted\": \"296.4K\", \"totalSubmission\": \"440K\", \"totalAcceptedRaw\": 296443, \"totalSubmissionRaw\": 440034, \"acRate\": \"67.4%\"}", "similarQuestions": "[{\"title\": \"Group Anagrams\", \"titleSlug\": \"group-anagrams\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Maximum Number of String Pairs\", \"titleSlug\": \"find-maximum-number-of-string-pairs\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9239,9 +9239,9 @@ "questionFrontendId": "250", "title": "Count Univalue Subtrees", "content": null, - "likes": 1219, - "dislikes": 444, - "stats": "{\"totalAccepted\": \"160.4K\", \"totalSubmission\": \"281.8K\", \"totalAcceptedRaw\": 160372, \"totalSubmissionRaw\": 281833, \"acRate\": \"56.9%\"}", + "likes": 1232, + "dislikes": 451, + "stats": "{\"totalAccepted\": \"164.6K\", \"totalSubmission\": \"287.9K\", \"totalAcceptedRaw\": 164618, \"totalSubmissionRaw\": 287922, \"acRate\": \"57.2%\"}", "similarQuestions": "[{\"title\": \"Subtree of Another Tree\", \"titleSlug\": \"subtree-of-another-tree\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Longest Univalue Path\", \"titleSlug\": \"longest-univalue-path\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9276,9 +9276,9 @@ "questionFrontendId": "251", "title": "Flatten 2D Vector", "content": null, - "likes": 728, - "dislikes": 410, - "stats": "{\"totalAccepted\": \"134.5K\", \"totalSubmission\": \"269.3K\", \"totalAcceptedRaw\": 134492, \"totalSubmissionRaw\": 269329, \"acRate\": \"49.9%\"}", + "likes": 734, + "dislikes": 415, + "stats": "{\"totalAccepted\": \"138.9K\", \"totalSubmission\": \"277K\", \"totalAcceptedRaw\": 138890, \"totalSubmissionRaw\": 277016, \"acRate\": \"50.1%\"}", "similarQuestions": "[{\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Peeking Iterator\", \"titleSlug\": \"peeking-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flatten Nested List Iterator\", \"titleSlug\": \"flatten-nested-list-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -9324,9 +9324,9 @@ "questionFrontendId": "252", "title": "Meeting Rooms", "content": null, - "likes": 2068, - "dislikes": 110, - "stats": "{\"totalAccepted\": \"447K\", \"totalSubmission\": \"761.6K\", \"totalAcceptedRaw\": 447035, \"totalSubmissionRaw\": 761575, \"acRate\": \"58.7%\"}", + "likes": 2082, + "dislikes": 111, + "stats": "{\"totalAccepted\": \"468.7K\", \"totalSubmission\": \"795.2K\", \"totalAcceptedRaw\": 468741, \"totalSubmissionRaw\": 795209, \"acRate\": \"58.9%\"}", "similarQuestions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms II\", \"titleSlug\": \"meeting-rooms-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms III\", \"titleSlug\": \"meeting-rooms-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Points That Intersect With Cars\", \"titleSlug\": \"points-that-intersect-with-cars\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9358,9 +9358,9 @@ "questionFrontendId": "253", "title": "Meeting Rooms II", "content": null, - "likes": 7055, - "dislikes": 169, - "stats": "{\"totalAccepted\": \"999.7K\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 999731, \"totalSubmissionRaw\": 1927812, \"acRate\": \"51.9%\"}", + "likes": 7121, + "dislikes": 173, + "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1053244, \"totalSubmissionRaw\": 2020251, \"acRate\": \"52.1%\"}", "similarQuestions": "[{\"title\": \"Merge Intervals\", \"titleSlug\": \"merge-intervals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms\", \"titleSlug\": \"meeting-rooms\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Arrows to Burst Balloons\", \"titleSlug\": \"minimum-number-of-arrows-to-burst-balloons\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Car Pooling\", \"titleSlug\": \"car-pooling\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Flowers in Full Bloom\", \"titleSlug\": \"number-of-flowers-in-full-bloom\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Meeting Rooms III\", \"titleSlug\": \"meeting-rooms-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Total Cost to Hire K Workers\", \"titleSlug\": \"total-cost-to-hire-k-workers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Points That Intersect With Cars\", \"titleSlug\": \"points-that-intersect-with-cars\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -9409,9 +9409,9 @@ "questionFrontendId": "254", "title": "Factor Combinations", "content": null, - "likes": 1154, + "likes": 1163, "dislikes": 75, - "stats": "{\"totalAccepted\": \"134.2K\", \"totalSubmission\": \"267.9K\", \"totalAcceptedRaw\": 134220, \"totalSubmissionRaw\": 267944, \"acRate\": \"50.1%\"}", + "stats": "{\"totalAccepted\": \"137K\", \"totalSubmission\": \"272.7K\", \"totalAcceptedRaw\": 137015, \"totalSubmissionRaw\": 272714, \"acRate\": \"50.2%\"}", "similarQuestions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9440,9 +9440,9 @@ "questionFrontendId": "255", "title": "Verify Preorder Sequence in Binary Search Tree", "content": null, - "likes": 1226, + "likes": 1248, "dislikes": 90, - "stats": "{\"totalAccepted\": \"85.8K\", \"totalSubmission\": \"169.5K\", \"totalAcceptedRaw\": 85775, \"totalSubmissionRaw\": 169518, \"acRate\": \"50.6%\"}", + "stats": "{\"totalAccepted\": \"90.2K\", \"totalSubmission\": \"175.7K\", \"totalAcceptedRaw\": 90182, \"totalSubmissionRaw\": 175744, \"acRate\": \"51.3%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Preorder Traversal\", \"titleSlug\": \"binary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9489,9 +9489,9 @@ "questionFrontendId": "256", "title": "Paint House", "content": null, - "likes": 2330, + "likes": 2345, "dislikes": 132, - "stats": "{\"totalAccepted\": \"223.7K\", \"totalSubmission\": \"353.2K\", \"totalAcceptedRaw\": 223676, \"totalSubmissionRaw\": 353155, \"acRate\": \"63.3%\"}", + "stats": "{\"totalAccepted\": \"231.7K\", \"totalSubmission\": \"363.5K\", \"totalAcceptedRaw\": 231656, \"totalSubmissionRaw\": 363548, \"acRate\": \"63.7%\"}", "similarQuestions": "[{\"title\": \"House Robber\", \"titleSlug\": \"house-robber\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"House Robber II\", \"titleSlug\": \"house-robber-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Paint House II\", \"titleSlug\": \"paint-house-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Paint Fence\", \"titleSlug\": \"paint-fence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Path Cost in a Grid\", \"titleSlug\": \"minimum-path-cost-in-a-grid\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -9523,9 +9523,9 @@ "questionFrontendId": "257", "title": "Binary Tree Paths", "content": "Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,null,5]\nOutput: ["1->2->5","1->3"]\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: ["1"]\n\n\n
\n
Constraints:
\n\n[1, 100]
.-100 <= Node.val <= 100
Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
\n
Example 1:
\n\n\nInput: num = 38\nOutput: 2\nExplanation: The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.\n\n\n
Example 2:
\n\n\nInput: num = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n0 <= num <= 231 - 1
\n
Follow up: Could you do it without any loop/recursion in O(1)
runtime?
Given an integer array nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,3,2,5]\nOutput: [3,5]\nExplanation: [5, 3] is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: nums = [-1,0]\nOutput: [-1,0]\n\n\n
Example 3:
\n\n\nInput: nums = [0,1]\nOutput: [1,0]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 3 * 104
-231 <= nums[i] <= 231 - 1
nums
will appear twice, only two integers will appear once.Table: Trips
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| id | int |\n| client_id | int |\n| driver_id | int |\n| city_id | int |\n| status | enum |\n| request_at | varchar | \n+-------------+----------+\nid is the primary key (column with unique values) for this table.\nThe table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table.\nStatus is an ENUM (category) type of ('completed', 'cancelled_by_driver', 'cancelled_by_client').\n\n\n
\n\n
Table: Users
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| users_id | int |\n| banned | enum |\n| role | enum |\n+-------------+----------+\nusers_id is the primary key (column with unique values) for this table.\nThe table holds all users. Each user has a unique users_id, and role is an ENUM type of ('client', 'driver', 'partner').\nbanned is an ENUM (category) type of ('Yes', 'No').\n\n\n
\n\n
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
\n\nWrite a solution to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01"
and "2013-10-03"
. Round Cancellation Rate
to two decimal points.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTrips table:\n+----+-----------+-----------+---------+---------------------+------------+\n| id | client_id | driver_id | city_id | status | request_at |\n+----+-----------+-----------+---------+---------------------+------------+\n| 1 | 1 | 10 | 1 | completed | 2013-10-01 |\n| 2 | 2 | 11 | 1 | cancelled_by_driver | 2013-10-01 |\n| 3 | 3 | 12 | 6 | completed | 2013-10-01 |\n| 4 | 4 | 13 | 6 | cancelled_by_client | 2013-10-01 |\n| 5 | 1 | 10 | 1 | completed | 2013-10-02 |\n| 6 | 2 | 11 | 6 | completed | 2013-10-02 |\n| 7 | 3 | 12 | 6 | completed | 2013-10-02 |\n| 8 | 2 | 12 | 12 | completed | 2013-10-03 |\n| 9 | 3 | 10 | 12 | completed | 2013-10-03 |\n| 10 | 4 | 13 | 12 | cancelled_by_driver | 2013-10-03 |\n+----+-----------+-----------+---------+---------------------+------------+\nUsers table:\n+----------+--------+--------+\n| users_id | banned | role |\n+----------+--------+--------+\n| 1 | No | client |\n| 2 | Yes | client |\n| 3 | No | client |\n| 4 | No | client |\n| 10 | No | driver |\n| 11 | No | driver |\n| 12 | No | driver |\n| 13 | No | driver |\n+----------+--------+--------+\nOutput: \n+------------+-------------------+\n| Day | Cancellation Rate |\n+------------+-------------------+\n| 2013-10-01 | 0.33 |\n| 2013-10-02 | 0.00 |\n| 2013-10-03 | 0.50 |\n+------------+-------------------+\nExplanation: \nOn 2013-10-01:\n - There were 4 requests in total, 2 of which were canceled.\n - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation.\n - Hence there are 3 unbanned requests in total, 1 of which was canceled.\n - The Cancellation Rate is (1 / 3) = 0.33\nOn 2013-10-02:\n - There were 3 requests in total, 0 of which were canceled.\n - The request with Id=6 was made by a banned client, so it is ignored.\n - Hence there are 2 unbanned requests in total, 0 of which were canceled.\n - The Cancellation Rate is (0 / 2) = 0.00\nOn 2013-10-03:\n - There were 3 requests in total, 1 of which was canceled.\n - The request with Id=8 was made by a banned client, so it is ignored.\n - Hence there are 2 unbanned request in total, 1 of which were canceled.\n - The Cancellation Rate is (1 / 2) = 0.50\n\n", - "likes": 1290, - "dislikes": 680, - "stats": "{\"totalAccepted\": \"214.1K\", \"totalSubmission\": \"579.5K\", \"totalAcceptedRaw\": 214097, \"totalSubmissionRaw\": 579549, \"acRate\": \"36.9%\"}", + "content": "
Table: Trips
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| id | int |\n| client_id | int |\n| driver_id | int |\n| city_id | int |\n| status | enum |\n| request_at | varchar | \n+-------------+----------+\nid is the primary key (column with unique values) for this table.\nThe table holds all taxi trips. Each trip has a unique id, while client_id and driver_id are foreign keys to the users_id at the Users table.\nStatus is an ENUM (category) type of ('completed', 'cancelled_by_driver', 'cancelled_by_client').\n\n\n
\n\n
Table: Users
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| users_id | int |\n| banned | enum |\n| role | enum |\n+-------------+----------+\nusers_id is the primary key (column with unique values) for this table.\nThe table holds all users. Each user has a unique users_id, and role is an ENUM type of ('client', 'driver', 'partner').\nbanned is an ENUM (category) type of ('Yes', 'No').\n\n\n
\n\n
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
\n\nWrite a solution to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01"
and "2013-10-03"
with at least one trip. Round Cancellation Rate
to two decimal points.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTrips table:\n+----+-----------+-----------+---------+---------------------+------------+\n| id | client_id | driver_id | city_id | status | request_at |\n+----+-----------+-----------+---------+---------------------+------------+\n| 1 | 1 | 10 | 1 | completed | 2013-10-01 |\n| 2 | 2 | 11 | 1 | cancelled_by_driver | 2013-10-01 |\n| 3 | 3 | 12 | 6 | completed | 2013-10-01 |\n| 4 | 4 | 13 | 6 | cancelled_by_client | 2013-10-01 |\n| 5 | 1 | 10 | 1 | completed | 2013-10-02 |\n| 6 | 2 | 11 | 6 | completed | 2013-10-02 |\n| 7 | 3 | 12 | 6 | completed | 2013-10-02 |\n| 8 | 2 | 12 | 12 | completed | 2013-10-03 |\n| 9 | 3 | 10 | 12 | completed | 2013-10-03 |\n| 10 | 4 | 13 | 12 | cancelled_by_driver | 2013-10-03 |\n+----+-----------+-----------+---------+---------------------+------------+\nUsers table:\n+----------+--------+--------+\n| users_id | banned | role |\n+----------+--------+--------+\n| 1 | No | client |\n| 2 | Yes | client |\n| 3 | No | client |\n| 4 | No | client |\n| 10 | No | driver |\n| 11 | No | driver |\n| 12 | No | driver |\n| 13 | No | driver |\n+----------+--------+--------+\nOutput: \n+------------+-------------------+\n| Day | Cancellation Rate |\n+------------+-------------------+\n| 2013-10-01 | 0.33 |\n| 2013-10-02 | 0.00 |\n| 2013-10-03 | 0.50 |\n+------------+-------------------+\nExplanation: \nOn 2013-10-01:\n - There were 4 requests in total, 2 of which were canceled.\n - However, the request with Id=2 was made by a banned client (User_Id=2), so it is ignored in the calculation.\n - Hence there are 3 unbanned requests in total, 1 of which was canceled.\n - The Cancellation Rate is (1 / 3) = 0.33\nOn 2013-10-02:\n - There were 3 requests in total, 0 of which were canceled.\n - The request with Id=6 was made by a banned client, so it is ignored.\n - Hence there are 2 unbanned requests in total, 0 of which were canceled.\n - The Cancellation Rate is (0 / 2) = 0.00\nOn 2013-10-03:\n - There were 3 requests in total, 1 of which was canceled.\n - The request with Id=8 was made by a banned client, so it is ignored.\n - Hence there are 2 unbanned request in total, 1 of which were canceled.\n - The Cancellation Rate is (1 / 2) = 0.50\n\n", + "likes": 1326, + "dislikes": 689, + "stats": "{\"totalAccepted\": \"232.5K\", \"totalSubmission\": \"627.4K\", \"totalAcceptedRaw\": 232549, \"totalSubmissionRaw\": 627372, \"acRate\": \"37.1%\"}", "similarQuestions": "[{\"title\": \"Hopper Company Queries I\", \"titleSlug\": \"hopper-company-queries-i\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries II\", \"titleSlug\": \"hopper-company-queries-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries III\", \"titleSlug\": \"hopper-company-queries-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -9756,9 +9756,9 @@ "questionFrontendId": "263", "title": "Ugly Number", "content": "
An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5.
\n\nGiven an integer n
, return true
if n
is an ugly number.
\n
Example 1:
\n\n\nInput: n = 6\nOutput: true\nExplanation: 6 = 2 × 3\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: true\nExplanation: 1 has no prime factors.\n\n\n
Example 3:
\n\n\nInput: n = 14\nOutput: false\nExplanation: 14 is not ugly since it includes the prime factor 7.\n\n\n
\n
Constraints:
\n\n-231 <= n <= 231 - 1
An ugly number is a positive integer whose prime factors are limited to 2
, 3
, and 5
.
Given an integer n
, return the nth
ugly number.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 12\nExplanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1690
Given an array nums
containing n
distinct numbers in the range [0, n]
, return the only number in the range that is missing from the array.
\n
Example 1:
\n\nInput: nums = [3,0,1]
\n\nOutput: 2
\n\nExplanation:
\n\nn = 3
since there are 3 numbers, so all numbers are in the range [0,3]
. 2 is the missing number in the range since it does not appear in nums
.
Example 2:
\n\nInput: nums = [0,1]
\n\nOutput: 2
\n\nExplanation:
\n\nn = 2
since there are 2 numbers, so all numbers are in the range [0,2]
. 2 is the missing number in the range since it does not appear in nums
.
Example 3:
\n\nInput: nums = [9,6,4,2,3,5,7,0,1]
\n\nOutput: 8
\n\nExplanation:
\n\nn = 9
since there are 9 numbers, so all numbers are in the range [0,9]
. 8 is the missing number in the range since it does not appear in nums
.
\n\n
\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 104
0 <= nums[i] <= n
nums
are unique.\n
Follow up: Could you implement a solution using only O(1)
extra space complexity and O(n)
runtime complexity?
Convert a non-negative integer num
to its English words representation.
\n
Example 1:
\n\n\nInput: num = 123\nOutput: "One Hundred Twenty Three"\n\n\n
Example 2:
\n\n\nInput: num = 12345\nOutput: "Twelve Thousand Three Hundred Forty Five"\n\n\n
Example 3:
\n\n\nInput: num = 1234567\nOutput: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"\n\n\n
\n
Constraints:
\n\n0 <= num <= 231 - 1
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h
such that the given researcher has published at least h
papers that have each been cited at least h
times.
\n
Example 1:
\n\n\nInput: citations = [3,0,6,1,5]\nOutput: 3\nExplanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\n
Example 2:
\n\n\nInput: citations = [1,3,1]\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == citations.length
1 <= n <= 5000
0 <= citations[i] <= 1000
Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in ascending order, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h
such that the given researcher has published at least h
papers that have each been cited at least h
times.
You must write an algorithm that runs in logarithmic time.
\n\n\n
Example 1:
\n\n\nInput: citations = [0,1,3,5,6]\nOutput: 3\nExplanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\n
Example 2:
\n\n\nInput: citations = [1,2,100]\nOutput: 2\n\n\n
\n
Constraints:
\n\nn == citations.length
1 <= n <= 105
0 <= citations[i] <= 1000
citations
is sorted in ascending order.Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their ith
paper and citations
is sorted in non-descending order, return the researcher's h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h
such that the given researcher has published at least h
papers that have each been cited at least h
times.
You must write an algorithm that runs in logarithmic time.
\n\n\n
Example 1:
\n\n\nInput: citations = [0,1,3,5,6]\nOutput: 3\nExplanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\n\n\n
Example 2:
\n\n\nInput: citations = [1,2,100]\nOutput: 2\n\n\n
\n
Constraints:
\n\nn == citations.length
1 <= n <= 105
0 <= citations[i] <= 1000
citations
is sorted in ascending order.You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
\n\nSuppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which returns whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
\n
Example 1:
\n\n\nInput: n = 5, bad = 4\nOutput: 4\nExplanation:\ncall isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.\n\n\n
Example 2:
\n\n\nInput: n = 1, bad = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= bad <= n <= 231 - 1
Given an integer n
, return the least number of perfect square numbers that sum to n
.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1
, 4
, 9
, and 16
are perfect squares while 3
and 11
are not.
\n
Example 1:
\n\n\nInput: n = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4.\n\n\n
Example 2:
\n\n\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
Given a string num
that contains only digits and an integer target
, return all possibilities to insert the binary operators '+'
, '-'
, and/or '*'
between the digits of num
so that the resultant expression evaluates to the target
value.
Note that operands in the returned expressions should not contain leading zeros.
\n\n\n
Example 1:
\n\n\nInput: num = "123", target = 6\nOutput: ["1*2*3","1+2+3"]\nExplanation: Both "1*2*3" and "1+2+3" evaluate to 6.\n\n\n
Example 2:
\n\n\nInput: num = "232", target = 8\nOutput: ["2*3+2","2+3*2"]\nExplanation: Both "2*3+2" and "2+3*2" evaluate to 8.\n\n\n
Example 3:
\n\n\nInput: num = "3456237490", target = 9191\nOutput: []\nExplanation: There are no expressions that can be created from "3456237490" to evaluate to 9191.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 10
num
consists of only digits.-231 <= target <= 231 - 1
Given an integer array nums
, move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
\n\n\n
Example 1:
\nInput: nums = [0,1,0,3,12]\nOutput: [1,3,12,0,0]\n
Example 2:
\nInput: nums = [0]\nOutput: [0]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
\nFollow up: Could you minimize the total number of operations done?", - "likes": 17481, - "dislikes": 504, - "stats": "{\"totalAccepted\": \"3.7M\", \"totalSubmission\": \"6M\", \"totalAcceptedRaw\": 3718482, \"totalSubmissionRaw\": 5953064, \"acRate\": \"62.5%\"}", + "likes": 17944, + "dislikes": 528, + "stats": "{\"totalAccepted\": \"4.1M\", \"totalSubmission\": \"6.5M\", \"totalAcceptedRaw\": 4081636, \"totalSubmissionRaw\": 6500232, \"acRate\": \"62.8%\"}", "similarQuestions": "[{\"title\": \"Remove Element\", \"titleSlug\": \"remove-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Apply Operations to an Array\", \"titleSlug\": \"apply-operations-to-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -10590,9 +10590,9 @@ "questionFrontendId": "284", "title": "Peeking Iterator", "content": "
Design an iterator that supports the peek
operation on an existing iterator in addition to the hasNext
and the next
operations.
Implement the PeekingIterator
class:
PeekingIterator(Iterator<int> nums)
Initializes the object with the given integer iterator iterator
.int next()
Returns the next element in the array and moves the pointer to the next element.boolean hasNext()
Returns true
if there are still elements in the array.int peek()
Returns the next element in the array without moving the pointer.Note: Each language may have a different implementation of the constructor and Iterator
, but they all support the int next()
and boolean hasNext()
functions.
\n
Example 1:
\n\n\nInput\n["PeekingIterator", "next", "peek", "next", "next", "hasNext"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 2, 2, 3, false]\n\nExplanation\nPeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\npeekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\npeekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\npeekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\npeekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\npeekingIterator.hasNext(); // return False\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
next
and peek
are valid.1000
calls will be made to next
, hasNext
, and peek
.\nFollow up: How would you extend your design to be generic and work with all types, not just integer?", - "likes": 1872, - "dislikes": 1042, - "stats": "{\"totalAccepted\": \"231.9K\", \"totalSubmission\": \"384.5K\", \"totalAcceptedRaw\": 231920, \"totalSubmissionRaw\": 384543, \"acRate\": \"60.3%\"}", + "likes": 1886, + "dislikes": 1045, + "stats": "{\"totalAccepted\": \"238K\", \"totalSubmission\": \"394.4K\", \"totalAcceptedRaw\": 238012, \"totalSubmissionRaw\": 394446, \"acRate\": \"60.3%\"}", "similarQuestions": "[{\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Flatten 2D Vector\", \"titleSlug\": \"flatten-2d-vector\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Zigzag Iterator\", \"titleSlug\": \"zigzag-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -10632,9 +10632,9 @@ "questionFrontendId": "285", "title": "Inorder Successor in BST", "content": null, - "likes": 2595, + "likes": 2607, "dislikes": 93, - "stats": "{\"totalAccepted\": \"349.3K\", \"totalSubmission\": \"692.5K\", \"totalAcceptedRaw\": 349318, \"totalSubmissionRaw\": 692508, \"acRate\": \"50.4%\"}", + "stats": "{\"totalAccepted\": \"356.1K\", \"totalSubmission\": \"703K\", \"totalAcceptedRaw\": 356138, \"totalSubmissionRaw\": 703008, \"acRate\": \"50.7%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Binary Search Tree Iterator\", \"titleSlug\": \"binary-search-tree-iterator\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Inorder Successor in BST II\", \"titleSlug\": \"inorder-successor-in-bst-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -10672,9 +10672,9 @@ "questionFrontendId": "286", "title": "Walls and Gates", "content": null, - "likes": 3210, - "dislikes": 69, - "stats": "{\"totalAccepted\": \"361.7K\", \"totalSubmission\": \"579.3K\", \"totalAcceptedRaw\": 361713, \"totalSubmissionRaw\": 579265, \"acRate\": \"62.4%\"}", + "likes": 3254, + "dislikes": 71, + "stats": "{\"totalAccepted\": \"383.7K\", \"totalSubmission\": \"609.5K\", \"totalAcceptedRaw\": 383671, \"totalSubmissionRaw\": 609474, \"acRate\": \"63.0%\"}", "similarQuestions": "[{\"title\": \"Surrounded Regions\", \"titleSlug\": \"surrounded-regions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Number of Islands\", \"titleSlug\": \"number-of-islands\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Distance from All Buildings\", \"titleSlug\": \"shortest-distance-from-all-buildings\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Battleships in a Board\", \"titleSlug\": \"battleships-in-a-board\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Robot Room Cleaner\", \"titleSlug\": \"robot-room-cleaner\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Rotting Oranges\", \"titleSlug\": \"rotting-oranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Houses at a Certain Distance I\", \"titleSlug\": \"count-the-number-of-houses-at-a-certain-distance-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count the Number of Houses at a Certain Distance II\", \"titleSlug\": \"count-the-number-of-houses-at-a-certain-distance-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -10709,9 +10709,9 @@ "questionFrontendId": "287", "title": "Find the Duplicate Number", "content": "
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive.
There is only one repeated number in nums
, return this repeated number.
You must solve the problem without modifying the array nums
and using only constant extra space.
\n
Example 1:
\n\n\nInput: nums = [1,3,4,2,2]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: nums = [3,1,3,4,2]\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: nums = [3,3,3,3,3]\nOutput: 3\n\n
\n
Constraints:
\n\n1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums
appear only once except for precisely one integer which appears two or more times.\n
Follow up:
\n\nnums
?According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
\n\nThe board is made up of an m x n
grid of cells, where each cell has an initial state: live (represented by a 1
) or dead (represented by a 0
). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n
grid board
. In this process, births and deaths occur simultaneously.
Given the current state of the board
, update the board
to reflect its next state.
Note that you do not need to return anything.
\n\n\n
Example 1:
\n\nInput: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n\n\n
Example 2:
\n\nInput: board = [[1,1],[1,0]]\nOutput: [[1,1],[1,1]]\n\n\n
\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m, n <= 25
board[i][j]
is 0
or 1
.\n
Follow up:
\n\nGiven a pattern
and a string s
, find if s
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in s
. Specifically:
pattern
maps to exactly one unique word in s
.s
maps to exactly one letter in pattern
.\n
Example 1:
\n\nInput: pattern = "abba", s = "dog cat cat dog"
\n\nOutput: true
\n\nExplanation:
\n\nThe bijection can be established as:
\n\n'a'
maps to "dog"
.'b'
maps to "cat"
.Example 2:
\n\nInput: pattern = "abba", s = "dog cat cat fish"
\n\nOutput: false
\nExample 3:
\n\nInput: pattern = "aaaa", s = "dog cat cat dog"
\n\nOutput: false
\n\n
Constraints:
\n\n1 <= pattern.length <= 300
pattern
contains only lower-case English letters.1 <= s.length <= 3000
s
contains only lowercase English letters and spaces ' '
.s
does not contain any leading or trailing spaces.s
are separated by a single space.You are playing the following Nim Game with your friend:
\n\nGiven n
, the number of stones in the heap, return true
if you can win the game assuming both you and your friend play optimally, otherwise return false
.
\n
Example 1:
\n\n\nInput: n = 4\nOutput: false\nExplanation: These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: true\n\n\n
Example 3:
\n\n\nInput: n = 2\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
\n\narr = [2,3,4]
, the median is 3
.arr = [2,3]
, the median is (2 + 3) / 2 = 2.5
.Implement the MedianFinder class:
\n\nMedianFinder()
initializes the MedianFinder
object.void addNum(int num)
adds the integer num
from the data stream to the data structure.double findMedian()
returns the median of all elements so far. Answers within 10-5
of the actual answer will be accepted.\n
Example 1:
\n\n\nInput\n["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]\n[[], [1], [2], [], [3], []]\nOutput\n[null, null, null, 1.5, null, 2.0]\n\nExplanation\nMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1); // arr = [1]\nmedianFinder.addNum(2); // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3); // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0\n\n\n
\n
Constraints:
\n\n-105 <= num <= 105
findMedian
.5 * 104
calls will be made to addNum
and findMedian
.\n
Follow up:
\n\n[0, 100]
, how would you optimize your solution?99%
of all integer numbers from the stream are in the range [0, 100]
, how would you optimize your solution?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.
\n\nDesign 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.
\n\nClarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,null,null,4,5]\nOutput: [1,2,3,null,null,4,5]\n\n\n
Example 2:
\n\n\nInput: root = []\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 104]
.-1000 <= Node.val <= 1000
You are playing the Bulls and Cows game with your friend.
\n\nYou write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:
\n\nGiven the secret number secret
and your friend's guess guess
, return the hint for your friend's guess.
The hint should be formatted as "xAyB"
, where x
is the number of bulls and y
is the number of cows. Note that both secret
and guess
may contain duplicate digits.
\n
Example 1:
\n\n\nInput: secret = "1807", guess = "7810"\nOutput: "1A3B"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n"1807"\n |\n"7810"\n\n
Example 2:
\n\n\nInput: secret = "1123", guess = "0111"\nOutput: "1A1B"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n"1123" "1123"\n | or |\n"0111" "0111"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.\n\n\n
\n
Constraints:
\n\n1 <= secret.length, guess.length <= 1000
secret.length == guess.length
secret
and guess
consist of digits only.Given an integer array nums
, return the length of the longest strictly increasing subsequence.
\n
Example 1:
\n\n\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nExplanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\n\n\n
Example 3:
\n\n\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2500
-104 <= nums[i] <= 104
\n
Follow up: Can you come up with an algorithm that runs in O(n log(n))
time complexity?
Given a string s
that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.
Return a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: s = "()())()"\nOutput: ["(())()","()()()"]\n\n\n
Example 2:
\n\n\nInput: s = "(a)())()"\nOutput: ["(a())()","(a)()()"]\n\n\n
Example 3:
\n\n\nInput: s = ")("\nOutput: [""]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 25
s
consists of lowercase English letters and parentheses '('
and ')'
.20
parentheses in s
.Given an integer array nums
, handle multiple queries of the following type:
nums
between indices left
and right
inclusive where left <= right
.Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]
).\n
Example 1:
\n\n\nInput\n["NumArray", "sumRange", "sumRange", "sumRange"]\n[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\nOutput\n[null, 1, -1, -3]\n\nExplanation\nNumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\nnumArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\nnumArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\nnumArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
104
calls will be made to sumRange
.Given a 2D matrix matrix
, handle multiple queries of the following type:
matrix
inside the rectangle defined by its upper left corner (row1, col1)
and lower right corner (row2, col2)
.Implement the NumMatrix
class:
NumMatrix(int[][] matrix)
Initializes the object with the integer matrix matrix
.int sumRegion(int row1, int col1, int row2, int col2)
Returns the sum of the elements of matrix
inside the rectangle defined by its upper left corner (row1, col1)
and lower right corner (row2, col2)
.You must design an algorithm where sumRegion
works on O(1)
time complexity.
\n
Example 1:
\n\nInput\n["NumMatrix", "sumRegion", "sumRegion", "sumRegion"]\n[[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\nOutput\n[null, 8, 11, 12]\n\nExplanation\nNumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\nnumMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\nnumMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\nnumMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 200
-104 <= matrix[i][j] <= 104
0 <= row1 <= row2 < m
0 <= col1 <= col2 < n
104
calls will be made to sumRegion
.An additive number is a string whose digits can form an additive sequence.
\n\nA valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
\n\nGiven a string containing only digits, return true
if it is an additive number or false
otherwise.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03
or 1, 02, 3
is invalid.
\n
Example 1:
\n\n\nInput: "112358"\nOutput: true\nExplanation: \nThe digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n\n\n
Example 2:
\n\n\nInput: "199100199"\nOutput: true\nExplanation: \nThe additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 35
num
consists only of digits.\n
Follow up: How would you handle overflow for very large input integers?
\n", - "likes": 1205, - "dislikes": 811, - "stats": "{\"totalAccepted\": \"100K\", \"totalSubmission\": \"310.5K\", \"totalAcceptedRaw\": 99982, \"totalSubmissionRaw\": 310502, \"acRate\": \"32.2%\"}", + "likes": 1217, + "dislikes": 815, + "stats": "{\"totalAccepted\": \"104.8K\", \"totalSubmission\": \"322.2K\", \"totalAcceptedRaw\": 104818, \"totalSubmissionRaw\": 322168, \"acRate\": \"32.5%\"}", "similarQuestions": "[{\"title\": \"Split Array into Fibonacci Sequence\", \"titleSlug\": \"split-array-into-fibonacci-sequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -11479,9 +11479,9 @@ "questionFrontendId": "307", "title": "Range Sum Query - Mutable", "content": "Given an integer array nums
, handle multiple queries of the following types:
nums
.nums
between indices left
and right
inclusive where left <= right
.Implement the NumArray
class:
NumArray(int[] nums)
Initializes the object with the integer array nums
.void update(int index, int val)
Updates the value of nums[index]
to be val
.int sumRange(int left, int right)
Returns the sum of the elements of nums
between indices left
and right
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]
).\n
Example 1:
\n\n\nInput\n["NumArray", "sumRange", "update", "sumRange"]\n[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\nOutput\n[null, 9, null, 8]\n\nExplanation\nNumArray numArray = new NumArray([1, 3, 5]);\nnumArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\nnumArray.update(1, 2); // nums = [1, 2, 5]\nnumArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
0 <= index < nums.length
-100 <= val <= 100
0 <= left <= right < nums.length
3 * 104
calls will be made to update
and sumRange
.You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
\n\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
\n\n\n
Example 1:
\n\n\nInput: prices = [1,2,3,0,2]\nOutput: 3\nExplanation: transactions = [buy, sell, cooldown, buy, sell]\n\n\n
Example 2:
\n\n\nInput: prices = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 5000
0 <= prices[i] <= 1000
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.
\n\nGiven a tree of n
nodes labelled 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.
\n\nThe height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
\n\n\n
Example 1:
\n\nInput: n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput: [1]\nExplanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\n\n\n
Example 2:
\n\nInput: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput: [3,4]\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
(ai, bi)
are distinct.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, then treat it as if there is a balloon with a 1
painted on it.
Return the maximum coins you can collect by bursting the balloons wisely.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,5,8]\nOutput: 167\nExplanation:\nnums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167\n\n
Example 2:
\n\n\nInput: nums = [1,5]\nOutput: 10\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 300
0 <= nums[i] <= 100
A super ugly number is a positive integer whose prime factors are in the array primes
.
Given an integer n
and an array of integers primes
, return the nth
super ugly number.
The nth
super ugly number is guaranteed to fit in a 32-bit signed integer.
\n
Example 1:
\n\n\nInput: n = 12, primes = [2,7,13,19]\nOutput: 32\nExplanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].\n\n\n
Example 2:
\n\n\nInput: n = 1, primes = [2,3,5]\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= primes.length <= 100
2 <= primes[i] <= 1000
primes[i]
is guaranteed to be a prime number.primes
are unique and sorted in ascending order.Given an integer array nums
, return an integer array counts
where counts[i]
is the number of smaller elements to the right of nums[i]
.
\n
Example 1:
\n\n\nInput: nums = [5,2,6,1]\nOutput: [2,1,1,0]\nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\n\n\n
Example 2:
\n\n\nInput: nums = [-1]\nOutput: [0]\n\n\n
Example 3:
\n\n\nInput: nums = [-1,-1]\nOutput: [0,0]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
Given a string s
, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
\n
Example 1:
\n\n\nInput: s = "bcabc"\nOutput: "abc"\n\n\n
Example 2:
\n\n\nInput: s = "cbacdcbc"\nOutput: "acdb"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of lowercase English letters.\n
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
\n", - "likes": 8843, - "dislikes": 648, - "stats": "{\"totalAccepted\": \"366.1K\", \"totalSubmission\": \"721.8K\", \"totalAcceptedRaw\": 366059, \"totalSubmissionRaw\": 721839, \"acRate\": \"50.7%\"}", + "likes": 8942, + "dislikes": 664, + "stats": "{\"totalAccepted\": \"384.3K\", \"totalSubmission\": \"748.7K\", \"totalAcceptedRaw\": 384302, \"totalSubmissionRaw\": 748683, \"acRate\": \"51.3%\"}", "similarQuestions": "[{\"title\": \"Smallest K-Length Subsequence With Occurrences of a Letter\", \"titleSlug\": \"smallest-k-length-subsequence-with-occurrences-of-a-letter\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -11882,9 +11882,9 @@ "questionFrontendId": "317", "title": "Shortest Distance from All Buildings", "content": null, - "likes": 1898, - "dislikes": 323, - "stats": "{\"totalAccepted\": \"191.8K\", \"totalSubmission\": \"438.3K\", \"totalAcceptedRaw\": 191823, \"totalSubmissionRaw\": 438344, \"acRate\": \"43.8%\"}", + "likes": 1949, + "dislikes": 338, + "stats": "{\"totalAccepted\": \"205.1K\", \"totalSubmission\": \"462.3K\", \"totalAcceptedRaw\": 205089, \"totalSubmissionRaw\": 462344, \"acRate\": \"44.4%\"}", "similarQuestions": "[{\"title\": \"Walls and Gates\", \"titleSlug\": \"walls-and-gates\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Best Meeting Point\", \"titleSlug\": \"best-meeting-point\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"As Far from Land as Possible\", \"titleSlug\": \"as-far-from-land-as-possible\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -11919,9 +11919,9 @@ "questionFrontendId": "318", "title": "Maximum Product of Word Lengths", "content": "Given a string array words
, return the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. If no such two words exist, return 0
.
\n
Example 1:
\n\n\nInput: words = ["abcw","baz","foo","bar","xtfn","abcdef"]\nOutput: 16\nExplanation: The two words can be "abcw", "xtfn".\n\n\n
Example 2:
\n\n\nInput: words = ["a","ab","abc","d","cd","bcd","abcd"]\nOutput: 4\nExplanation: The two words can be "ab", "cd".\n\n\n
Example 3:
\n\n\nInput: words = ["a","aa","aaa","aaaa"]\nOutput: 0\nExplanation: No such pair of words.\n\n\n
\n
Constraints:
\n\n2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i]
consists only of lowercase English letters.There are n
bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith
round, you toggle every i
bulb. For the nth
round, you only toggle the last bulb.
Return the number of bulbs that are on after n
rounds.
\n
Example 1:
\n\nInput: n = 3\nOutput: 1\nExplanation: At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
You are given two integer arrays nums1
and nums2
of lengths m
and n
respectively. nums1
and nums2
represent the digits of two numbers. You are also given an integer k
.
Create the maximum number of length k <= m + n
from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the k
digits representing the answer.
\n
Example 1:
\n\n\nInput: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\nOutput: [9,8,6,5,3]\n\n\n
Example 2:
\n\n\nInput: nums1 = [6,7], nums2 = [6,0,4], k = 5\nOutput: [6,7,6,0,4]\n\n\n
Example 3:
\n\n\nInput: nums1 = [3,9], nums2 = [8,9], k = 3\nOutput: [9,8,9]\n\n\n
\n
Constraints:
\n\nm == nums1.length
n == nums2.length
1 <= m, n <= 500
0 <= nums1[i], nums2[i] <= 9
1 <= k <= m + n
nums1
and nums2
do not have leading zeros.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 assume that you have an infinite number of each kind of coin.
\n\n\n
Example 1:
\n\n\nInput: coins = [1,2,5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\n\n\n
Example 2:
\n\n\nInput: coins = [2], amount = 3\nOutput: -1\n\n\n
Example 3:
\n\n\nInput: coins = [1], amount = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104
Given an integer array nums
, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]...
.
You may assume the input array always has a valid answer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,5,1,1,6,4]\nOutput: [1,6,1,5,1,4]\nExplanation: [1,4,1,5,1,6] is also accepted.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,2,2,3,1]\nOutput: [2,3,1,3,1,2]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
0 <= nums[i] <= 5000
nums
.\nFollow Up: Can you do it in
O(n)
time and/or in-place with O(1)
extra space?",
- "likes": 3130,
- "dislikes": 972,
- "stats": "{\"totalAccepted\": \"173.7K\", \"totalSubmission\": \"493.1K\", \"totalAcceptedRaw\": 173735, \"totalSubmissionRaw\": 493149, \"acRate\": \"35.2%\"}",
+ "likes": 3167,
+ "dislikes": 976,
+ "stats": "{\"totalAccepted\": \"180.8K\", \"totalSubmission\": \"507.3K\", \"totalAcceptedRaw\": 180819, \"totalSubmissionRaw\": 507311, \"acRate\": \"35.6%\"}",
"similarQuestions": "[{\"title\": \"Sort Colors\", \"titleSlug\": \"sort-colors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Wiggle Sort\", \"titleSlug\": \"wiggle-sort\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Array With Elements Not Equal to Average of Neighbors\", \"titleSlug\": \"array-with-elements-not-equal-to-average-of-neighbors\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -12184,9 +12184,9 @@
"questionFrontendId": "325",
"title": "Maximum Size Subarray Sum Equals k",
"content": null,
- "likes": 2077,
- "dislikes": 64,
- "stats": "{\"totalAccepted\": \"202K\", \"totalSubmission\": \"402.6K\", \"totalAcceptedRaw\": 202016, \"totalSubmissionRaw\": 402642, \"acRate\": \"50.2%\"}",
+ "likes": 2107,
+ "dislikes": 65,
+ "stats": "{\"totalAccepted\": \"211.3K\", \"totalSubmission\": \"417.6K\", \"totalAcceptedRaw\": 211313, \"totalSubmissionRaw\": 417624, \"acRate\": \"50.6%\"}",
"similarQuestions": "[{\"title\": \"Minimum Size Subarray Sum\", \"titleSlug\": \"minimum-size-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Sum Query - Immutable\", \"titleSlug\": \"range-sum-query-immutable\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Contiguous Array\", \"titleSlug\": \"contiguous-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subarray Product Less Than K\", \"titleSlug\": \"subarray-product-less-than-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Beauty of an Array After Applying Operation\", \"titleSlug\": \"maximum-beauty-of-an-array-after-applying-operation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Subarray With OR at Least K II\", \"titleSlug\": \"shortest-subarray-with-or-at-least-k-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [
@@ -12225,9 +12225,9 @@
"questionFrontendId": "326",
"title": "Power of Three",
"content": "Given an integer n
, return true
if it is a power of three. Otherwise, return false
.
An integer n
is a power of three, if there exists an integer x
such that n == 3x
.
\n
Example 1:
\n\n\nInput: n = 27\nOutput: true\nExplanation: 27 = 33\n\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: false\nExplanation: There is no x where 3x = 0.\n\n\n
Example 3:
\n\n\nInput: n = -1\nOutput: false\nExplanation: There is no x where 3x = (-1).\n\n\n
\n
Constraints:
\n\n-231 <= n <= 231 - 1
\nFollow up: Could you solve it without loops/recursion?", - "likes": 3189, - "dislikes": 284, - "stats": "{\"totalAccepted\": \"959.8K\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 959768, \"totalSubmissionRaw\": 2019058, \"acRate\": \"47.5%\"}", + "likes": 3264, + "dislikes": 292, + "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1027914, \"totalSubmissionRaw\": 2141094, \"acRate\": \"48.0%\"}", "similarQuestions": "[{\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Four\", \"titleSlug\": \"power-of-four\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Check if Number is a Sum of Powers of Three\", \"titleSlug\": \"check-if-number-is-a-sum-of-powers-of-three\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -12259,10 +12259,10 @@ "questionFrontendId": "327", "title": "Count of Range Sum", "content": "
Given an integer array nums
and two integers lower
and upper
, return the number of range sums that lie in [lower, upper]
inclusive.
Range sum S(i, j)
is defined as the sum of the elements in nums
between indices i
and j
inclusive, where i <= j
.
\n
Example 1:
\n\n\nInput: nums = [-2,5,-1], lower = -2, upper = 2\nOutput: 3\nExplanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n\n\n
Example 2:
\n\n\nInput: nums = [0], lower = 0, upper = 0\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
-105 <= lower <= upper <= 105
Given the head
of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
\n\nNote that the relative order inside both the even and odd groups should remain as it was in the input.
\n\nYou must solve the problem in O(1)
extra space complexity and O(n)
time complexity.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5]\nOutput: [1,3,5,2,4]\n\n\n
Example 2:
\n\nInput: head = [2,1,3,5,6,4,7]\nOutput: [2,3,6,7,1,5,4]\n\n\n
\n
Constraints:
\n\n[0, 104]
.-106 <= Node.val <= 106
Given an m x n
integers matrix
, return the length of the longest increasing path in matrix
.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
\n\n\n
Example 1:
\n\nInput: matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput: 4\nExplanation: The longest increasing path is [1, 2, 6, 9]
.\n
\n\nExample 2:
\n\nInput: matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput: 4\nExplanation: The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.\n
\n\nExample 3:
\n\n\nInput: matrix = [[1]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 200
0 <= matrix[i][j] <= 231 - 1
Given a sorted integer array nums
and an integer n
, add/patch elements to the array such that any number in the range [1, n]
inclusive can be formed by the sum of some elements in the array.
Return the minimum number of patches required.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3], n = 6\nOutput: 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\n\n\n
Example 2:
\n\n\nInput: nums = [1,5,10], n = 20\nOutput: 2\nExplanation: The two patches can be [2, 4].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,2], n = 5\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 104
nums
is sorted in ascending order.1 <= n <= 231 - 1
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'
.
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#"
, where '#'
represents a null node.
Given a string of comma-separated values preorder
, return true
if it is a correct preorder traversal serialization of a binary tree.
It is guaranteed that each comma-separated value in the string must be either an integer or a character '#'
representing null pointer.
You may assume that the input format is always valid.
\n\n"1,,3"
.Note: You are not allowed to reconstruct the tree.
\n\n\n
Example 1:
\nInput: preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\n
Example 2:
\nInput: preorder = \"1,#\"\nOutput: false\n
Example 3:
\nInput: preorder = \"9,#,#,1\"\nOutput: false\n\n
\n
Constraints:
\n\n1 <= preorder.length <= 104
preorder
consist of integers in the range [0, 100]
and '#'
separated by commas ','
.You are given a list of airline tickets
where tickets[i] = [fromi, toi]
represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from "JFK"
, thus, the itinerary must begin with "JFK"
. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
["JFK", "LGA"]
has a smaller lexical order than ["JFK", "LGB"]
.You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
\n\n\n
Example 1:
\n\nInput: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]\nOutput: ["JFK","MUC","LHR","SFO","SJC"]\n\n\n
Example 2:
\n\nInput: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]\nOutput: ["JFK","ATL","JFK","SFO","ATL","SFO"]\nExplanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.\n\n\n
\n
Constraints:
\n\n1 <= tickets.length <= 300
tickets[i].length == 2
fromi.length == 3
toi.length == 3
fromi
and toi
consist of uppercase English letters.fromi != toi
Given an integer array nums
, return true
if there exists a triple of indices (i, j, k)
such that i < j < k
and nums[i] < nums[j] < nums[k]
. If no such indices exists, return false
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: Any triplet where i < j < k is valid.\n\n\n
Example 2:
\n\n\nInput: nums = [5,4,3,2,1]\nOutput: false\nExplanation: No triplet exists.\n\n\n
Example 3:
\n\n\nInput: nums = [2,1,5,0,4,6]\nOutput: true\nExplanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
\nFollow up: Could you implement a solution that runs in
O(n)
time complexity and O(1)
space complexity?",
- "likes": 8385,
- "dislikes": 612,
- "stats": "{\"totalAccepted\": \"729.3K\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 729271, \"totalSubmissionRaw\": 1860571, \"acRate\": \"39.2%\"}",
+ "likes": 8553,
+ "dislikes": 654,
+ "stats": "{\"totalAccepted\": \"799.4K\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 799398, \"totalSubmissionRaw\": 2043193, \"acRate\": \"39.1%\"}",
"similarQuestions": "[{\"title\": \"Longest Increasing Subsequence\", \"titleSlug\": \"longest-increasing-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Count Special Quadruplets\", \"titleSlug\": \"count-special-quadruplets\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Good Triplets in an Array\", \"titleSlug\": \"count-good-triplets-in-an-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Increasing Quadruplets\", \"titleSlug\": \"count-increasing-quadruplets\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -12575,9 +12575,9 @@
"questionFrontendId": "335",
"title": "Self Crossing",
"content": "You are given an array of integers distance
.
You start at the point (0, 0)
on an X-Y plane, and you move distance[0]
meters to the north, then distance[1]
meters to the west, distance[2]
meters to the south, distance[3]
meters to the east, and so on. In other words, after each move, your direction changes counter-clockwise.
Return true
if your path crosses itself or false
if it does not.
\n
Example 1:
\n\nInput: distance = [2,1,1,2]\nOutput: true\nExplanation: The path crosses itself at the point (0, 1).\n\n\n
Example 2:
\n\nInput: distance = [1,2,3,4]\nOutput: false\nExplanation: The path does not cross itself at any point.\n\n\n
Example 3:
\n\nInput: distance = [1,1,1,2,1]\nOutput: true\nExplanation: The path crosses itself at the point (0, 0).\n\n\n
\n
Constraints:
\n\n1 <= distance.length <= 105
1 <= distance[i] <= 105
You are given a 0-indexed array of unique strings words
.
A palindrome pair is a pair of integers (i, j)
such that:
0 <= i, j < words.length
,i != j
, andwords[i] + words[j]
(the concatenation of the two strings) is a palindrome.Return an array of all the palindrome pairs of words
.
You must write an algorithm with O(sum of words[i].length)
runtime complexity.
\n
Example 1:
\n\n\nInput: words = ["abcd","dcba","lls","s","sssll"]\nOutput: [[0,1],[1,0],[3,2],[2,4]]\nExplanation: The palindromes are ["abcddcba","dcbaabcd","slls","llssssll"]\n\n\n
Example 2:
\n\n\nInput: words = ["bat","tab","cat"]\nOutput: [[0,1],[1,0]]\nExplanation: The palindromes are ["battab","tabbat"]\n\n\n
Example 3:
\n\n\nInput: words = ["a",""]\nOutput: [[0,1],[1,0]]\nExplanation: The palindromes are ["a","a"]\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 5000
0 <= words[i].length <= 300
words[i]
consists of lowercase English letters.The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root
.
Besides the root
, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root
of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
\n
Example 1:
\n\nInput: root = [3,2,3,null,3,null,1]\nOutput: 7\nExplanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\n\n\n
Example 2:
\n\nInput: root = [3,4,5,1,3,null,1]\nOutput: 9\nExplanation: Maximum amount of money the thief can rob = 4 + 5 = 9.\n\n\n
\n
Constraints:
\n\n[1, 104]
.0 <= Node.val <= 104
Given an integer n
, return an array ans
of length n + 1
such that for each i
(0 <= i <= n
), ans[i]
is the number of 1
's in the binary representation of i
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: [0,1,1]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: [0,1,1,2,1,2]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101\n\n\n
\n
Constraints:
\n\n0 <= n <= 105
\n
Follow up:
\n\nO(n log n)
. Can you do it in linear time O(n)
and possibly in a single pass?__builtin_popcount
in C++)?You are given a nested list of integers nestedList
. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.
Implement the NestedIterator
class:
NestedIterator(List<NestedInteger> nestedList)
Initializes the iterator with the nested list nestedList
.int next()
Returns the next integer in the nested list.boolean hasNext()
Returns true
if there are still some integers in the nested list and false
otherwise.Your code will be tested with the following pseudocode:
\n\n\ninitialize iterator with nestedList\nres = []\nwhile iterator.hasNext()\n append iterator.next() to the end of res\nreturn res\n\n\n
If res
matches the expected flattened list, then your code will be judged as correct.
\n
Example 1:
\n\n\nInput: nestedList = [[1,1],2,[1,1]]\nOutput: [1,1,2,1,1]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n\n\n
Example 2:
\n\n\nInput: nestedList = [1,[4,[6]]]\nOutput: [1,4,6]\nExplanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n\n\n
\n
Constraints:
\n\n1 <= nestedList.length <= 500
[-106, 106]
.Given an integer n
, return true
if it is a power of four. Otherwise, return false
.
An integer n
is a power of four, if there exists an integer x
such that n == 4x
.
\n
Example 1:
\nInput: n = 16\nOutput: true\n
Example 2:
\nInput: n = 5\nOutput: false\n
Example 3:
\nInput: n = 1\nOutput: true\n\n
\n
Constraints:
\n\n-231 <= n <= 231 - 1
\nFollow up: Could you solve it without loops/recursion?", - "likes": 4006, + "likes": 4050, "dislikes": 402, - "stats": "{\"totalAccepted\": \"759.1K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 759138, \"totalSubmissionRaw\": 1550265, \"acRate\": \"49.0%\"}", + "stats": "{\"totalAccepted\": \"806.8K\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 806812, \"totalSubmissionRaw\": 1631474, \"acRate\": \"49.5%\"}", "similarQuestions": "[{\"title\": \"Power of Two\", \"titleSlug\": \"power-of-two\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Power of Three\", \"titleSlug\": \"power-of-three\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -12885,9 +12885,9 @@ "questionFrontendId": "343", "title": "Integer Break", "content": "
Given an integer n
, break it into the sum of k
positive integers, where k >= 2
, and maximize the product of those integers.
Return the maximum product you can get.
\n\n\n
Example 1:
\n\n\nInput: n = 2\nOutput: 1\nExplanation: 2 = 1 + 1, 1 × 1 = 1.\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: 36\nExplanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.\n\n\n
\n
Constraints:
\n\n2 <= n <= 58
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
\n
Example 1:
\nInput: s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\nOutput: [\"o\",\"l\",\"l\",\"e\",\"h\"]\n
Example 2:
\nInput: s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\nOutput: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is a printable ascii character.Given a string s
, reverse only all the vowels in the string and return it.
The vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in both lower and upper cases, more than once.
\n
Example 1:
\n\nInput: s = "IceCreAm"
\n\nOutput: "AceCreIm"
\n\nExplanation:
\n\nThe vowels in s
are ['I', 'e', 'e', 'A']
. On reversing the vowels, s becomes "AceCreIm"
.
Example 2:
\n\nInput: s = "leetcode"
\n\nOutput: "leotcede"
\n\n
Constraints:
\n\n1 <= s.length <= 3 * 105
s
consist of printable ASCII characters.Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
\n
Example 1:
\nInput: nums = [1,1,1,2,2,3], k = 2\nOutput: [1,2]\n
Example 2:
\nInput: nums = [1], k = 1\nOutput: [1]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
k
is in the range [1, the number of unique elements in the array]
.\n
Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2]\n\n\n
Example 2:
\n\n\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [9,4]\nExplanation: [4,9] is also accepted.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2,2]\n\n\n
Example 2:
\n\n\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [4,9]\nExplanation: [9,4] is also accepted.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
\n
Follow up:
\n\nnums1
's size is small compared to nums2
's size? Which algorithm is better?nums2
are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?Given a data stream input of non-negative integers a1, a2, ..., an
, summarize the numbers seen so far as a list of disjoint intervals.
Implement the SummaryRanges
class:
SummaryRanges()
Initializes the object with an empty stream.void addNum(int value)
Adds the integer value
to the stream.int[][] getIntervals()
Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]
. The answer should be sorted by starti
.\n
Example 1:
\n\n\nInput\n["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"]\n[[], [1], [], [3], [], [7], [], [2], [], [6], []]\nOutput\n[null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n\nExplanation\nSummaryRanges summaryRanges = new SummaryRanges();\nsummaryRanges.addNum(1); // arr = [1]\nsummaryRanges.getIntervals(); // return [[1, 1]]\nsummaryRanges.addNum(3); // arr = [1, 3]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\nsummaryRanges.addNum(7); // arr = [1, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\nsummaryRanges.addNum(2); // arr = [1, 2, 3, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\nsummaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\nsummaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n\n\n
\n
Constraints:
\n\n0 <= value <= 104
3 * 104
calls will be made to addNum
and getIntervals
.102
calls will be made to getIntervals
.\n
Follow up: What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
\n", - "likes": 1763, - "dislikes": 366, - "stats": "{\"totalAccepted\": \"115.9K\", \"totalSubmission\": \"192.3K\", \"totalAcceptedRaw\": 115895, \"totalSubmissionRaw\": 192258, \"acRate\": \"60.3%\"}", + "likes": 1779, + "dislikes": 368, + "stats": "{\"totalAccepted\": \"119.4K\", \"totalSubmission\": \"200.7K\", \"totalAcceptedRaw\": 119436, \"totalSubmissionRaw\": 200726, \"acRate\": \"59.5%\"}", "similarQuestions": "[{\"title\": \"Summary Ranges\", \"titleSlug\": \"summary-ranges\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find Right Interval\", \"titleSlug\": \"find-right-interval\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Range Module\", \"titleSlug\": \"range-module\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Integers in Intervals\", \"titleSlug\": \"count-integers-in-intervals\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -13293,9 +13293,9 @@ "questionFrontendId": "353", "title": "Design Snake Game", "content": null, - "likes": 960, - "dislikes": 340, - "stats": "{\"totalAccepted\": \"90.8K\", \"totalSubmission\": \"232.9K\", \"totalAcceptedRaw\": 90806, \"totalSubmissionRaw\": 232885, \"acRate\": \"39.0%\"}", + "likes": 996, + "dislikes": 348, + "stats": "{\"totalAccepted\": \"98.9K\", \"totalSubmission\": \"249.2K\", \"totalAcceptedRaw\": 98867, \"totalSubmissionRaw\": 249187, \"acRate\": \"39.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -13336,9 +13336,9 @@ "questionFrontendId": "354", "title": "Russian Doll Envelopes", "content": "You are given a 2D array of integers envelopes
where envelopes[i] = [wi, hi]
represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
\n\nReturn the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
\n\nNote: You cannot rotate an envelope.
\n\n\n
Example 1:
\n\n\nInput: envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput: 3\nExplanation: The maximum number of envelopes you can Russian doll is 3
([2,3] => [5,4] => [6,7]).\n
\n\nExample 2:
\n\n\nInput: envelopes = [[1,1],[1,1],[1,1]]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= envelopes.length <= 105
envelopes[i].length == 2
1 <= wi, hi <= 105
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10
most recent tweets in the user's news feed.
Implement the Twitter
class:
Twitter()
Initializes your twitter object.void postTweet(int userId, int tweetId)
Composes a new tweet with ID tweetId
by the user userId
. Each call to this function will be made with a unique tweetId
.List<Integer> getNewsFeed(int userId)
Retrieves the 10
most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.void follow(int followerId, int followeeId)
The user with ID followerId
started following the user with ID followeeId
.void unfollow(int followerId, int followeeId)
The user with ID followerId
started unfollowing the user with ID followeeId
.\n
Example 1:
\n\n\nInput\n["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]\n[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]\nOutput\n[null, null, [5], null, null, [6, 5], null, [5]]\n\nExplanation\nTwitter twitter = new Twitter();\ntwitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).\ntwitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]\ntwitter.follow(1, 2); // User 1 follows user 2.\ntwitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).\ntwitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.\ntwitter.unfollow(1, 2); // User 1 unfollows user 2.\ntwitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.\n\n\n
\n
Constraints:
\n\n1 <= userId, followerId, followeeId <= 500
0 <= tweetId <= 104
3 * 104
calls will be made to postTweet
, getNewsFeed
, follow
, and unfollow
.Given an integer n
, return the count of all numbers with unique digits, x
, where 0 <= x < 10n
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 91\nExplanation: The answer should be the total numbers in the range of 0 ≤ x < 100, excluding 11,22,33,44,55,66,77,88,99\n\n\n
Example 2:
\n\n\nInput: n = 0\nOutput: 1\n\n\n
\n
Constraints:
\n\n0 <= n <= 8
Given an m x n
matrix matrix
and an integer k
, return the max sum of a rectangle in the matrix such that its sum is no larger than k
.
It is guaranteed that there will be a rectangle with a sum no larger than k
.
\n
Example 1:
\n\nInput: matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput: 2\nExplanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n\n\n
Example 2:
\n\n\nInput: matrix = [[2,2,-1]], k = 3\nOutput: 3\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-100 <= matrix[i][j] <= 100
-105 <= k <= 105
\n
Follow up: What if the number of rows is much larger than the number of columns?
\n", - "likes": 3493, + "likes": 3510, "dislikes": 175, - "stats": "{\"totalAccepted\": \"131K\", \"totalSubmission\": \"295K\", \"totalAcceptedRaw\": 131047, \"totalSubmissionRaw\": 295020, \"acRate\": \"44.4%\"}", + "stats": "{\"totalAccepted\": \"134K\", \"totalSubmission\": \"300K\", \"totalAcceptedRaw\": 134025, \"totalSubmissionRaw\": 300021, \"acRate\": \"44.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -13740,9 +13740,9 @@ "questionFrontendId": "364", "title": "Nested List Weight Sum II", "content": null, - "likes": 1144, - "dislikes": 468, - "stats": "{\"totalAccepted\": \"146.4K\", \"totalSubmission\": \"226.1K\", \"totalAcceptedRaw\": 146367, \"totalSubmissionRaw\": 226081, \"acRate\": \"64.7%\"}", + "likes": 1153, + "dislikes": 473, + "stats": "{\"totalAccepted\": \"153.7K\", \"totalSubmission\": \"234.4K\", \"totalAcceptedRaw\": 153708, \"totalSubmissionRaw\": 234443, \"acRate\": \"65.6%\"}", "similarQuestions": "[{\"title\": \"Nested List Weight Sum\", \"titleSlug\": \"nested-list-weight-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Array Nesting\", \"titleSlug\": \"array-nesting\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -13777,9 +13777,9 @@ "questionFrontendId": "365", "title": "Water and Jug Problem", "content": "You are given two jugs with capacities x
liters and y
liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target
using the following operations:
\n
Example 1:
\n\nInput: x = 3, y = 5, target = 4
\n\nOutput: true
\n\nExplanation:
\n\nFollow these steps to reach a total of 4 liters:
\n\nReference: The Die Hard example.
\nExample 2:
\n\nInput: x = 2, y = 6, target = 5
\n\nOutput: false
\nExample 3:
\n\nInput: x = 1, y = 2, target = 3
\n\nOutput: true
\n\nExplanation: Fill both jugs. The total amount of water in both jugs is equal to 3 now.
\n\n
Constraints:
\n\n1 <= x, y, target <= 103
Given a positive integer num, return true
if num
is a perfect square or false
otherwise.
A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.
\n\nYou must not use any built-in library function, such as sqrt
.
\n
Example 1:
\n\n\nInput: num = 16\nOutput: true\nExplanation: We return true because 4 * 4 = 16 and 4 is an integer.\n\n\n
Example 2:
\n\n\nInput: num = 14\nOutput: false\nExplanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.\n\n\n
\n
Constraints:
\n\n1 <= num <= 231 - 1
Given a set of distinct positive integers nums
, return the largest subset answer
such that every pair (answer[i], answer[j])
of elements in this subset satisfies:
answer[i] % answer[j] == 0
, oranswer[j] % answer[i] == 0
If there are multiple solutions, return any of them.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: [1,2]\nExplanation: [1,3] is also accepted.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,4,8]\nOutput: [1,2,4,8]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 109
nums
are unique.Given two integers a
and b
, return the sum of the two integers without using the operators +
and -
.
\n
Example 1:
\nInput: a = 1, b = 2\nOutput: 3\n
Example 2:
\nInput: a = 2, b = 3\nOutput: 5\n\n
\n
Constraints:
\n\n-1000 <= a, b <= 1000
Your task is to calculate ab
mod 1337
where a
is a positive integer and b
is an extremely large positive integer given in the form of an array.
\n
Example 1:
\n\n\nInput: a = 2, b = [3]\nOutput: 8\n\n\n
Example 2:
\n\n\nInput: a = 2, b = [1,0]\nOutput: 1024\n\n\n
Example 3:
\n\n\nInput: a = 1, b = [4,3,3,8,5,2]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= a <= 231 - 1
1 <= b.length <= 2000
0 <= b[i] <= 9
b
does not contain leading zeros.You are given two integer arrays nums1
and nums2
sorted in non-decreasing order and an integer k
.
Define a pair (u, v)
which consists of one element from the first array and one element from the second array.
Return the k
pairs (u1, v1), (u2, v2), ..., (uk, vk)
with the smallest sums.
\n
Example 1:
\n\n\nInput: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput: [[1,2],[1,4],[1,6]]\nExplanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput: [[1,1],[1,1]]\nExplanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
-109 <= nums1[i], nums2[i] <= 109
nums1
and nums2
both are sorted in non-decreasing order.1 <= k <= 104
k <= nums1.length * nums2.length
We are playing the Guess Game. The game is as follows:
\n\nI 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.
\n\nYou call a pre-defined API int guess(int num)
, which returns three possible results:
-1
: Your guess is higher than the number I picked (i.e. num > pick
).1
: Your guess is lower than the number I picked (i.e. num < pick
).0
: your guess is equal to the number I picked (i.e. num == pick
).Return the number that I picked.
\n\n\n
Example 1:
\n\n\nInput: n = 10, pick = 6\nOutput: 6\n\n\n
Example 2:
\n\n\nInput: n = 1, pick = 1\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: n = 2, pick = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
1 <= pick <= n
We are playing the Guessing Game. The game will work as follows:
\n\n1
and n
.x
, you will pay x
dollars. If you run out of money, you lose the game.Given a particular n
, return the minimum amount of money you need to guarantee a win regardless of what number I pick.
\n
Example 1:
\n\nInput: n = 10\nOutput: 16\nExplanation: The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n - If this is my number, your total is $0. Otherwise, you pay $7.\n - If my number is higher, the range is [8,10]. Guess 9.\n - If this is my number, your total is $7. Otherwise, you pay $9.\n - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n - If my number is lower, the range is [1,6]. Guess 3.\n - If this is my number, your total is $7. Otherwise, you pay $3.\n - If my number is higher, the range is [4,6]. Guess 5.\n - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n - If my number is lower, the range is [1,2]. Guess 1.\n - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 0\nExplanation: There is only one possible number, so you can guess 1 and not have to pay anything.\n\n\n
Example 3:
\n\n\nInput: n = 2\nOutput: 1\nExplanation: There are two possible numbers, 1 and 2.\n- Guess 1.\n - If this is my number, your total is $0. Otherwise, you pay $1.\n - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 200
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
\n\n[1, 7, 4, 9, 2, 5]
is a wiggle sequence because the differences (6, -3, 5, -7, 3)
alternate between positive and negative.[1, 4, 7, 2, 5]
and [1, 7, 4, 5, 5]
are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
\n\nGiven an integer array nums
, return the length of the longest wiggle subsequence of nums
.
\n
Example 1:
\n\n\nInput: nums = [1,7,4,9,2,5]\nOutput: 6\nExplanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n\n\n
Example 2:
\n\n\nInput: nums = [1,17,5,10,13,15,10,5,16,8]\nOutput: 7\nExplanation: There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5,6,7,8,9]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] <= 1000
\n
Follow up: Could you solve this in O(n)
time?
Given an array of distinct integers nums
and a target integer target
, return the number of possible combinations that add up to target
.
The test cases are generated so that the answer can fit in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3], target = 4\nOutput: 7\nExplanation:\nThe possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.\n\n\n
Example 2:
\n\n\nInput: nums = [9], target = 3\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= 1000
nums
are unique.1 <= target <= 1000
\n
Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
\n", - "likes": 7516, - "dislikes": 676, - "stats": "{\"totalAccepted\": \"529.6K\", \"totalSubmission\": \"971.8K\", \"totalAcceptedRaw\": 529647, \"totalSubmissionRaw\": 971805, \"acRate\": \"54.5%\"}", + "likes": 7587, + "dislikes": 686, + "stats": "{\"totalAccepted\": \"550.8K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 550831, \"totalSubmissionRaw\": 1008107, \"acRate\": \"54.6%\"}", "similarQuestions": "[{\"title\": \"Combination Sum\", \"titleSlug\": \"combination-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Ways to Express an Integer as Sum of Powers\", \"titleSlug\": \"ways-to-express-an-integer-as-sum-of-powers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -14242,9 +14242,9 @@ "questionFrontendId": "378", "title": "Kth Smallest Element in a Sorted Matrix", "content": "Given an n x n
matrix
where each of the rows and columns is sorted in ascending order, return the kth
smallest element in the matrix.
Note that it is the kth
smallest element in the sorted order, not the kth
distinct element.
You must find a solution with a memory complexity better than O(n2)
.
\n
Example 1:
\n\n\nInput: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\nOutput: 13\nExplanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13\n\n\n
Example 2:
\n\n\nInput: matrix = [[-5]], k = 1\nOutput: -5\n\n\n
\n
Constraints:
\n\nn == matrix.length == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= 109
matrix
are guaranteed to be sorted in non-decreasing order.1 <= k <= n2
\n
Follow up:
\n\nO(1)
memory complexity)?O(n)
time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.Implement the RandomizedSet
class:
RandomizedSet()
Initializes the RandomizedSet
object.bool insert(int val)
Inserts an item val
into the set if not present. Returns true
if the item was not present, false
otherwise.bool remove(int val)
Removes an item val
from the set if present. Returns true
if the item was present, false
otherwise.int getRandom()
Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.You must implement the functions of the class such that each function works in average O(1)
time complexity.
\n
Example 1:
\n\n\nInput\n["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]\n[[], [1], [2], [2], [], [1], [2], []]\nOutput\n[null, true, false, true, 2, true, false, 2]\n\nExplanation\nRandomizedSet randomizedSet = new RandomizedSet();\nrandomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\nrandomizedSet.remove(2); // Returns false as 2 does not exist in the set.\nrandomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\nrandomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\nrandomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\nrandomizedSet.insert(2); // 2 was already in the set, so return false.\nrandomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.\n\n\n
\n
Constraints:
\n\n-231 <= val <= 231 - 1
2 *
105
calls will be made to insert
, remove
, and getRandom
.getRandom
is called.RandomizedCollection
is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.
Implement the RandomizedCollection
class:
RandomizedCollection()
Initializes the empty RandomizedCollection
object.bool insert(int val)
Inserts an item val
into the multiset, even if the item is already present. Returns true
if the item is not present, false
otherwise.bool remove(int val)
Removes an item val
from the multiset if present. Returns true
if the item is present, false
otherwise. Note that if val
has multiple occurrences in the multiset, we only remove one of them.int getRandom()
Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains.You must implement the functions of the class such that each function works on average O(1)
time complexity.
Note: The test cases are generated such that getRandom
will only be called if there is at least one item in the RandomizedCollection
.
\n
Example 1:
\n\n\nInput\n["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"]\n[[], [1], [1], [2], [], [1], []]\nOutput\n[null, true, false, true, 2, true, 1]\n\nExplanation\nRandomizedCollection randomizedCollection = new RandomizedCollection();\nrandomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\nrandomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\nrandomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\nrandomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\nrandomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\nrandomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.\n\n\n
\n
Constraints:
\n\n-231 <= val <= 231 - 1
2 * 105
calls in total will be made to insert
, remove
, and getRandom
.getRandom
is called.Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
\n\nImplement the Solution
class:
Solution(ListNode head)
Initializes the object with the head of the singly-linked list head
.int getRandom()
Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.\n
Example 1:
\n\nInput\n["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 3, 2, 2, 3]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n\n\n
\n
Constraints:
\n\n[1, 104]
.-104 <= Node.val <= 104
104
calls will be made to getRandom
.\n
Follow up:
\n\nGiven two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
\n
Example 1:
\nInput: ransomNote = \"a\", magazine = \"b\"\nOutput: false\n
Example 2:
\nInput: ransomNote = \"aa\", magazine = \"ab\"\nOutput: false\n
Example 3:
\nInput: ransomNote = \"aa\", magazine = \"aab\"\nOutput: true\n\n
\n
Constraints:
\n\n1 <= ransomNote.length, magazine.length <= 105
ransomNote
and magazine
consist of lowercase English letters.Given an integer array nums
, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.
Implement the Solution
class:
Solution(int[] nums)
Initializes the object with the integer array nums
.int[] reset()
Resets the array to its original configuration and returns it.int[] shuffle()
Returns a random shuffling of the array.\n
Example 1:
\n\n\nInput\n["Solution", "shuffle", "reset", "shuffle"]\n[[[1, 2, 3]], [], [], []]\nOutput\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle(); // Shuffle the array [1,2,3] and return its result.\n // Any permutation of [1,2,3] must be equally likely to be returned.\n // Example: return [3, 1, 2]\nsolution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50
-106 <= nums[i] <= 106
nums
are unique.104
calls in total will be made to reset
and shuffle
.Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger
.
Each element is either an integer or a list whose elements may also be integers or other lists.
\n\n\n
Example 1:
\n\n\nInput: s = "324"\nOutput: 324\nExplanation: You should return a NestedInteger object which contains a single integer 324.\n\n\n
Example 2:
\n\n\nInput: s = "[123,[456,[789]]]"\nOutput: [123,[456,[789]]]\nExplanation: Return a NestedInteger object containing a nested list with 2 elements:\n1. An integer containing value 123.\n2. A nested list containing two elements:\n i. An integer containing value 456.\n ii. A nested list with one element:\n a. An integer containing value 789\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 104
s
consists of digits, square brackets "[]"
, negative sign '-'
, and commas ','
.s
is the serialization of valid NestedInteger
.[-106, 106]
.Given an integer n
, return all the numbers in the range [1, n]
sorted in lexicographical order.
You must write an algorithm that runs in O(n)
time and uses O(1)
extra space.
\n
Example 1:
\nInput: n = 13\nOutput: [1,10,11,12,13,2,3,4,5,6,7,8,9]\n
Example 2:
\nInput: n = 2\nOutput: [1,2]\n\n
\n
Constraints:
\n\n1 <= n <= 5 * 104
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
\n
Example 1:
\n\nInput: s = "leetcode"
\n\nOutput: 0
\n\nExplanation:
\n\nThe character 'l'
at index 0 is the first character that does not occur at any other index.
Example 2:
\n\nInput: s = "loveleetcode"
\n\nOutput: 2
\nExample 3:
\n\nInput: s = "aabb"
\n\nOutput: -1
\n\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only lowercase English letters.Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:
\n\nHere, we have dir
as the only directory in the root. dir
contains two subdirectories, subdir1
and subdir2
. subdir1
contains a file file1.ext
and subdirectory subsubdir1
. subdir2
contains a subdirectory subsubdir2
, which contains a file file2.ext
.
In text form, it looks like this (with \u27f6 representing the tab character):
\n\n\ndir\n\u27f6 subdir1\n\u27f6 \u27f6 file1.ext\n\u27f6 \u27f6 subsubdir1\n\u27f6 subdir2\n\u27f6 \u27f6 subsubdir2\n\u27f6 \u27f6 \u27f6 file2.ext\n\n\n
If we were to write this representation in code, it will look like this: "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext"
. Note that the '\\n'
and '\\t'
are the new-line and tab characters.
Every file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s
. Using the above example, the absolute path to file2.ext
is "dir/subdir2/subsubdir2/file2.ext"
. Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension
, where name
and extension
consist of letters, digits, and/or spaces.
Given a string input
representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0
.
Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.
\n\n\n
Example 1:
\n\nInput: input = "dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext"\nOutput: 20\nExplanation: We have only one file, and the absolute path is "dir/subdir2/file.ext" of length 20.\n\n\n
Example 2:
\n\nInput: input = "dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext"\nOutput: 32\nExplanation: We have two files:\n"dir/subdir1/file1.ext" of length 21\n"dir/subdir2/subsubdir2/file2.ext" of length 32.\nWe return 32 since it is the longest absolute path to a file.\n\n\n
Example 3:
\n\n\nInput: input = "a"\nOutput: 0\nExplanation: We do not have any files, just a single directory named "a".\n\n\n
\n
Constraints:
\n\n1 <= input.length <= 104
input
may contain lowercase or uppercase English letters, a new line character '\\n'
, a tab character '\\t'
, a dot '.'
, a space ' '
, and digits.You are given two strings s
and t
.
String t
is generated by random shuffling string s
and then add one more letter at a random position.
Return the letter that was added to t
.
\n
Example 1:
\n\n\nInput: s = "abcd", t = "abcde"\nOutput: "e"\nExplanation: 'e' is the letter that was added.\n\n\n
Example 2:
\n\n\nInput: s = "", t = "y"\nOutput: "y"\n\n\n
\n
Constraints:
\n\n0 <= s.length <= 1000
t.length == s.length + 1
s
and t
consist of lowercase English letters.You have a list arr
of all integers in the range [1, n]
sorted in a strictly increasing order. Apply the following algorithm on arr
:
Given the integer n
, return the last number that remains in arr
.
\n
Example 1:
\n\n\nInput: n = 9\nOutput: 6\nExplanation:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr = [2, 4, 6, 8]\narr = [2, 6]\narr = [6]\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
Given an array rectangles
where rectangles[i] = [xi, yi, ai, bi]
represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi)
and the top-right point of it is (ai, bi)
.
Return true
if all the rectangles together form an exact cover of a rectangular region.
\n
Example 1:
\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\nOutput: true\nExplanation: All 5 rectangles together form an exact cover of a rectangular region.\n\n\n
Example 2:
\n\nInput: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\nOutput: false\nExplanation: Because there is a gap between the two rectangular regions.\n\n\n
Example 3:
\n\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\nOutput: false\nExplanation: Because two of the rectangles overlap with each other.\n\n\n
\n
Constraints:
\n\n1 <= rectangles.length <= 2 * 104
rectangles[i].length == 4
-105 <= xi < ai <= 105
-105 <= yi < bi <= 105
Given two strings s
and t
, return true
if s
is a subsequence of t
, or false
otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
\n
Example 1:
\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\n
Example 2:
\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n\n
\n
Constraints:
\n\n0 <= s.length <= 100
0 <= t.length <= 104
s
and t
consist only of lowercase English letters.\nFollow up: Suppose there are lots of incoming
s
, say s1, s2, ..., sk
where k >= 109
, and you want to check one by one to see if t
has its subsequence. In this scenario, how would you change your code?",
- "likes": 10049,
- "dislikes": 569,
- "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"3.9M\", \"totalAcceptedRaw\": 1884824, \"totalSubmissionRaw\": 3911998, \"acRate\": \"48.2%\"}",
+ "likes": 10283,
+ "dislikes": 580,
+ "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"4.3M\", \"totalAcceptedRaw\": 2078645, \"totalSubmissionRaw\": 4296866, \"acRate\": \"48.4%\"}",
"similarQuestions": "[{\"title\": \"Number of Matching Subsequences\", \"titleSlug\": \"number-of-matching-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Way to Form String\", \"titleSlug\": \"shortest-way-to-form-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Append Characters to String to Make Subsequence\", \"titleSlug\": \"append-characters-to-string-to-make-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Make String a Subsequence Using Cyclic Increments\", \"titleSlug\": \"make-string-a-subsequence-using-cyclic-increments\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -14814,9 +14814,9 @@
"questionFrontendId": "393",
"title": "UTF-8 Validation",
"content": "Given an integer array data
representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
\n\n0
, followed by its Unicode code.n
bits are all one's, the n + 1
bit is 0
, followed by n - 1
bytes with the most significant 2
bits being 10
.This is how the UTF-8 encoding would work:
\n\n\n Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\n\n
x
denotes a bit in the binary form of a byte that may be either 0
or 1
.
Note: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
\n\n\n
Example 1:
\n\n\nInput: data = [197,130,1]\nOutput: true\nExplanation: data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n\n\n
Example 2:
\n\n\nInput: data = [235,140,4]\nOutput: false\nExplanation: data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.\n\n\n
\n
Constraints:
\n\n1 <= data.length <= 2 * 104
0 <= data[i] <= 255
Given an encoded string, return its decoded string.
\n\nThe encoding rule is: k[encoded_string]
, where the encoded_string
inside the square brackets is being repeated exactly k
times. Note that k
is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k
. For example, there will not be input like 3a
or 2[4]
.
The test cases are generated so that the length of the output will never exceed 105
.
\n
Example 1:
\n\n\nInput: s = "3[a]2[bc]"\nOutput: "aaabcbc"\n\n\n
Example 2:
\n\n\nInput: s = "3[a2[c]]"\nOutput: "accaccacc"\n\n\n
Example 3:
\n\n\nInput: s = "2[abc]3[cd]ef"\nOutput: "abcabccdcdcdef"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 30
s
consists of lowercase English letters, digits, and square brackets '[]'
.s
is guaranteed to be a valid input.s
are in the range [1, 300]
.Given a string s
and an integer k
, return the length of the longest substring of s
such that the frequency of each character in this substring is greater than or equal to k
.
if no such substring exists, return 0.
\n\n\n
Example 1:
\n\n\nInput: s = "aaabb", k = 3\nOutput: 3\nExplanation: The longest substring is "aaa", as 'a' is repeated 3 times.\n\n\n
Example 2:
\n\n\nInput: s = "ababbc", k = 2\nOutput: 5\nExplanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of only lowercase English letters.1 <= k <= 105
You are given an integer array nums
of length n
.
Assume arrk
to be an array obtained by rotating nums
by k
positions clock-wise. We define the rotation function F
on nums
as follow:
F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].
Return the maximum value of F(0), F(1), ..., F(n-1)
.
The test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,3,2,6]\nOutput: 26\nExplanation:\nF(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n\n\n
Example 2:
\n\n\nInput: nums = [100]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
-100 <= nums[i] <= 100
Given a positive integer n
, you can apply one of the following operations:
n
is even, replace n
with n / 2
.n
is odd, replace n
with either n + 1
or n - 1
.Return the minimum number of operations needed for n
to become 1
.
\n
Example 1:
\n\n\nInput: n = 8\nOutput: 3\nExplanation: 8 -> 4 -> 2 -> 1\n\n\n
Example 2:
\n\n\nInput: n = 7\nOutput: 4\nExplanation: 7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
Given an integer array nums
with possible duplicates, randomly output the index of a given target
number. You can assume that the given target number must exist in the array.
Implement the Solution
class:
Solution(int[] nums)
Initializes the object with the array nums
.int pick(int target)
Picks a random index i
from nums
where nums[i] == target
. If there are multiple valid i's, then each index should have an equal probability of returning.\n
Example 1:
\n\n\nInput\n["Solution", "pick", "pick", "pick"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\nOutput\n[null, 4, 0, 2]\n\nExplanation\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
target
is an integer from nums
.104
calls will be made to pick
.You are given an array of variable pairs equations
and an array of real numbers values
, where equations[i] = [Ai, Bi]
and values[i]
represent the equation Ai / Bi = values[i]
. Each Ai
or Bi
is a string that represents a single variable.
You are also given some queries
, where queries[j] = [Cj, Dj]
represents the jth
query where you must find the answer for Cj / Dj = ?
.
Return the answers to all queries. If a single answer cannot be determined, return -1.0
.
Note: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
\n\nNote: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.
\n\n\n
Example 1:
\n\n\nInput: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]\nOutput: [6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation: \nGiven: a / b = 2.0, b / c = 3.0\nqueries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? \nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnote: x is undefined => -1.0\n\n
Example 2:
\n\n\nInput: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]\nOutput: [3.75000,0.40000,5.00000,0.20000]\n\n\n
Example 3:
\n\n\nInput: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]\nOutput: [0.50000,2.00000,-1.00000,-1.00000]\n\n\n
\n
Constraints:
\n\n1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj
consist of lower case English letters and digits.Given an integer n
, return the nth
digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]
.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 3\n\n\n
Example 2:
\n\n\nInput: n = 11\nOutput: 0\nExplanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.
\n\n"4:51"
.Given an integer turnedOn
which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.
The hour must not contain a leading zero.
\n\n"01:00"
is not valid. It should be "1:00"
.The minute must consist of two digits and may contain a leading zero.
\n\n"10:2"
is not valid. It should be "10:02"
.\n
Example 1:
\nInput: turnedOn = 1\nOutput: [\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]\n
Example 2:
\nInput: turnedOn = 9\nOutput: []\n\n
\n
Constraints:
\n\n0 <= turnedOn <= 10
Given string num representing a non-negative integer num
, and an integer k
, return the smallest possible integer after removing k
digits from num
.
\n
Example 1:
\n\n\nInput: num = "1432219", k = 3\nOutput: "1219"\nExplanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n\n\n
Example 2:
\n\n\nInput: num = "10200", k = 1\nOutput: "200"\nExplanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n\n\n
Example 3:
\n\n\nInput: num = "10", k = 2\nOutput: "0"\nExplanation: Remove all the digits from the number and it is left with nothing which is 0.\n\n\n
\n
Constraints:
\n\n1 <= k <= num.length <= 105
num
consists of only digits.num
does not have any leading zeros except for the zero itself.A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.
\n\nGiven a list of stones
positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1
unit.
If the frog's last jump was k
units, its next jump must be either k - 1
, k
, or k + 1
units. The frog can only jump in the forward direction.
\n
Example 1:
\n\n\nInput: stones = [0,1,3,5,6,8,12,17]\nOutput: true\nExplanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n\n\n
Example 2:
\n\n\nInput: stones = [0,1,2,3,4,8,9,11]\nOutput: false\nExplanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n\n\n
\n
Constraints:
\n\n2 <= stones.length <= 2000
0 <= stones[i] <= 231 - 1
stones[0] == 0
stones
is sorted in a strictly increasing order.Given the root
of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
\n\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: 24\nExplanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n[1, 1000]
.-1000 <= Node.val <= 1000
Given a 32-bit integer num
, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
\n\nNote: You are not allowed to use any built-in library method to directly solve this problem.
\n\n\n
Example 1:
\nInput: num = 26\nOutput: \"1a\"\n
Example 2:
\nInput: num = -1\nOutput: \"ffffffff\"\n\n
\n
Constraints:
\n\n-231 <= num <= 231 - 1
You are given an array of people, people
, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith
person of height hi
with exactly ki
other people in front who have a height greater than or equal to hi
.
Reconstruct and return the queue that is represented by the input array people
. The returned queue should be formatted as an array queue
, where queue[j] = [hj, kj]
is the attributes of the jth
person in the queue (queue[0]
is the person at the front of the queue).
\n
Example 1:
\n\n\nInput: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:\nPerson 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\n\n\n
Example 2:
\n\n\nInput: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n\n\n
\n
Constraints:
\n\n1 <= people.length <= 2000
0 <= hi <= 106
0 <= ki < people.length
Given an m x n
integer matrix heightMap
representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
\n
Example 1:
\n\nInput: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\nOutput: 4\nExplanation: After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.\n\n\n
Example 2:
\n\nInput: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\nOutput: 10\n\n\n
\n
Constraints:
\n\nm == heightMap.length
n == heightMap[i].length
1 <= m, n <= 200
0 <= heightMap[i][j] <= 2 * 104
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.
\n
Example 1:
\n\n\nInput: s = "abccccdd"\nOutput: 7\nExplanation: One longest palindrome that can be built is "dccaccd", whose length is 7.\n\n\n
Example 2:
\n\n\nInput: s = "a"\nOutput: 1\nExplanation: The longest palindrome that can be built is "a", whose length is 1.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2000
s
consists of lowercase and/or uppercase English letters only.Given an integer array nums
and an integer k
, split nums
into k
non-empty subarrays such that the largest sum of any subarray is minimized.
Return the minimized largest sum of the split.
\n\nA subarray is a contiguous part of the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [7,2,5,10,8], k = 2\nOutput: 18\nExplanation: There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5], k = 2\nOutput: 9\nExplanation: There are four ways to split nums into two subarrays.\nThe best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] <= 106
1 <= k <= min(50, nums.length)
Given an integer n
, return a string array answer
(1-indexed) where:
answer[i] == "FizzBuzz"
if i
is divisible by 3
and 5
.answer[i] == "Fizz"
if i
is divisible by 3
.answer[i] == "Buzz"
if i
is divisible by 5
.answer[i] == i
(as a string) if none of the above conditions are true.\n
Example 1:
\nInput: n = 3\nOutput: [\"1\",\"2\",\"Fizz\"]\n
Example 2:
\nInput: n = 5\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\n
Example 3:
\nInput: n = 15\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n\n
\n
Constraints:
\n\n1 <= n <= 104
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
\n\n[1,3,5,7,9]
, [7,7,7,7]
, and [3,-1,-5,-9]
are arithmetic sequences.Given an integer array nums
, return the number of arithmetic subarrays of nums
.
A subarray is a contiguous subsequence of the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 3\nExplanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
Given an integer array nums
, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
\n
Example 1:
\n\n\nInput: nums = [3,2,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2]\nOutput: 2\nExplanation:\nThe first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.\n\n\n
Example 3:
\n\n\nInput: nums = [2,2,3,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
\nFollow up: Can you find an
O(n)
solution?",
- "likes": 3174,
- "dislikes": 3295,
- "stats": "{\"totalAccepted\": \"635.8K\", \"totalSubmission\": \"1.7M\", \"totalAcceptedRaw\": 635844, \"totalSubmissionRaw\": 1743151, \"acRate\": \"36.5%\"}",
+ "likes": 3260,
+ "dislikes": 3362,
+ "stats": "{\"totalAccepted\": \"685.2K\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 685235, \"totalSubmissionRaw\": 1842898, \"acRate\": \"37.2%\"}",
"similarQuestions": "[{\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Neither Minimum nor Maximum\", \"titleSlug\": \"neither-minimum-nor-maximum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -15637,9 +15637,9 @@
"questionFrontendId": "415",
"title": "Add Strings",
"content": "Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
You must solve the problem without using any built-in library for handling large integers (such as BigInteger
). You must also not convert the inputs to integers directly.
\n
Example 1:
\n\n\nInput: num1 = "11", num2 = "123"\nOutput: "134"\n\n\n
Example 2:
\n\n\nInput: num1 = "456", num2 = "77"\nOutput: "533"\n\n\n
Example 3:
\n\n\nInput: num1 = "0", num2 = "0"\nOutput: "0"\n\n\n
\n
Constraints:
\n\n1 <= num1.length, num2.length <= 104
num1
and num2
consist of only digits.num1
and num2
don't have any leading zeros except for the zero itself.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.
\n
Example 1:
\n\n\nInput: nums = [1,5,11,5]\nOutput: true\nExplanation: The array can be partitioned as [1, 5, 5] and [11].\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,5]\nOutput: false\nExplanation: The array cannot be partitioned into equal sum subsets.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= 100
There is an m x n
rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.
The island is partitioned into a grid of square cells. You are given an m x n
integer matrix heights
where heights[r][c]
represents the height above sea level of the cell at coordinate (r, c)
.
The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.
\n\nReturn a 2D list of grid coordinates result
where result[i] = [ri, ci]
denotes that rain water can flow from cell (ri, ci)
to both the Pacific and Atlantic oceans.
\n
Example 1:
\n\nInput: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\nOutput: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\nExplanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -> Pacific Ocean \n [0,4] -> Atlantic Ocean\n[1,3]: [1,3] -> [0,3] -> Pacific Ocean \n [1,3] -> [1,4] -> Atlantic Ocean\n[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean \n [1,4] -> Atlantic Ocean\n[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean \n [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean\n[3,0]: [3,0] -> Pacific Ocean \n [3,0] -> [4,0] -> Atlantic Ocean\n[3,1]: [3,1] -> [3,0] -> Pacific Ocean \n [3,1] -> [4,1] -> Atlantic Ocean\n[4,0]: [4,0] -> Pacific Ocean \n [4,0] -> Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.\n\n\n
Example 2:
\n\n\nInput: heights = [[1]]\nOutput: [[0,0]]\nExplanation: The water can flow from the only cell to the Pacific and Atlantic oceans.\n\n\n
\n
Constraints:
\n\nm == heights.length
n == heights[r].length
1 <= m, n <= 200
0 <= heights[r][c] <= 105
Given an m x n
matrix board
where each cell is a battleship 'X'
or empty '.'
, return the number of the battleships on board
.
Battleships can only be placed horizontally or vertically on board
. In other words, they can only be made of the shape 1 x k
(1
row, k
columns) or k x 1
(k
rows, 1
column), where k
can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).
\n
Example 1:
\n\nInput: board = [["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: board = [["."]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
is either '.'
or 'X'
.\n
Follow up: Could you do it in one-pass, using only O(1)
extra memory and without modifying the values board
?
A password is considered strong if the below conditions are all met:
\n\n6
characters and at most 20
characters."Baaabb0"
is weak, but "Baaba0"
is strong).Given a string password
, return the minimum number of steps required to make password
strong. if password
is already strong, return 0
.
In one step, you can:
\n\npassword
,password
, orpassword
with another character.\n
Example 1:
\nInput: password = \"a\"\nOutput: 5\n
Example 2:
\nInput: password = \"aA1\"\nOutput: 3\n
Example 3:
\nInput: password = \"1337C0d3\"\nOutput: 0\n\n
\n
Constraints:
\n\n1 <= password.length <= 50
password
consists of letters, digits, dot '.'
or exclamation mark '!'
.Given an integer array nums
, return the maximum result of nums[i] XOR nums[j]
, where 0 <= i <= j < n
.
\n
Example 1:
\n\n\nInput: nums = [3,10,5,25,2,8]\nOutput: 28\nExplanation: The maximum result is 5 XOR 25 = 28.\n\n\n
Example 2:
\n\n\nInput: nums = [14,70,53,83,49,91,36,80,92,51,66,70]\nOutput: 127\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 105
0 <= nums[i] <= 231 - 1
Given a string s
containing an out-of-order English representation of digits 0-9
, return the digits in ascending order.
\n
Example 1:
\nInput: s = \"owoztneoer\"\nOutput: \"012\"\n
Example 2:
\nInput: s = \"fviefuro\"\nOutput: \"45\"\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is one of the characters ["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]
.s
is guaranteed to be valid.You are given a string s
and an integer k
. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k
times.
Return the length of the longest substring containing the same letter you can get after performing the above operations.
\n\n\n
Example 1:
\n\n\nInput: s = "ABAB", k = 2\nOutput: 4\nExplanation: Replace the two 'A's with two 'B's or vice versa.\n\n\n
Example 2:
\n\n\nInput: s = "AABABBA", k = 1\nOutput: 4\nExplanation: Replace the one 'A' in the middle with 'B' and form "AABBBBA".\nThe substring "BBBB" has the longest repeating letters, which is 4.\nThere may exists other ways to achieve this answer too.\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only uppercase English letters.0 <= k <= s.length
Given a n * n
matrix grid
of 0's
and 1's
only. We want to represent grid
with a Quad-Tree.
Return the root of the Quad-Tree representing grid
.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
\n\nval
: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val
to True or False when isLeaf
is False, and both are accepted in the answer.isLeaf
: True if the node is a leaf node on the tree or False if the node has four children.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}\n\n
We can construct a Quad-Tree from a two-dimensional area using the following steps:
\n\n1's
or all 0's
) set isLeaf
True and set val
to the value of the grid and set the four children to Null and stop.isLeaf
to False and set val
to any value and divide the current grid into four sub-grids as shown in the photo.If you want to know more about the Quad-Tree, you can refer to the wiki.
\n\nQuad-Tree format:
\n\nYou don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null
signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]
.
If the value of isLeaf
or val
is True we represent it as 1 in the list [isLeaf, val]
and if the value of isLeaf
or val
is False we represent it as 0.
\n
Example 1:
\n\nInput: grid = [[0,1],[1,0]]\nOutput: [[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation: The explanation of this example is shown below:\nNotice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.\n\n\n\n
Example 2:
\n\n\nInput: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nOutput: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation: All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:\n\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
n == 2x
where 0 <= x <= 6
Given an n-ary tree, return the level order traversal of its nodes' values.
\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
\n\n\n
Example 1:
\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [[1],[3,2,4],[5,6]]\n\n\n
Example 2:
\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n\n\n
\n
Constraints:
\n\n1000
[0, 104]
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.
\n\nGiven the head
of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr
be a node with a child list. The nodes in the child list should appear after curr
and before curr.next
in the flattened list.
Return the head
of the flattened list. The nodes in the list must have all of their child pointers set to null
.
\n
Example 1:
\n\nInput: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput: [1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n\n\n
Example 2:
\n\nInput: head = [1,2,null,3]\nOutput: [1,3,2]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\n\n\n\n
Example 3:
\n\n\nInput: head = []\nOutput: []\nExplanation: There could be empty list in the input.\n\n\n
\n
Constraints:
\n\n1000
.1 <= Node.val <= 105
\n
How the multilevel linked list is represented in test cases:
\n\nWe use the multilevel linked list from Example 1 above:
\n\n\n 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL\n\n
The serialization of each level is as follows:
\n\n\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\n\n\n
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\n\n\n[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]\n\n\n
Merging the serialization of each level and removing trailing nulls we obtain:
\n\n\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n\n", - "likes": 5165, - "dislikes": 333, - "stats": "{\"totalAccepted\": \"359.1K\", \"totalSubmission\": \"590.2K\", \"totalAcceptedRaw\": 359129, \"totalSubmissionRaw\": 590155, \"acRate\": \"60.9%\"}", + "likes": 5237, + "dislikes": 339, + "stats": "{\"totalAccepted\": \"377.2K\", \"totalSubmission\": \"615.4K\", \"totalAcceptedRaw\": 377239, \"totalSubmissionRaw\": 615434, \"acRate\": \"61.3%\"}", "similarQuestions": "[{\"title\": \"Flatten Binary Tree to Linked List\", \"titleSlug\": \"flatten-binary-tree-to-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Correct a Binary Tree\", \"titleSlug\": \"correct-a-binary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -16238,9 +16238,9 @@ "questionFrontendId": "431", "title": "Encode N-ary Tree to Binary Tree", "content": null, - "likes": 526, - "dislikes": 29, - "stats": "{\"totalAccepted\": \"23K\", \"totalSubmission\": \"28.8K\", \"totalAcceptedRaw\": 22991, \"totalSubmissionRaw\": 28766, \"acRate\": \"79.9%\"}", + "likes": 530, + "dislikes": 30, + "stats": "{\"totalAccepted\": \"23.7K\", \"totalSubmission\": \"29.6K\", \"totalAcceptedRaw\": 23722, \"totalSubmissionRaw\": 29604, \"acRate\": \"80.1%\"}", "similarQuestions": "[{\"title\": \"Serialize and Deserialize N-ary Tree\", \"titleSlug\": \"serialize-and-deserialize-n-ary-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -16281,9 +16281,9 @@ "questionFrontendId": "432", "title": "All O`one Data Structure", "content": "
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.
\n\nImplement the AllOne
class:
AllOne()
Initializes the object of the data structure.inc(String key)
Increments the count of the string key
by 1
. If key
does not exist in the data structure, insert it with count 1
.dec(String key)
Decrements the count of the string key
by 1
. If the count of key
is 0
after the decrement, remove it from the data structure. It is guaranteed that key
exists in the data structure before the decrement.getMaxKey()
Returns one of the keys with the maximal count. If no element exists, return an empty string ""
.getMinKey()
Returns one of the keys with the minimum count. If no element exists, return an empty string ""
.Note that each function must run in O(1)
average time complexity.
\n
Example 1:
\n\n\nInput\n["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"]\n[[], ["hello"], ["hello"], [], [], ["leet"], [], []]\nOutput\n[null, null, null, "hello", "hello", null, "hello", "leet"]\n\nExplanation\nAllOne allOne = new AllOne();\nallOne.inc("hello");\nallOne.inc("hello");\nallOne.getMaxKey(); // return "hello"\nallOne.getMinKey(); // return "hello"\nallOne.inc("leet");\nallOne.getMaxKey(); // return "hello"\nallOne.getMinKey(); // return "leet"\n\n\n
\n
Constraints:
\n\n1 <= key.length <= 10
key
consists of lowercase English letters.dec
, key
is existing in the data structure.5 * 104
calls will be made to inc
, dec
, getMaxKey
, and getMinKey
.A gene string can be represented by an 8-character long string, with choices from 'A'
, 'C'
, 'G'
, and 'T'
.
Suppose we need to investigate a mutation from a gene string startGene
to a gene string endGene
where one mutation is defined as one single character changed in the gene string.
"AACCGGTT" --> "AACCGGTA"
is one mutation.There is also a gene bank bank
that records all the valid gene mutations. A gene must be in bank
to make it a valid gene string.
Given the two gene strings startGene
and endGene
and the gene bank bank
, return the minimum number of mutations needed to mutate from startGene
to endGene
. If there is no such a mutation, return -1
.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
\n\n\n
Example 1:
\n\n\nInput: startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"]\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]\nOutput: 2\n\n\n
\n
Constraints:
\n\n0 <= bank.length <= 10
startGene.length == endGene.length == bank[i].length == 8
startGene
, endGene
, and bank[i]
consist of only the characters ['A', 'C', 'G', 'T']
.Given a string s
, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
\n\n\n
Example 1:
\n\n\nInput: s = "Hello, my name is John"\nOutput: 5\nExplanation: The five segments are ["Hello,", "my", "name", "is", "John"]\n\n\n
Example 2:
\n\n\nInput: s = "Hello"\nOutput: 1\n\n\n
\n
Constraints:
\n\n0 <= s.length <= 300
s
consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:"
.s
is ' '
.Given an array of intervals intervals
where intervals[i] = [starti, endi]
, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note that intervals which only touch at a point are non-overlapping. For example, [1, 2]
and [2, 3]
are non-overlapping.
\n
Example 1:
\n\n\nInput: intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput: 1\nExplanation: [1,3] can be removed and the rest of the intervals are non-overlapping.\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,2],[1,2],[1,2]]\nOutput: 2\nExplanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.\n\n\n
Example 3:
\n\n\nInput: intervals = [[1,2],[2,3]]\nOutput: 0\nExplanation: You don't need to remove any of the intervals since they're already non-overlapping.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 105
intervals[i].length == 2
-5 * 104 <= starti < endi <= 5 * 104
You are given an array of intervals
, where intervals[i] = [starti, endi]
and each starti
is unique.
The right interval for an interval i
is an interval j
such that startj >= endi
and startj
is minimized. Note that i
may equal j
.
Return an array of right interval indices for each interval i
. If no right interval exists for interval i
, then put -1
at index i
.
\n
Example 1:
\n\n\nInput: intervals = [[1,2]]\nOutput: [-1]\nExplanation: There is only one interval in the collection, so it outputs -1.\n\n\n
Example 2:
\n\n\nInput: intervals = [[3,4],[2,3],[1,2]]\nOutput: [-1,0,1]\nExplanation: There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.\n\n\n
Example 3:
\n\n\nInput: intervals = [[1,4],[2,3],[3,4]]\nOutput: [-1,2,-1]\nExplanation: There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 2 * 104
intervals[i].length == 2
-106 <= starti <= endi <= 106
Given the root
of a binary tree and an integer targetSum
, return the number of paths where the sum of the values along the path equals targetSum
.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
\n\n\n
Example 1:
\n\nInput: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput: 3\nExplanation: The paths that sum to 8 are shown.\n\n\n
Example 2:
\n\n\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: 3\n\n\n
\n
Constraints:
\n\n[0, 1000]
.-109 <= Node.val <= 109
-1000 <= targetSum <= 1000
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.
\n
Example 1:
\n\n\nInput: s = "cbaebabacd", p = "abc"\nOutput: [0,6]\nExplanation:\nThe substring with start index = 0 is "cba", which is an anagram of "abc".\nThe substring with start index = 6 is "bac", which is an anagram of "abc".\n\n\n
Example 2:
\n\n\nInput: s = "abab", p = "ab"\nOutput: [0,1,2]\nExplanation:\nThe substring with start index = 0 is "ab", which is an anagram of "ab".\nThe substring with start index = 1 is "ba", which is an anagram of "ab".\nThe substring with start index = 2 is "ab", which is an anagram of "ab".\n\n\n
\n
Constraints:
\n\n1 <= s.length, p.length <= 3 * 104
s
and p
consist of lowercase English letters.Given two integers n
and k
, return the kth
lexicographically smallest integer in the range [1, n]
.
\n
Example 1:
\n\n\nInput: n = 13, k = 2\nOutput: 10\nExplanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\n\n\n
Example 2:
\n\n\nInput: n = 1, k = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 109
You have n
coins and you want to build a staircase with these coins. The staircase consists of k
rows where the ith
row has exactly i
coins. The last row of the staircase may be incomplete.
Given the integer n
, return the number of complete rows of the staircase you will build.
\n
Example 1:
\n\nInput: n = 5\nOutput: 2\nExplanation: Because the 3rd row is incomplete, we return 2.\n\n\n
Example 2:
\n\nInput: n = 8\nOutput: 3\nExplanation: Because the 4th row is incomplete, we return 3.\n\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
Given an integer array nums
of length n
where all the integers of nums
are in the range [1, n]
and each integer appears at most twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n)
time and uses only constant auxiliary space, excluding the space needed to store the output
\n
Example 1:
\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [2,3]\n
Example 2:
\nInput: nums = [1,1,2]\nOutput: [1]\n
Example 3:
\nInput: nums = [1]\nOutput: []\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
1 <= nums[i] <= n
nums
appears once or twice.Given an array of characters chars
, compress it using the following algorithm:
Begin with an empty string s
. For each group of consecutive repeating characters in chars
:
1
, append the character to s
.The compressed string s
should not be returned separately, but instead, be stored in the input character array chars
. Note that group lengths that are 10
or longer will be split into multiple characters in chars
.
After you are done modifying the input array, return the new length of the array.
\n\nYou must write an algorithm that uses only constant extra space.
\n\n\n
Example 1:
\n\n\nInput: chars = ["a","a","b","b","c","c","c"]\nOutput: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]\nExplanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".\n\n\n
Example 2:
\n\n\nInput: chars = ["a"]\nOutput: Return 1, and the first character of the input array should be: ["a"]\nExplanation: The only group is "a", which remains uncompressed since it's a single character.\n\n\n
Example 3:
\n\n\nInput: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]\nOutput: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].\nExplanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".\n\n
\n
Constraints:
\n\n1 <= chars.length <= 2000
chars[i]
is a lowercase English letter, uppercase English letter, digit, or symbol.You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
\n\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.
\n\n\n
Example 1:
\n\nInput: l1 = [7,2,4,3], l2 = [5,6,4]\nOutput: [7,8,0,7]\n\n\n
Example 2:
\n\n\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [8,0,7]\n\n\n
Example 3:
\n\n\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n[1, 100]
.0 <= Node.val <= 9
\n
Follow up: Could you solve it without reversing the input lists?
\n", - "likes": 5982, - "dislikes": 295, - "stats": "{\"totalAccepted\": \"511.2K\", \"totalSubmission\": \"829.6K\", \"totalAcceptedRaw\": 511232, \"totalSubmissionRaw\": 829565, \"acRate\": \"61.6%\"}", + "likes": 6040, + "dislikes": 297, + "stats": "{\"totalAccepted\": \"527.9K\", \"totalSubmission\": \"854.8K\", \"totalAcceptedRaw\": 527852, \"totalSubmissionRaw\": 854818, \"acRate\": \"61.8%\"}", "similarQuestions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Two Polynomials Represented as Linked Lists\", \"titleSlug\": \"add-two-polynomials-represented-as-linked-lists\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -16780,9 +16780,9 @@ "questionFrontendId": "446", "title": "Arithmetic Slices II - Subsequence", "content": "Given an integer array nums
, return the number of all the arithmetic subsequences of nums
.
A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
\n\n[1, 3, 5, 7, 9]
, [7, 7, 7, 7]
, and [3, -1, -5, -9]
are arithmetic sequences.[1, 1, 2, 5, 7]
is not an arithmetic sequence.A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
\n\n[2,5,10]
is a subsequence of [1,2,1,2,4,1,5,10]
.The test cases are generated so that the answer fits in 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,4,6,8,10]\nOutput: 7\nExplanation: All arithmetic subsequence slices are:\n[2,4,6]\n[4,6,8]\n[6,8,10]\n[2,4,6,8]\n[4,6,8,10]\n[2,4,6,8,10]\n[2,6,10]\n\n\n
Example 2:
\n\n\nInput: nums = [7,7,7,7,7]\nOutput: 16\nExplanation: Any subsequence of this array is arithmetic.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-231 <= nums[i] <= 231 - 1
You are given n
points
in the plane that are all distinct, where points[i] = [xi, yi]
. A boomerang is a tuple of points (i, j, k)
such that the distance between i
and j
equals the distance between i
and k
(the order of the tuple matters).
Return the number of boomerangs.
\n\n\n
Example 1:
\n\n\nInput: points = [[0,0],[1,0],[2,0]]\nOutput: 2\nExplanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\n\n\n
Example 2:
\n\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: points = [[1,1]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == points.length
1 <= n <= 500
points[i].length == 2
-104 <= xi, yi <= 104
Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
\n
Example 1:
\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [5,6]\n
Example 2:
\nInput: nums = [1,1]\nOutput: [2]\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
1 <= nums[i] <= n
\n
Follow up: Could you do it without extra space and in O(n)
runtime? You may assume the returned list does not count as extra space.
Serialization is 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.
\n\nDesign an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
\n\nThe encoded string should be as compact as possible.
\n\n\n
Example 1:
\nInput: root = [2,1,3]\nOutput: [2,1,3]\n
Example 2:
\nInput: root = []\nOutput: []\n\n
\n
Constraints:
\n\n[0, 104]
.0 <= Node.val <= 104
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
\n\nBasically, the deletion can be divided into two stages:
\n\n\n
Example 1:
\n\nInput: root = [5,3,6,2,4,null,7], key = 3\nOutput: [5,4,6,2,null,null,7]\nExplanation: Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.\n\n\n\n
Example 2:
\n\n\nInput: root = [5,3,6,2,4,null,7], key = 0\nOutput: [5,3,6,2,4,null,7]\nExplanation: The tree does not contain a node with value = 0.\n\n\n
Example 3:
\n\n\nInput: root = [], key = 0\nOutput: []\n\n\n
\n
Constraints:
\n\n[0, 104]
.-105 <= Node.val <= 105
root
is a valid binary search tree.-105 <= key <= 105
\n
Follow up: Could you solve it with time complexity O(height of tree)
?
Given a string s
, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
\n\n\n
Example 1:
\n\n\nInput: s = "tree"\nOutput: "eert"\nExplanation: 'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: s = "cccaaa"\nOutput: "aaaccc"\nExplanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.\nNote that "cacaca" is incorrect, as the same characters must be together.\n\n\n
Example 3:
\n\n\nInput: s = "Aabb"\nOutput: "bbAa"\nExplanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 105
s
consists of uppercase and lowercase English letters and digits.There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points
where points[i] = [xstart, xend]
denotes a balloon whose horizontal diameter stretches between xstart
and xend
. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart
and xend
is burst by an arrow shot at x
if xstart <= x <= xend
. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array points
, return the minimum number of arrows that must be shot to burst all balloons.
\n
Example 1:
\n\n\nInput: points = [[10,16],[2,8],[1,6],[7,12]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].\n\n\n
Example 2:
\n\n\nInput: points = [[1,2],[3,4],[5,6],[7,8]]\nOutput: 4\nExplanation: One arrow needs to be shot for each balloon for a total of 4 arrows.\n\n\n
Example 3:
\n\n\nInput: points = [[1,2],[2,3],[3,4],[4,5]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 105
points[i].length == 2
-231 <= xstart < xend <= 231 - 1
Given an integer array nums
of size n
, return the minimum number of moves required to make all array elements equal.
In one move, you can increment n - 1
elements of the array by 1
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: 3\nExplanation: Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
Given four integer arrays nums1
, nums2
, nums3
, and nums4
all of length n
, return the number of tuples (i, j, k, l)
such that:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
\n
Example 1:
\n\n\nInput: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\nOutput: 2\nExplanation:\nThe two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0\n\n\n
Example 2:
\n\n\nInput: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == nums1.length
n == nums2.length
n == nums3.length
n == nums4.length
1 <= n <= 200
-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.
\n\nEach child i
has a greed factor g[i]
, which is the minimum size of a cookie that the child will be content with; and each cookie j
has a size s[j]
. If s[j] >= g[i]
, we can assign the cookie j
to the child i
, and the child i
will be content. Your goal is to maximize the number of your content children and output the maximum number.
\n
Example 1:
\n\n\nInput: g = [1,2,3], s = [1,1]\nOutput: 1\nExplanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.\n\n\n
Example 2:
\n\n\nInput: g = [1,2], s = [1,2,3]\nOutput: 2\nExplanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.\n\n\n
\n
Constraints:
\n\n1 <= g.length <= 3 * 104
0 <= s.length <= 3 * 104
1 <= g[i], s[j] <= 231 - 1
\n
Note: This question is the same as 2410: Maximum Matching of Players With Trainers.
\n", - "likes": 4260, - "dislikes": 395, - "stats": "{\"totalAccepted\": \"606.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 606786, \"totalSubmissionRaw\": 1135800, \"acRate\": \"53.4%\"}", + "likes": 4477, + "dislikes": 412, + "stats": "{\"totalAccepted\": \"692.7K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 692713, \"totalSubmissionRaw\": 1286319, \"acRate\": \"53.9%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -17163,9 +17163,9 @@ "questionFrontendId": "456", "title": "132 Pattern", "content": "Given an array of n
integers nums
, a 132 pattern is a subsequence of three integers nums[i]
, nums[j]
and nums[k]
such that i < j < k
and nums[i] < nums[k] < nums[j]
.
Return true
if there is a 132 pattern in nums
, otherwise, return false
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: false\nExplanation: There is no 132 pattern in the sequence.\n\n\n
Example 2:
\n\n\nInput: nums = [3,1,4,2]\nOutput: true\nExplanation: There is a 132 pattern in the sequence: [1, 4, 2].\n\n\n
Example 3:
\n\n\nInput: nums = [-1,3,2,0]\nOutput: true\nExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 2 * 105
-109 <= nums[i] <= 109
You are playing a game involving a circular array of non-zero integers nums
. Each nums[i]
denotes the number of indices forward/backward you must move if you are located at index i
:
nums[i]
is positive, move nums[i]
steps forward, andnums[i]
is negative, move nums[i]
steps backward.Since the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.
\n\nA cycle in the array consists of a sequence of indices seq
of length k
where:
seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...
nums[seq[j]]
is either all positive or all negative.k > 1
Return true
if there is a cycle in nums
, or false
otherwise.
\n
Example 1:
\n\nInput: nums = [2,-1,1,2,2]\nOutput: true\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction).\n\n\n
Example 2:
\n\nInput: nums = [-1,-2,-3,-4,-5,6]\nOutput: false\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nThe only cycle is of size 1, so we return false.\n\n\n
Example 3:
\n\nInput: nums = [1,-1,5,1,4]\nOutput: true\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --> 1 --> 0 --> ..., and while it is of size > 1, it has a node jumping forward and a node jumping backward, so it is not a cycle.\nWe can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5000
-1000 <= nums[i] <= 1000
nums[i] != 0
\n
Follow up: Could you solve it in O(n)
time complexity and O(1)
extra space complexity?
There are buckets
buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest
minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
\n\nminutesToDie
minutes. You may not feed any other pigs during this time.minutesToDie
minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.Given buckets
, minutesToDie
, and minutesToTest
, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
\n
Example 1:
\n\n\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 15\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.\n\n\n
Example 2:
\n\n\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 30\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.\n\n\n
\n
Constraints:
\n\n1 <= buckets <= 1000
1 <= minutesToDie <= minutesToTest <= 100
Given a string s
, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.
\n
Example 1:
\n\n\nInput: s = "abab"\nOutput: true\nExplanation: It is the substring "ab" twice.\n\n\n
Example 2:
\n\n\nInput: s = "aba"\nOutput: false\n\n\n
Example 3:
\n\n\nInput: s = "abcabcabcabc"\nOutput: true\nExplanation: It is the substring "abc" four times or the substring "abcabc" twice.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of lowercase English letters.Design and implement a data structure for a Least Frequently Used (LFU) cache.
\n\nImplement 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.
\n\nWhen a key is first inserted into the cache, its use counter is set to 1
(due to the put
operation). The use counter for a key in the cache is incremented either a get
or put
operation is called on it.
The functions get
and put
must each run in O(1)
average time complexity.
\n
Example 1:
\n\n\nInput\n["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n\nExplanation\n// cnt(x) = the use counter for key x\n// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\nLFUCache lfu = new LFUCache(2);\nlfu.put(1, 1); // cache=[1,_], cnt(1)=1\nlfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\nlfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\nlfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n // cache=[3,1], cnt(3)=1, cnt(1)=2\nlfu.get(2); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\nlfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\nlfu.get(1); // return -1 (not found)\nlfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\nlfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3\n\n\n
\n
Constraints:
\n\n1 <= capacity <= 104
0 <= key <= 105
0 <= value <= 109
2 * 105
calls will be made to get
and put
.\n ", - "likes": 5872, - "dislikes": 337, - "stats": "{\"totalAccepted\": \"285.4K\", \"totalSubmission\": \"625.1K\", \"totalAcceptedRaw\": 285390, \"totalSubmissionRaw\": 625092, \"acRate\": \"45.7%\"}", + "likes": 5993, + "dislikes": 341, + "stats": "{\"totalAccepted\": \"308.5K\", \"totalSubmission\": \"662.6K\", \"totalAcceptedRaw\": 308536, \"totalSubmissionRaw\": 662578, \"acRate\": \"46.6%\"}", "similarQuestions": "[{\"title\": \"LRU Cache\", \"titleSlug\": \"lru-cache\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Design In-Memory File System\", \"titleSlug\": \"design-in-memory-file-system\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -17355,9 +17355,9 @@ "questionFrontendId": "461", "title": "Hamming Distance", "content": "
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
\n\nGiven two integers x
and y
, return the Hamming distance between them.
\n
Example 1:
\n\n\nInput: x = 1, y = 4\nOutput: 2\nExplanation:\n1 (0 0 0 1)\n4 (0 1 0 0)\n ↑ ↑\nThe above arrows point to positions where the corresponding bits are different.\n\n\n
Example 2:
\n\n\nInput: x = 3, y = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n0 <= x, y <= 231 - 1
\n
Note: This question is the same as 2220: Minimum Bit Flips to Convert Number.
\n", - "likes": 3903, - "dislikes": 223, - "stats": "{\"totalAccepted\": \"612.9K\", \"totalSubmission\": \"808.3K\", \"totalAcceptedRaw\": 612925, \"totalSubmissionRaw\": 808347, \"acRate\": \"75.8%\"}", + "likes": 3941, + "dislikes": 224, + "stats": "{\"totalAccepted\": \"634.2K\", \"totalSubmission\": \"833.6K\", \"totalAcceptedRaw\": 634180, \"totalSubmissionRaw\": 833558, \"acRate\": \"76.1%\"}", "similarQuestions": "[{\"title\": \"Number of 1 Bits\", \"titleSlug\": \"number-of-1-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Total Hamming Distance\", \"titleSlug\": \"total-hamming-distance\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -17386,10 +17386,10 @@ "questionFrontendId": "462", "title": "Minimum Moves to Equal Array Elements II", "content": "Given an integer array nums
of size n
, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1
.
Test cases are designed so that the answer will fit in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation:\nOnly two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]\n\n\n
Example 2:
\n\n\nInput: nums = [1,10,2,9]\nOutput: 16\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= nums.length <= 105
-109 <= nums[i] <= 109
You are given row x col
grid
representing a map where grid[i][j] = 1
represents land and grid[i][j] = 0
represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid
is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
\n\n\n
Example 1:
\n\nInput: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\nOutput: 16\nExplanation: The perimeter is the 16 yellow stripes in the image above.\n\n\n
Example 2:
\n\n\nInput: grid = [[1]]\nOutput: 4\n\n\n
Example 3:
\n\n\nInput: grid = [[1,0]]\nOutput: 4\n\n\n
\n
Constraints:
\n\nrow == grid.length
col == grid[i].length
1 <= row, col <= 100
grid[i][j]
is 0
or 1
.grid
.In the "100 game" two players take turns adding, to a running total, any integer from 1
to 10
. The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
\n\nFor example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100.
\n\nGiven two integers maxChoosableInteger
and desiredTotal
, return true
if the first player to move can force a win, otherwise, return false
. Assume both players play optimally.
\n
Example 1:
\n\n\nInput: maxChoosableInteger = 10, desiredTotal = 11\nOutput: false\nExplanation:\nNo matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.\n\n\n
Example 2:
\n\n\nInput: maxChoosableInteger = 10, desiredTotal = 0\nOutput: true\n\n\n
Example 3:
\n\n\nInput: maxChoosableInteger = 10, desiredTotal = 1\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= maxChoosableInteger <= 20
0 <= desiredTotal <= 300
We define str = [s, n]
as the string str
which consists of the string s
concatenated n
times.
str == ["abc", 3] =="abcabcabc"
.We define that string s1
can be obtained from string s2
if we can remove some characters from s2
such that it becomes s1
.
s1 = "abc"
can be obtained from s2 = "abdbec"
based on our definition by removing the bolded underlined characters.You are given two strings s1
and s2
and two integers n1
and n2
. You have the two strings str1 = [s1, n1]
and str2 = [s2, n2]
.
Return the maximum integer m
such that str = [str2, m]
can be obtained from str1
.
\n
Example 1:
\nInput: s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\nOutput: 2\n
Example 2:
\nInput: s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\nOutput: 1\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 100
s1
and s2
consist of lowercase English letters.1 <= n1, n2 <= 106
We define the string base
to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz"
, so base
will look like this:
"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...."
.Given a string s
, return the number of unique non-empty substrings of s
are present in base
.
\n
Example 1:
\n\n\nInput: s = "a"\nOutput: 1\nExplanation: Only the substring "a" of s is in base.\n\n\n
Example 2:
\n\n\nInput: s = "cac"\nOutput: 2\nExplanation: There are two substrings ("a", "c") of s in base.\n\n\n
Example 3:
\n\n\nInput: s = "zab"\nOutput: 6\nExplanation: There are six substrings ("z", "a", "b", "za", "ab", and "zab") of s in base.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.Given a string queryIP
, return "IPv4"
if IP is a valid IPv4 address, "IPv6"
if IP is a valid IPv6 address or "Neither"
if IP is not a correct IP of any type.
A valid IPv4 address is an IP in the form "x1.x2.x3.x4"
where 0 <= xi <= 255
and xi
cannot contain leading zeros. For example, "192.168.1.1"
and "192.168.1.0"
are valid IPv4 addresses while "192.168.01.1"
, "192.168.1.00"
, and "192.168@1.1"
are invalid IPv4 addresses.
A valid IPv6 address is an IP in the form "x1:x2:x3:x4:x5:x6:x7:x8"
where:
1 <= xi.length <= 4
xi
is a hexadecimal string which may contain digits, lowercase English letter ('a'
to 'f'
) and upper-case English letters ('A'
to 'F'
).xi
.For example, "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
and "2001:db8:85a3:0:0:8A2E:0370:7334"
are valid IPv6 addresses, while "2001:0db8:85a3::8A2E:037j:7334"
and "02001:0db8:85a3:0000:0000:8a2e:0370:7334"
are invalid IPv6 addresses.
\n
Example 1:
\n\n\nInput: queryIP = "172.16.254.1"\nOutput: "IPv4"\nExplanation: This is a valid IPv4 address, return "IPv4".\n\n\n
Example 2:
\n\n\nInput: queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334"\nOutput: "IPv6"\nExplanation: This is a valid IPv6 address, return "IPv6".\n\n\n
Example 3:
\n\n\nInput: queryIP = "256.256.256.256"\nOutput: "Neither"\nExplanation: This is neither a IPv4 address nor a IPv6 address.\n\n\n
\n
Constraints:
\n\nqueryIP
consists only of English letters, digits and the characters '.'
and ':'
.Given the API rand7()
that generates a uniform random integer in the range [1, 7]
, write a function rand10()
that generates a uniform random integer in the range [1, 10]
. You can only call the API rand7()
, and you shouldn't call any other API. Please do not use a language's built-in random API.
Each test case will have one internal argument n
, the number of times that your implemented function rand10()
will be called while testing. Note that this is not an argument passed to rand10()
.
\n
Example 1:
\nInput: n = 1\nOutput: [2]\n
Example 2:
\nInput: n = 2\nOutput: [2,8]\n
Example 3:
\nInput: n = 3\nOutput: [3,8,10]\n\n
\n
Constraints:
\n\n1 <= n <= 105
\n
Follow up:
\n\nrand7()
function?rand7()
?Given an array of strings words
(without duplicates), return all the concatenated words in the given list of words
.
A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.
\n\n\n
Example 1:
\n\n\nInput: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]\nOutput: ["catsdogcats","dogcatsdog","ratcatdogcat"]\nExplanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; \n"dogcatsdog" can be concatenated by "dog", "cats" and "dog"; \n"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".\n\n
Example 2:
\n\n\nInput: words = ["cat","dog","catdog"]\nOutput: ["catdog"]\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 104
1 <= words[i].length <= 30
words[i]
consists of only lowercase English letters.words
are unique.1 <= sum(words[i].length) <= 105
You are given an integer array matchsticks
where matchsticks[i]
is the length of the ith
matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true
if you can make this square and false
otherwise.
\n
Example 1:
\n\nInput: matchsticks = [1,1,2,2,2]\nOutput: true\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n\n\n
Example 2:
\n\n\nInput: matchsticks = [3,3,3,3,4]\nOutput: false\nExplanation: You cannot find a way to form a square with all the matchsticks.\n\n\n
\n
Constraints:
\n\n1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 108
You are given an array of binary strings strs
and two integers m
and n
.
Return the size of the largest subset of strs
such that there are at most m
0
's and n
1
's in the subset.
A set x
is a subset of a set y
if all elements of x
are also elements of y
.
\n
Example 1:
\n\n\nInput: strs = ["10","0001","111001","1","0"], m = 5, n = 3\nOutput: 4\nExplanation: The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.\nOther valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.\n{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.\n\n\n
Example 2:
\n\n\nInput: strs = ["10","0","1"], m = 1, n = 1\nOutput: 2\nExplanation: The largest subset is {"0", "1"}, so the answer is 2.\n\n\n
\n
Constraints:
\n\n1 <= strs.length <= 600
1 <= strs[i].length <= 100
strs[i]
consists only of digits '0'
and '1'
.1 <= m, n <= 100
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
\n\nEvery house can be warmed, as long as the house is within the heater's warm radius range.
\n\nGiven the positions of houses
and heaters
on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.
Notice that all the heaters
follow your radius standard, and the warm radius will the same.
\n
Example 1:
\n\n\nInput: houses = [1,2,3], heaters = [2]\nOutput: 1\nExplanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.\n\n\n
Example 2:
\n\n\nInput: houses = [1,2,3,4], heaters = [1,4]\nOutput: 1\nExplanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed.\n\n\n
Example 3:
\n\n\nInput: houses = [1,5], heaters = [2]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= houses.length, heaters.length <= 3 * 104
1 <= houses[i], heaters[i] <= 109
The complement of an integer is the integer you get when you flip all the 0
's to 1
's and all the 1
's to 0
's in its binary representation.
5
is "101"
in binary and its complement is "010"
which is the integer 2
.Given an integer num
, return its complement.
\n
Example 1:
\n\n\nInput: num = 5\nOutput: 2\nExplanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\n\n\n
Example 2:
\n\n\nInput: num = 1\nOutput: 0\nExplanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n\n\n
\n
Constraints:
\n\n1 <= num < 231
\n
Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/
\n", - "likes": 3109, - "dislikes": 138, - "stats": "{\"totalAccepted\": \"491.9K\", \"totalSubmission\": \"699.6K\", \"totalAcceptedRaw\": 491890, \"totalSubmissionRaw\": 699573, \"acRate\": \"70.3%\"}", + "likes": 3128, + "dislikes": 143, + "stats": "{\"totalAccepted\": \"504.7K\", \"totalSubmission\": \"717.7K\", \"totalAcceptedRaw\": 504749, \"totalSubmissionRaw\": 717696, \"acRate\": \"70.3%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -17946,9 +17946,9 @@ "questionFrontendId": "477", "title": "Total Hamming Distance", "content": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
\n\nGiven an integer array nums
, return the sum of Hamming distances between all the pairs of the integers in nums
.
\n
Example 1:
\n\n\nInput: nums = [4,14,2]\nOutput: 6\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n\n\n
Example 2:
\n\n\nInput: nums = [4,14,4]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
0 <= nums[i] <= 109
Given the radius and the position of the center of a circle, implement the function randPoint
which generates a uniform random point inside the circle.
Implement the Solution
class:
Solution(double radius, double x_center, double y_center)
initializes the object with the radius of the circle radius
and the position of the center (x_center, y_center)
.randPoint()
returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y]
.\n
Example 1:
\n\n\nInput\n["Solution", "randPoint", "randPoint", "randPoint"]\n[[1.0, 0.0, 0.0], [], [], []]\nOutput\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\nExplanation\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n\n\n
\n
Constraints:
\n\n0 < radius <= 108
-107 <= x_center, y_center <= 107
3 * 104
calls will be made to randPoint
.Given an integer n, return the largest palindromic integer that can be represented as the product of two n
-digits integers. Since the answer can be very large, return it modulo 1337
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 9\n\n\n
\n
Constraints:
\n\n1 <= n <= 8
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
\n\narr = [2,3,4]
, the median is 3
.arr = [1,2,3,4]
, the median is (2 + 3) / 2 = 2.5
.You are given an integer array nums
and an integer k
. There is a sliding window of size k
which is moving from the very left of the array to the very right. You can only see the k
numbers in the window. Each time the sliding window moves right by one position.
Return the median array for each window in the original array. Answers within 10-5
of the actual value will be accepted.
\n
Example 1:
\n\n\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\nExplanation: \nWindow position Median\n--------------- -----\n[1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,2,3,1,4,2], k = 3\nOutput: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
A magical string s
consists of only '1'
and '2'
and obeys the following rules:
'1'
and '2'
generates the string s
itself.The first few elements of s
is s = "1221121221221121122……"
. If we group the consecutive 1
's and 2
's in s
, it will be "1 22 11 2 1 22 1 22 11 2 11 22 ......"
and the occurrences of 1
's or 2
's in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......"
. You can see that the occurrence sequence is s
itself.
Given an integer n
, return the number of 1
's in the first n
number in the magical string s
.
\n
Example 1:
\n\n\nInput: n = 6\nOutput: 3\nExplanation: The first 6 elements of magical string s is "122112" and it contains three 1's, so return 3.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given a license key represented as a string s
that consists of only alphanumeric characters and dashes. The string is separated into n + 1
groups by n
dashes. You are also given an integer k
.
We want to reformat the string s
such that each group contains exactly k
characters, except for the first group, which could be shorter than k
but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.
Return the reformatted license key.
\n\n\n
Example 1:
\n\n\nInput: s = "5F3Z-2e-9-w", k = 4\nOutput: "5F3Z-2E9W"\nExplanation: The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.\n\n\n
Example 2:
\n\n\nInput: s = "2-5g-3-J", k = 2\nOutput: "2-5G-3J"\nExplanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of English letters, digits, and dashes '-'
.1 <= k <= 104
Given an integer n
represented as a string, return the smallest good base of n
.
We call k >= 2
a good base of n
, if all digits of n
base k
are 1
's.
\n
Example 1:
\n\n\nInput: n = "13"\nOutput: "3"\nExplanation: 13 base 3 is 111.\n\n\n
Example 2:
\n\n\nInput: n = "4681"\nOutput: "8"\nExplanation: 4681 base 8 is 11111.\n\n\n
Example 3:
\n\n\nInput: n = "1000000000000000000"\nOutput: "999999999999999999"\nExplanation: 1000000000000000000 base 999999999999999999 is 11.\n\n\n
\n
Constraints:
\n\nn
is an integer in the range [3, 1018]
.n
does not contain any leading zeros.Given a binary array nums
, return the maximum number of consecutive 1
's in the array.
\n
Example 1:
\n\n\nInput: nums = [1,1,0,1,1,1]\nOutput: 3\nExplanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.\n\n\n
Example 2:
\n\n\nInput: nums = [1,0,1,1,0,1]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.You are given an integer array nums
. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0
. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0]
or nums[nums.length - 1]
) which reduces the size of the array by 1
. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return true
if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true
. You may assume that both players are playing optimally.
\n
Example 1:
\n\n\nInput: nums = [1,5,2]\nOutput: false\nExplanation: Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.\n\n\n
Example 2:
\n\n\nInput: nums = [1,5,233,7]\nOutput: true\nExplanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 20
0 <= nums[i] <= 107
You are playing a variation of the game Zuma.
\n\nIn this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R'
, yellow 'Y'
, blue 'B'
, green 'G'
, or white 'W'
. You also have several colored balls in your hand.
Your goal is to clear all of the balls from the board. On each turn:
\n\nGiven a string board
, representing the row of balls on the board, and a string hand
, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1
.
\n
Example 1:
\n\n\nInput: board = "WRRBBW", hand = "RB"\nOutput: -1\nExplanation: It is impossible to clear all the balls. The best you can do is:\n- Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.\n\n
Example 2:
\n\n\nInput: board = "WWRRBBWW", hand = "WRBRW"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.\n2 balls from your hand were needed to clear the board.\n\n\n
Example 3:
\n\n\nInput: board = "G", hand = "GGGGG"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG. GGG -> empty.\n2 balls from your hand were needed to clear the board.\n\n\n
\n
Constraints:
\n\n1 <= board.length <= 16
1 <= hand.length <= 5
board
and hand
consist of the characters 'R'
, 'Y'
, 'B'
, 'G'
, and 'W'
.Given an integer array nums
, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
\n
Example 1:
\n\n\nInput: nums = [4,6,7,7]\nOutput: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n\n\n
Example 2:
\n\n\nInput: nums = [4,4,3,2,1]\nOutput: [[4,4]]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 15
-100 <= nums[i] <= 100
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
\n\nW
should not be larger than the length L
, which means L >= W
.L
and width W
should be as small as possible.Return an array [L, W]
where L
and W
are the length and width of the web page you designed in sequence.
\n
Example 1:
\n\n\nInput: area = 4\nOutput: [2,2]\nExplanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.\n\n\n
Example 2:
\n\n\nInput: area = 37\nOutput: [37,1]\n\n\n
Example 3:
\n\n\nInput: area = 122122\nOutput: [427,286]\n\n\n
\n
Constraints:
\n\n1 <= area <= 107
Given an integer array nums
, return the number of reverse pairs in the array.
A reverse pair is a pair (i, j)
where:
0 <= i < j < nums.length
andnums[i] > 2 * nums[j]
.\n
Example 1:
\n\n\nInput: nums = [1,3,2,3,1]\nOutput: 2\nExplanation: The reverse pairs are:\n(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,3,5,1]\nOutput: 3\nExplanation: The reverse pairs are:\n(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1\n(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
-231 <= nums[i] <= 231 - 1
You 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.
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
.
\n
Example 1:
\n\n\nInput: nums = [1,1,1,1,1], target = 3\nOutput: 5\nExplanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\n\n\n
Example 2:
\n\n\nInput: nums = [1], target = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 20
0 <= nums[i] <= 1000
0 <= sum(nums[i]) <= 1000
-1000 <= target <= 1000
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration
seconds. More formally, an attack at second t
will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]
. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration
seconds after the new attack.
You are given a non-decreasing integer array timeSeries
, where timeSeries[i]
denotes that Teemo attacks Ashe at second timeSeries[i]
, and an integer duration
.
Return the total number of seconds that Ashe is poisoned.
\n\n\n
Example 1:
\n\n\nInput: timeSeries = [1,4], duration = 2\nOutput: 4\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\n\n\n
Example 2:
\n\n\nInput: timeSeries = [1,2], duration = 2\nOutput: 3\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.\n\n
\n
Constraints:
\n\n1 <= timeSeries.length <= 104
0 <= timeSeries[i], duration <= 107
timeSeries
is sorted in non-decreasing order.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.
\n
Example 1:
\n\n\nInput: nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput: [-1,3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,4], nums2 = [1,2,3,4]\nOutput: [3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length <= nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 104
nums1
and nums2
are unique.nums1
also appear in nums2
.\nFollow up: Could you find an
O(nums1.length + nums2.length)
solution?",
- "likes": 8564,
- "dislikes": 881,
- "stats": "{\"totalAccepted\": \"934.6K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 934637, \"totalSubmissionRaw\": 1266791, \"acRate\": \"73.8%\"}",
+ "likes": 8909,
+ "dislikes": 954,
+ "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 1053373, \"totalSubmissionRaw\": 1414206, \"acRate\": \"74.5%\"}",
"similarQuestions": "[{\"title\": \"Next Greater Element II\", \"titleSlug\": \"next-greater-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element III\", \"titleSlug\": \"next-greater-element-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Daily Temperatures\", \"titleSlug\": \"daily-temperatures\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Subarray Ranges\", \"titleSlug\": \"sum-of-subarray-ranges\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sum of Total Strength of Wizards\", \"titleSlug\": \"sum-of-total-strength-of-wizards\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Next Greater Element IV\", \"titleSlug\": \"next-greater-element-iv\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Remove Nodes From Linked List\", \"titleSlug\": \"remove-nodes-from-linked-list\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Missing Integer Greater Than Sequential Prefix Sum\", \"titleSlug\": \"smallest-missing-integer-greater-than-sequential-prefix-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -18689,9 +18689,9 @@
"questionFrontendId": "497",
"title": "Random Point in Non-overlapping Rectangles",
"content": "You are given an array of non-overlapping axis-aligned rectangles rects
where rects[i] = [ai, bi, xi, yi]
indicates that (ai, bi)
is the bottom-left corner point of the ith
rectangle and (xi, yi)
is the top-right corner point of the ith
rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
\n\nNote that an integer point is a point that has integer coordinates.
\n\nImplement the Solution
class:
Solution(int[][] rects)
Initializes the object with the given rectangles rects
.int[] pick()
Returns a random integer point [u, v]
inside the space covered by one of the given rectangles.\n
Example 1:
\n\nInput\n["Solution", "pick", "pick", "pick", "pick", "pick"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\nOutput\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\nExplanation\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n\n\n
\n
Constraints:
\n\n1 <= rects.length <= 100
rects[i].length == 4
-109 <= ai < xi <= 109
-109 <= bi < yi <= 109
xi - ai <= 2000
yi - bi <= 2000
104
calls will be made to pick
.Given an m x n
matrix mat
, return an array of all the elements of the array in a diagonal order.
\n
Example 1:
\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,2,4,7,5,3,6,8,9]\n\n\n
Example 2:
\n\n\nInput: mat = [[1,2],[3,4]]\nOutput: [1,2,3,4]\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
Given an array of strings words
, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.
Note that the strings are case-insensitive, both lowercased and uppercased of the same letter are treated as if they are at the same row.
\n\nIn the American keyboard:
\n\n"qwertyuiop"
,"asdfghjkl"
, and"zxcvbnm"
.\n
Example 1:
\n\nInput: words = ["Hello","Alaska","Dad","Peace"]
\n\nOutput: ["Alaska","Dad"]
\n\nExplanation:
\n\nBoth "a"
and "A"
are in the 2nd row of the American keyboard due to case insensitivity.
Example 2:
\n\nInput: words = ["omk"]
\n\nOutput: []
\nExample 3:
\n\nInput: words = ["adsdf","sfd"]
\n\nOutput: ["adsdf","sfd"]
\n\n
Constraints:
\n\n1 <= words.length <= 20
1 <= words[i].length <= 100
words[i]
consists of English letters (both lowercase and uppercase). Given the root
of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.
If the tree has more than one mode, return them in any order.
\n\nAssume a BST is defined as follows:
\n\n\n
Example 1:
\n\nInput: root = [1,null,2,2]\nOutput: [2]\n\n\n
Example 2:
\n\n\nInput: root = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n[1, 104]
.-105 <= Node.val <= 105
\nFollow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).", - "likes": 3969, - "dislikes": 798, - "stats": "{\"totalAccepted\": \"337.7K\", \"totalSubmission\": \"591.4K\", \"totalAcceptedRaw\": 337690, \"totalSubmissionRaw\": 591426, \"acRate\": \"57.1%\"}", + "likes": 4002, + "dislikes": 801, + "stats": "{\"totalAccepted\": \"351.8K\", \"totalSubmission\": \"611.8K\", \"totalAcceptedRaw\": 351771, \"totalSubmissionRaw\": 611840, \"acRate\": \"57.5%\"}", "similarQuestions": "[{\"title\": \"Validate Binary Search Tree\", \"titleSlug\": \"validate-binary-search-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -18898,9 +18898,9 @@ "questionFrontendId": "502", "title": "IPO", "content": "
Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k
distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k
distinct projects.
You are given n
projects where the ith
project has a pure profit profits[i]
and a minimum capital of capital[i]
is needed to start it.
Initially, you have w
capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of at most k
distinct projects from given projects to maximize your final capital, and return the final maximized capital.
The answer is guaranteed to fit in a 32-bit signed integer.
\n\n\n
Example 1:
\n\n\nInput: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput: 4\nExplanation: Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n\n\n
Example 2:
\n\n\nInput: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput: 6\n\n\n
\n
Constraints:
\n\n1 <= k <= 105
0 <= w <= 109
n == profits.length
n == capital.length
1 <= n <= 105
0 <= profits[i] <= 104
0 <= capital[i] <= 109
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 circularly to find its next greater number. If it doesn't exist, return -1
for this number.
\n
Example 1:
\n\n\nInput: nums = [1,2,1]\nOutput: [2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,3]\nOutput: [2,3,4,-1,4]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-109 <= nums[i] <= 109
Given an integer num
, return a string of its base 7 representation.
\n
Example 1:
\nInput: num = 100\nOutput: \"202\"\n
Example 2:
\nInput: num = -7\nOutput: \"-10\"\n\n
\n
Constraints:
\n\n-107 <= num <= 107
You are given an integer array score
of size n
, where score[i]
is the score of the ith
athlete in a competition. All the scores are guaranteed to be unique.
The athletes are placed based on their scores, where the 1st
place athlete has the highest score, the 2nd
place athlete has the 2nd
highest score, and so on. The placement of each athlete determines their rank:
1st
place athlete's rank is "Gold Medal"
.2nd
place athlete's rank is "Silver Medal"
.3rd
place athlete's rank is "Bronze Medal"
.4th
place to the nth
place athlete, their rank is their placement number (i.e., the xth
place athlete's rank is "x"
).Return an array answer
of size n
where answer[i]
is the rank of the ith
athlete.
\n
Example 1:
\n\n\nInput: score = [5,4,3,2,1]\nOutput: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]\nExplanation: The placements are [1st, 2nd, 3rd, 4th, 5th].\n\n
Example 2:
\n\n\nInput: score = [10,3,8,9,4]\nOutput: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]\nExplanation: The placements are [1st, 5th, 3rd, 2nd, 4th].\n\n\n\n
\n
Constraints:
\n\nn == score.length
1 <= n <= 104
0 <= score[i] <= 106
score
are unique.A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x
is an integer that can divide x
evenly.
Given an integer n
, return true
if n
is a perfect number, otherwise return false
.
\n
Example 1:
\n\n\nInput: num = 28\nOutput: true\nExplanation: 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.\n\n\n
Example 2:
\n\n\nInput: num = 7\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= num <= 108
Given the root
of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
\n\n\n
Example 1:
\n\nInput: root = [5,2,-3]\nOutput: [2,-3,4]\n\n\n
Example 2:
\n\nInput: root = [5,2,-5]\nOutput: [2]\n\n\n
\n
Constraints:
\n\n[1, 104]
.-105 <= Node.val <= 105
The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
\nF(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.\n\n\n
Given n
, calculate F(n)
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 1\nExplanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: 2\nExplanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: 3\nExplanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n\n\n
\n
Constraints:
\n\n0 <= n <= 30
Table: Activity
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| player_id | int |\n| device_id | int |\n| event_date | date |\n| games_played | int |\n+--------------+---------+\n(player_id, event_date) is the primary key (combination of columns with unique values) of this table.\nThis table shows the activity of players of some games.\nEach row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.\n\n\n
\n\n
Write a solution to find the first login date for each player.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1 | 2 | 2016-03-01 | 5 |\n| 1 | 2 | 2016-05-02 | 6 |\n| 2 | 3 | 2017-06-25 | 1 |\n| 3 | 1 | 2016-03-02 | 0 |\n| 3 | 4 | 2018-07-03 | 5 |\n+-----------+-----------+------------+--------------+\nOutput: \n+-----------+-------------+\n| player_id | first_login |\n+-----------+-------------+\n| 1 | 2016-03-01 |\n| 2 | 2017-06-25 |\n| 3 | 2016-03-02 |\n+-----------+-------------+\n\n", - "likes": 908, - "dislikes": 33, - "stats": "{\"totalAccepted\": \"340.8K\", \"totalSubmission\": \"451.9K\", \"totalAcceptedRaw\": 340765, \"totalSubmissionRaw\": 451937, \"acRate\": \"75.4%\"}", + "likes": 947, + "dislikes": 35, + "stats": "{\"totalAccepted\": \"382.9K\", \"totalSubmission\": \"505.5K\", \"totalAcceptedRaw\": 382929, \"totalSubmissionRaw\": 505469, \"acRate\": \"75.8%\"}", "similarQuestions": "[{\"title\": \"Game Play Analysis II\", \"titleSlug\": \"game-play-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -19268,9 +19268,9 @@ "questionFrontendId": "512", "title": "Game Play Analysis II", "content": null, - "likes": 272, + "likes": 273, "dislikes": 43, - "stats": "{\"totalAccepted\": \"94.3K\", \"totalSubmission\": \"176K\", \"totalAcceptedRaw\": 94329, \"totalSubmissionRaw\": 175957, \"acRate\": \"53.6%\"}", + "stats": "{\"totalAccepted\": \"98.6K\", \"totalSubmission\": \"182.6K\", \"totalAcceptedRaw\": 98645, \"totalSubmissionRaw\": 182638, \"acRate\": \"54.0%\"}", "similarQuestions": "[{\"title\": \"Game Play Analysis I\", \"titleSlug\": \"game-play-analysis-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Game Play Analysis III\", \"titleSlug\": \"game-play-analysis-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -19299,9 +19299,9 @@ "questionFrontendId": "513", "title": "Find Bottom Left Tree Value", "content": "
Given the root
of a binary tree, return the leftmost value in the last row of the tree.
\n
Example 1:
\n\nInput: root = [2,1,3]\nOutput: 1\n\n\n
Example 2:
\n\nInput: root = [1,2,3,4,null,5,6,null,null,7]\nOutput: 7\n\n\n
\n
Constraints:
\n\n[1, 104]
.-231 <= Node.val <= 231 - 1
In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door.
\n\nGiven a string ring
that represents the code engraved on the outer ring and another string key
that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.
Initially, the first character of the ring is aligned at the "12:00"
direction. You should spell all the characters in key
one by one by rotating ring
clockwise or anticlockwise to make each character of the string key aligned at the "12:00"
direction and then by pressing the center button.
At the stage of rotating the ring to spell the key character key[i]
:
ring
's characters at the "12:00"
direction, where this character must equal key[i]
.key[i]
has been aligned at the "12:00"
direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.\n
Example 1:
\n\nInput: ring = "godding", key = "gd"\nOutput: 4\nExplanation:\nFor the first key character 'g', since it is already in place, we just need 1 step to spell this character. \nFor the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".\nAlso, we need 1 more step for spelling.\nSo the final output is 4.\n\n\n
Example 2:
\n\n\nInput: ring = "godding", key = "godding"\nOutput: 13\n\n\n
\n
Constraints:
\n\n1 <= ring.length, key.length <= 100
ring
and key
consist of only lower case English letters.key
could always be spelled by rotating ring
.Given the root
of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
\n
Example 1:
\n\nInput: root = [1,3,2,5,3,null,9]\nOutput: [1,3,9]\n\n\n
Example 2:
\n\n\nInput: root = [1,2,3]\nOutput: [1,3]\n\n\n
\n
Constraints:
\n\n[0, 104]
.-231 <= Node.val <= 231 - 1
Given a string s
, find the longest palindromic subsequence's length in s
.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: s = "bbbab"\nOutput: 4\nExplanation: One possible longest palindromic subsequence is "bbbb".\n\n\n
Example 2:
\n\n\nInput: s = "cbbd"\nOutput: 2\nExplanation: One possible longest palindromic subsequence is "bb".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists only of lowercase English letters.You have n
super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any m
(1 <= m <= n
) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array machines
representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1
.
\n
Example 1:
\n\n\nInput: machines = [1,0,5]\nOutput: 3\nExplanation:\n1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2\n\n\n
Example 2:
\n\n\nInput: machines = [0,3,0]\nOutput: 2\nExplanation:\n1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1\n\n\n
Example 3:
\n\n\nInput: machines = [0,2,0]\nOutput: -1\nExplanation:\nIt's impossible to make all three washing machines have the same number of dresses.\n\n\n
\n
Constraints:
\n\nn == machines.length
1 <= n <= 104
0 <= machines[i] <= 105
You are given an integer array coins
representing coins of different denominations and an integer amount
representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0
.
You may assume that you have an infinite number of each kind of coin.
\n\nThe answer is guaranteed to fit into a signed 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: amount = 5, coins = [1,2,5]\nOutput: 4\nExplanation: there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\n\n\n
Example 2:
\n\n\nInput: amount = 3, coins = [2]\nOutput: 0\nExplanation: the amount of 3 cannot be made up just with coins of 2.\n\n\n
Example 3:
\n\n\nInput: amount = 10, coins = [10]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= coins.length <= 300
1 <= coins[i] <= 5000
coins
are unique.0 <= amount <= 5000
There is an m x n
binary grid matrix
with all the values set 0
initially. Design an algorithm to randomly pick an index (i, j)
where matrix[i][j] == 0
and flips it to 1
. All the indices (i, j)
where matrix[i][j] == 0
should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.
\n\nImplement the Solution
class:
Solution(int m, int n)
Initializes the object with the size of the binary matrix m
and n
.int[] flip()
Returns a random index [i, j]
of the matrix where matrix[i][j] == 0
and flips it to 1
.void reset()
Resets all the values of the matrix to be 0
.\n
Example 1:
\n\n\nInput\n["Solution", "flip", "flip", "flip", "reset", "flip"]\n[[3, 1], [], [], [], [], []]\nOutput\n[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]\n\nExplanation\nSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 104
flip
.1000
calls will be made to flip
and reset
.We define the usage of capitals in a word to be right when one of the following cases holds:
\n\n"USA"
."leetcode"
."Google"
.Given a string word
, return true
if the usage of capitals in it is right.
\n
Example 1:
\nInput: word = \"USA\"\nOutput: true\n
Example 2:
\nInput: word = \"FlaG\"\nOutput: false\n\n
\n
Constraints:
\n\n1 <= word.length <= 100
word
consists of lowercase and uppercase English letters.Given two strings a
and b
, return the length of the longest uncommon subsequence between a
and b
. If no such uncommon subsequence exists, return -1
.
An uncommon subsequence between two strings is a string that is a subsequence of exactly one of them.
\n\n\n
Example 1:
\n\n\nInput: a = "aba", b = "cdc"\nOutput: 3\nExplanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".\nNote that "cdc" is also a longest uncommon subsequence.\n\n\n
Example 2:
\n\n\nInput: a = "aaa", b = "bbb"\nOutput: 3\nExplanation: The longest uncommon subsequences are "aaa" and "bbb".\n\n\n
Example 3:
\n\n\nInput: a = "aaa", b = "aaa"\nOutput: -1\nExplanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1
.\n
\n\n\n
Constraints:
\n\n1 <= a.length, b.length <= 100
a
and b
consist of lower-case English letters.Given an array of strings strs
, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1
.
An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.
\n\nA subsequence of a string s
is a string that can be obtained after deleting any number of characters from s
.
"abc"
is a subsequence of "aebdc"
because you can delete the underlined characters in "aebdc"
to get "abc"
. Other subsequences of "aebdc"
include "aebdc"
, "aeb"
, and ""
(empty string).\n
Example 1:
\nInput: strs = [\"aba\",\"cdc\",\"eae\"]\nOutput: 3\n
Example 2:
\nInput: strs = [\"aaa\",\"aaa\",\"aa\"]\nOutput: -1\n\n
\n
Constraints:
\n\n2 <= strs.length <= 50
1 <= strs[i].length <= 10
strs[i]
consists of lowercase English letters.Given an integer array nums and an integer k, return true
if nums
has a good subarray or false
otherwise.
A good subarray is a subarray where:
\n\nk
.Note that:
\n\nx
is a multiple of k
if there exists an integer n
such that x = n * k
. 0
is always a multiple of k
.\n
Example 1:
\n\n\nInput: nums = [23,2,4,6,7], k = 6\nOutput: true\nExplanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\n\n\n
Example 2:
\n\n\nInput: nums = [23,2,6,4,7], k = 6\nOutput: true\nExplanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.\n\n\n
Example 3:
\n\n\nInput: nums = [23,2,6,4,7], k = 13\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= sum(nums[i]) <= 231 - 1
1 <= k <= 231 - 1
Given a string s
and a string array dictionary
, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
\n
Example 1:
\n\n\nInput: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]\nOutput: "apple"\n\n\n
Example 2:
\n\n\nInput: s = "abpcplea", dictionary = ["a","b","c"]\nOutput: "a"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s
and dictionary[i]
consist of lowercase English letters.Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of 0
and 1
.
\n
Example 1:
\n\n\nInput: nums = [0,1]\nOutput: 2\nExplanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,0]\nOutput: 2\nExplanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.Given a binary array nums
, return the maximum length of a contiguous subarray with an equal number of 0
and 1
.
\n
Example 1:
\n\n\nInput: nums = [0,1]\nOutput: 2\nExplanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,0]\nOutput: 2\nExplanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n\n\n
Example 3:
\n\n\nInput: nums = [0,1,1,1,1,1,0,0,0]\nOutput: 6\nExplanation: [1,1,1,0,0,0] is the longest contiguous subarray with equal number of 0 and 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.Suppose you have n
integers labeled 1
through n
. A permutation of those n
integers perm
(1-indexed) is considered a beautiful arrangement if for every i
(1 <= i <= n
), either of the following is true:
perm[i]
is divisible by i
.i
is divisible by perm[i]
.Given an integer n
, return the number of the beautiful arrangements that you can construct.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 2\nExplanation: \nThe first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 15
You are given a 0-indexed array of positive integers w
where w[i]
describes the weight of the ith
index.
You need to implement the function pickIndex()
, which randomly picks an index in the range [0, w.length - 1]
(inclusive) and returns it. The probability of picking an index i
is w[i] / sum(w)
.
w = [1, 3]
, the probability of picking index 0
is 1 / (1 + 3) = 0.25
(i.e., 25%
), and the probability of picking index 1
is 3 / (1 + 3) = 0.75
(i.e., 75%
).\n
Example 1:
\n\n\nInput\n["Solution","pickIndex"]\n[[[1]],[]]\nOutput\n[null,0]\n\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n\n\n
Example 2:
\n\n\nInput\n["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\n\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n\n\n
\n
Constraints:
\n\n1 <= w.length <= 104
1 <= w[i] <= 105
pickIndex
will be called at most 104
times.Let's play the minesweeper game (Wikipedia, online game)!
\n\nYou are given an m x n
char matrix board
representing the game board where:
'M'
represents an unrevealed mine,'E'
represents an unrevealed empty square,'B'
represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),'1'
to '8'
) represents how many mines are adjacent to this revealed square, and'X'
represents a revealed mine.You are also given an integer array click
where click = [clickr, clickc]
represents the next click position among all the unrevealed squares ('M'
or 'E'
).
Return the board after revealing this position according to the following rules:
\n\n'M'
is revealed, then the game is over. You should change it to 'X'
.'E'
with no adjacent mines is revealed, then change it to a revealed blank 'B'
and all of its adjacent unrevealed squares should be revealed recursively.'E'
with at least one adjacent mine is revealed, then change it to a digit ('1'
to '8'
) representing the number of adjacent mines.\n
Example 1:
\n\nInput: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0]\nOutput: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]\n\n\n
Example 2:
\n\nInput: board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2]\nOutput: [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]\n\n\n
\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m, n <= 50
board[i][j]
is either 'M'
, 'E'
, 'B'
, or a digit from '1'
to '8'
.click.length == 2
0 <= clickr < m
0 <= clickc < n
board[clickr][clickc]
is either 'M'
or 'E'
.Given the root
of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.
\n
Example 1:
\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\n
Example 2:
\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n
\n
Constraints:
\n\n[2, 104]
.0 <= Node.val <= 105
\n
Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
\n", - "likes": 4518, - "dislikes": 242, - "stats": "{\"totalAccepted\": \"475.2K\", \"totalSubmission\": \"810.4K\", \"totalAcceptedRaw\": 475197, \"totalSubmissionRaw\": 810364, \"acRate\": \"58.6%\"}", + "likes": 4596, + "dislikes": 258, + "stats": "{\"totalAccepted\": \"521.9K\", \"totalSubmission\": \"887.6K\", \"totalAcceptedRaw\": 521940, \"totalSubmissionRaw\": 887593, \"acRate\": \"58.8%\"}", "similarQuestions": "[{\"title\": \"K-diff Pairs in an Array\", \"titleSlug\": \"k-diff-pairs-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -19990,9 +19990,9 @@ "questionFrontendId": "531", "title": "Lonely Pixel I", "content": null, - "likes": 440, + "likes": 446, "dislikes": 41, - "stats": "{\"totalAccepted\": \"45.2K\", \"totalSubmission\": \"72.5K\", \"totalAcceptedRaw\": 45208, \"totalSubmissionRaw\": 72451, \"acRate\": \"62.4%\"}", + "stats": "{\"totalAccepted\": \"46.2K\", \"totalSubmission\": \"73.9K\", \"totalAcceptedRaw\": 46170, \"totalSubmissionRaw\": 73908, \"acRate\": \"62.5%\"}", "similarQuestions": "[{\"title\": \"Lonely Pixel II\", \"titleSlug\": \"lonely-pixel-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -20027,9 +20027,9 @@ "questionFrontendId": "532", "title": "K-diff Pairs in an Array", "content": "Given an array of integers nums
and an integer k
, return the number of unique k-diff pairs in the array.
A k-diff pair is an integer pair (nums[i], nums[j])
, where the following are true:
0 <= i, j < nums.length
i != j
|nums[i] - nums[j]| == k
Notice that |val|
denotes the absolute value of val
.
\n
Example 1:
\n\n\nInput: nums = [3,1,4,1,5], k = 2\nOutput: 2\nExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number of unique pairs.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5], k = 1\nOutput: 4\nExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,1,5,4], k = 0\nOutput: 1\nExplanation: There is one 0-diff pair in the array, (1, 1).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-107 <= nums[i] <= 107
0 <= k <= 107
Note: This is a companion problem to the System Design problem: Design TinyURL.\n\n
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk
. Design a class to encode a URL and decode a tiny URL.
There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.
\n\nImplement the Solution
class:
Solution()
Initializes the object of the system.String encode(String longUrl)
Returns a tiny URL for the given longUrl
.String decode(String shortUrl)
Returns the original long URL for the given shortUrl
. It is guaranteed that the given shortUrl
was encoded by the same object.\n
Example 1:
\n\n\nInput: url = "https://leetcode.com/problems/design-tinyurl"\nOutput: "https://leetcode.com/problems/design-tinyurl"\n\nExplanation:\nSolution obj = new Solution();\nstring tiny = obj.encode(url); // returns the encoded tiny url.\nstring ans = obj.decode(tiny); // returns the original url after decoding it.\n\n\n
\n
Constraints:
\n\n1 <= url.length <= 104
url
is guranteed to be a valid URL.A complex number can be represented as a string on the form "real+imaginaryi"
where:
real
is the real part and is an integer in the range [-100, 100]
.imaginary
is the imaginary part and is an integer in the range [-100, 100]
.i2 == -1
.Given two complex numbers num1
and num2
as strings, return a string of the complex number that represents their multiplications.
\n
Example 1:
\n\n\nInput: num1 = "1+1i", num2 = "1+1i"\nOutput: "0+2i"\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n\n\n
Example 2:
\n\n\nInput: num1 = "1+-1i", num2 = "1+-1i"\nOutput: "0+-2i"\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n\n\n
\n
Constraints:
\n\nnum1
and num2
are valid complex numbers.Given the root
of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
\n\n\n
Example 1:
\n\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\n
Example 2:
\n\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n
\n
Constraints:
\n\n[0, 104]
.-104 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.\n
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
\n", - "likes": 5290, - "dislikes": 176, - "stats": "{\"totalAccepted\": \"319.9K\", \"totalSubmission\": \"456K\", \"totalAcceptedRaw\": 319929, \"totalSubmissionRaw\": 456034, \"acRate\": \"70.2%\"}", + "likes": 5337, + "dislikes": 177, + "stats": "{\"totalAccepted\": \"329.5K\", \"totalSubmission\": \"467.4K\", \"totalAcceptedRaw\": 329524, \"totalSubmissionRaw\": 467441, \"acRate\": \"70.5%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -20295,9 +20295,9 @@ "questionFrontendId": "539", "title": "Minimum Time Difference", "content": "Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list.\n\n
Example 1:
\nInput: timePoints = [\"23:59\",\"00:00\"]\nOutput: 1\n
Example 2:
\nInput: timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput: 0\n\n
\n
Constraints:
\n\n2 <= timePoints.length <= 2 * 104
timePoints[i]
is in the format "HH:MM".You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
\n\nReturn the single element that appears only once.
\n\nYour solution must run in O(log n)
time and O(1)
space.
\n
Example 1:
\nInput: nums = [1,1,2,3,3,4,4,8,8]\nOutput: 2\n
Example 2:
\nInput: nums = [3,3,7,7,10,11,11]\nOutput: 10\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer than k
characters left, reverse all of them. If there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters and leave the other as original.
\n
Example 1:
\nInput: s = \"abcdefg\", k = 2\nOutput: \"bacdfeg\"\n
Example 2:
\nInput: s = \"abcd\", k = 2\nOutput: \"bacd\"\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of only lowercase English letters.1 <= k <= 104
Given an m x n
binary matrix mat
, return the distance of the nearest 0
for each cell.
The distance between two cells sharing a common edge is 1
.
\n
Example 1:
\n\nInput: mat = [[0,0,0],[0,1,0],[0,0,0]]\nOutput: [[0,0,0],[0,1,0],[0,0,0]]\n\n\n
Example 2:
\n\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]]\nOutput: [[0,0,0],[0,1,0],[1,2,1]]\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
mat[i][j]
is either 0
or 1
.0
in mat
.\n
Note: This question is the same as 1765: https://leetcode.com/problems/map-of-highest-peak/
\n", - "likes": 9934, - "dislikes": 431, - "stats": "{\"totalAccepted\": \"681.7K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 681734, \"totalSubmissionRaw\": 1350126, \"acRate\": \"50.5%\"}", + "likes": 10161, + "dislikes": 439, + "stats": "{\"totalAccepted\": \"742.6K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 742616, \"totalSubmissionRaw\": 1443940, \"acRate\": \"51.4%\"}", "similarQuestions": "[{\"title\": \"Shortest Path to Get Food\", \"titleSlug\": \"shortest-path-to-get-food\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Remove Adjacent Ones in Matrix\", \"titleSlug\": \"minimum-operations-to-remove-adjacent-ones-in-matrix\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Difference Between Ones and Zeros in Row and Column\", \"titleSlug\": \"difference-between-ones-and-zeros-in-row-and-column\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -20443,9 +20443,9 @@ "questionFrontendId": "543", "title": "Diameter of Binary Tree", "content": "Given the root
of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
.
The length of a path between two nodes is represented by the number of edges between them.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n\n\n
Example 2:
\n\n\nInput: root = [1,2]\nOutput: 1\n\n\n
\n
Constraints:
\n\n[1, 104]
.-100 <= Node.val <= 100
You are given several boxes
with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k
boxes, k >= 1
), remove them and get k * k
points.
Return the maximum points you can get.
\n\n\n
Example 1:
\n\n\nInput: boxes = [1,3,2,2,2,3,4,3,1]\nOutput: 23\nExplanation:\n[1, 3, 2, 2, 2, 3, 4, 3, 1] \n----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n----> [1, 3, 3, 3, 1] (1*1=1 points) \n----> [1, 1] (3*3=9 points) \n----> [] (2*2=4 points)\n\n\n
Example 2:
\n\n\nInput: boxes = [1,1,1]\nOutput: 9\n\n\n
Example 3:
\n\n\nInput: boxes = [1]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= boxes.length <= 100
1 <= boxes[i] <= 100
There are n
cities. Some of them are connected, while some are not. If city a
is connected directly with city b
, and city b
is connected directly with city c
, then city a
is connected indirectly with city c
.
A province is a group of directly or indirectly connected cities and no other cities outside of the group.
\n\nYou are given an n x n
matrix isConnected
where isConnected[i][j] = 1
if the ith
city and the jth
city are directly connected, and isConnected[i][j] = 0
otherwise.
Return the total number of provinces.
\n\n\n
Example 1:
\n\nInput: isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput: 2\n\n\n
Example 2:
\n\nInput: isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
is 1
or 0
.isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
Table: Activity
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| player_id | int |\n| device_id | int |\n| event_date | date |\n| games_played | int |\n+--------------+---------+\n(player_id, event_date) is the primary key (combination of columns with unique values) of this table.\nThis table shows the activity of players of some games.\nEach row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.\n\n\n
\n\n
Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1 | 2 | 2016-03-01 | 5 |\n| 1 | 2 | 2016-03-02 | 6 |\n| 2 | 3 | 2017-06-25 | 1 |\n| 3 | 1 | 2016-03-02 | 0 |\n| 3 | 4 | 2018-07-03 | 5 |\n+-----------+-----------+------------+--------------+\nOutput: \n+-----------+\n| fraction |\n+-----------+\n| 0.33 |\n+-----------+\nExplanation: \nOnly the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33\n\n", - "likes": 1102, - "dislikes": 221, - "stats": "{\"totalAccepted\": \"269.5K\", \"totalSubmission\": \"695.4K\", \"totalAcceptedRaw\": 269549, \"totalSubmissionRaw\": 695382, \"acRate\": \"38.8%\"}", + "content": "
Table: Activity
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| player_id | int |\n| device_id | int |\n| event_date | date |\n| games_played | int |\n+--------------+---------+\n(player_id, event_date) is the primary key (combination of columns with unique values) of this table.\nThis table shows the activity of players of some games.\nEach row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.\n\n\n
\n\n
Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to determine the number of players who logged in on the day immediately following their initial login, and divide it by the number of total players.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivity table:\n+-----------+-----------+------------+--------------+\n| player_id | device_id | event_date | games_played |\n+-----------+-----------+------------+--------------+\n| 1 | 2 | 2016-03-01 | 5 |\n| 1 | 2 | 2016-03-02 | 6 |\n| 2 | 3 | 2017-06-25 | 1 |\n| 3 | 1 | 2016-03-02 | 0 |\n| 3 | 4 | 2018-07-03 | 5 |\n+-----------+-----------+------------+--------------+\nOutput: \n+-----------+\n| fraction |\n+-----------+\n| 0.33 |\n+-----------+\nExplanation: \nOnly the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33\n\n", + "likes": 1226, + "dislikes": 228, + "stats": "{\"totalAccepted\": \"325.6K\", \"totalSubmission\": \"825.8K\", \"totalAcceptedRaw\": 325575, \"totalSubmissionRaw\": 825795, \"acRate\": \"39.4%\"}", "similarQuestions": "[{\"title\": \"Game Play Analysis III\", \"titleSlug\": \"game-play-analysis-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Game Play Analysis V\", \"titleSlug\": \"game-play-analysis-v\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -20736,9 +20736,9 @@ "questionFrontendId": "551", "title": "Student Attendance Record I", "content": "
You are given a string s
representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A'
: Absent.'L'
: Late.'P'
: Present.The student is eligible for an attendance award if they meet both of the following criteria:
\n\n'A'
) for strictly fewer than 2 days total.'L'
) for 3 or more consecutive days.Return true
if the student is eligible for an attendance award, or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "PPALLP"\nOutput: true\nExplanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.\n\n\n
Example 2:
\n\n\nInput: s = "PPALLL"\nOutput: false\nExplanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either 'A'
, 'L'
, or 'P'
.An attendance record for a student can be represented as a string where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
\n\n'A'
: Absent.'L'
: Late.'P'
: Present.Any student is eligible for an attendance award if they meet both of the following criteria:
\n\n'A'
) for strictly fewer than 2 days total.'L'
) for 3 or more consecutive days.Given an integer n
, return the number of possible attendance records of length n
that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 8\nExplanation: There are 8 records with length 2 that are eligible for an award:\n"PP", "AP", "PA", "LP", "PL", "AL", "LA", "LL"\nOnly "AA" is not eligible because there are 2 absences (there need to be fewer than 2).\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: n = 10101\nOutput: 183236316\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given an integer array nums
. The adjacent integers in nums
will perform the float division.
nums = [2,3,4]
, we will evaluate the expression "2/3/4"
.However, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.
\n\nReturn the corresponding expression that has the maximum value in string format.
\n\nNote: your expression should not contain redundant parenthesis.
\n\n\n
Example 1:
\n\n\nInput: nums = [1000,100,10,2]\nOutput: "1000/(100/10/2)"\nExplanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in "1000/((100/10)/2)" are redundant since they do not influence the operation priority.\nSo you should return "1000/(100/10/2)".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,4]\nOutput: "2/(3/4)"\nExplanation: (2/(3/4)) = 8/3 = 2.667\nIt can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 10
2 <= nums[i] <= 1000
There is a rectangular brick wall in front of you with n
rows of bricks. The ith
row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.
Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.
\n\nGiven the 2D array wall
that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.
\n
Example 1:
\n\nInput: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: wall = [[1],[1],[1]]\nOutput: 3\n\n\n
\n
Constraints:
\n\nn == wall.length
1 <= n <= 104
1 <= wall[i].length <= 104
1 <= sum(wall[i].length) <= 2 * 104
sum(wall[i])
is the same for each row i
.1 <= wall[i][j] <= 231 - 1
Given a positive integer n
, find the smallest integer which has exactly the same digits existing in the integer n
and is greater in value than n
. If no such positive integer exists, return -1
.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1
.
\n
Example 1:
\nInput: n = 12\nOutput: 21\n
Example 2:
\nInput: n = 21\nOutput: -1\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
Given a string s
, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
\n
Example 1:
\n\n\nInput: s = "Let's take LeetCode contest"\nOutput: "s'teL ekat edoCteeL tsetnoc"\n\n\n
Example 2:
\n\n\nInput: s = "Mr Ding"\nOutput: "rM gniD"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 104
s
contains printable ASCII characters.s
does not contain any leading or trailing spaces.s
.s
are separated by a single space.A Binary Matrix is a matrix in which all the elements are either 0 or 1.
\n\nGiven quadTree1
and quadTree2
. quadTree1
represents a n * n
binary matrix and quadTree2
represents another n * n
binary matrix.
Return a Quad-Tree representing the n * n
binary matrix which is the result of logical bitwise OR of the two binary matrixes represented by quadTree1
and quadTree2
.
Notice that you can assign the value of a node to True or False when isLeaf
is False, and both are accepted in the answer.
A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:
\n\nval
: True if the node represents a grid of 1's or False if the node represents a grid of 0's.isLeaf
: True if the node is leaf node on the tree or False if the node has the four children.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}\n\n
We can construct a Quad-Tree from a two-dimensional area using the following steps:
\n\n1's
or all 0's
) set isLeaf
True and set val
to the value of the grid and set the four children to Null and stop.isLeaf
to False and set val
to any value and divide the current grid into four sub-grids as shown in the photo.If you want to know more about the Quad-Tree, you can refer to the wiki.
\n\nQuad-Tree format:
\n\nThe input/output represents the serialized format of a Quad-Tree using level order traversal, where null
signifies a path terminator where no node exists below.
It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val]
.
If the value of isLeaf
or val
is True we represent it as 1 in the list [isLeaf, val]
and if the value of isLeaf
or val
is False we represent it as 0.
\n
Example 1:
\n\nInput: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]\n, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nOutput: [[0,0],[1,1],[1,1],[1,1],[1,0]]\nExplanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.\nIf we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.\nNotice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.\n\n\n\n
Example 2:
\n\n\nInput: quadTree1 = [[1,0]], quadTree2 = [[1,0]]\nOutput: [[1,0]]\nExplanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.\nThe resulting matrix is of size 1*1 with also zero.\n\n\n
\n
Constraints:
\n\nquadTree1
and quadTree2
are both valid Quad-Trees each representing a n * n
grid.n == 2x
where 0 <= x <= 9
.Given a n-ary tree, find its maximum depth.
\n\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
\n\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
\n\n\n
Example 1:
\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: 3\n\n\n
Example 2:
\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: 5\n\n\n
\n
Constraints:
\n\n[0, 104]
.1000
.Given an array of integers nums
and an integer k
, return the total number of subarrays whose sum equals to k
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\nInput: nums = [1,1,1], k = 2\nOutput: 2\n
Example 2:
\nInput: nums = [1,2,3], k = 3\nOutput: 2\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
Given an integer array nums
of 2n
integers, group these integers into n
pairs (a1, b1), (a2, b2), ..., (an, bn)
such that the sum of min(ai, bi)
for all i
is maximized. Return the maximized sum.
\n
Example 1:
\n\n\nInput: nums = [1,4,3,2]\nOutput: 4\nExplanation: All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.\n\n
Example 2:
\n\n\nInput: nums = [6,2,6,5,1,2]\nOutput: 9\nExplanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
nums.length == 2 * n
-104 <= nums[i] <= 104
Given the root
of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0
. The rule is similar if the node does not have a right child.
\n
Example 1:
\n\nInput: root = [1,2,3]\nOutput: 1\nExplanation: \nTilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1\n\n\n
Example 2:
\n\nInput: root = [4,2,9,3,5,null,7]\nOutput: 15\nExplanation: \nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\n\n\n
Example 3:
\n\nInput: root = [21,7,14,1,1,2,2,3,3]\nOutput: 9\n\n\n
\n
Constraints:
\n\n[0, 104]
.-1000 <= Node.val <= 1000
Given a string n
representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
\n\n\n
Example 1:
\n\n\nInput: n = "123"\nOutput: "121"\n\n\n
Example 2:
\n\n\nInput: n = "1"\nOutput: "0"\nExplanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.\n\n\n
\n
Constraints:
\n\n1 <= n.length <= 18
n
consists of only digits.n
does not have leading zeros.n
is representing an integer in the range [1, 1018 - 1]
.You are given an integer array nums
of length n
where nums
is a permutation of the numbers in the range [0, n - 1]
.
You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }
subjected to the following rule:
s[k]
starts with the selection of the element nums[k]
of index = k
.s[k]
should be nums[nums[k]]
, and then nums[nums[nums[k]]]
, and so on.s[k]
.Return the longest length of a set s[k]
.
\n
Example 1:
\n\n\nInput: nums = [5,4,0,3,1,6,2]\nOutput: 4\nExplanation: \nnums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,2]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] < nums.length
nums
are unique.In MATLAB, there is a handy function called reshape
which can reshape an m x n
matrix into a new one with a different size r x c
keeping its original data.
You are given an m x n
matrix mat
and two integers r
and c
representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
\n\nIf the reshape
operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
\n
Example 1:
\n\nInput: mat = [[1,2],[3,4]], r = 1, c = 4\nOutput: [[1,2,3,4]]\n\n\n
Example 2:
\n\nInput: mat = [[1,2],[3,4]], r = 2, c = 4\nOutput: [[1,2],[3,4]]\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
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
.
\n
Example 1:
\n\n\nInput: s1 = "ab", s2 = "eidbaooo"\nOutput: true\nExplanation: s2 contains one permutation of s1 ("ba").\n\n\n
Example 2:
\n\n\nInput: s1 = "ab", s2 = "eidboaoo"\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 104
s1
and s2
consist of lowercase English letters.Table: Employee
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n| department | varchar |\n| managerId | int |\n+-------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table indicates the name of an employee, their department, and the id of their manager.\nIf managerId is null, then the employee does not have a manager.\nNo employee will be the manager of themself.\n\n\n
\n\n
Write a solution to find managers with at least five direct reports.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+-----+-------+------------+-----------+\n| id | name | department | managerId |\n+-----+-------+------------+-----------+\n| 101 | John | A | null |\n| 102 | Dan | A | 101 |\n| 103 | James | A | 101 |\n| 104 | Amy | A | 101 |\n| 105 | Anne | A | 101 |\n| 106 | Ron | B | 101 |\n+-----+-------+------------+-----------+\nOutput: \n+------+\n| name |\n+------+\n| John |\n+------+\n\n", - "likes": 1344, - "dislikes": 155, - "stats": "{\"totalAccepted\": \"582.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 582399, \"totalSubmissionRaw\": 1183387, \"acRate\": \"49.2%\"}", + "likes": 1460, + "dislikes": 162, + "stats": "{\"totalAccepted\": \"700.8K\", \"totalSubmission\": \"1.4M\", \"totalAcceptedRaw\": 700763, \"totalSubmissionRaw\": 1432425, \"acRate\": \"48.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -21487,9 +21487,9 @@ "questionFrontendId": "571", "title": "Find Median Given Frequency of Numbers", "content": null, - "likes": 310, + "likes": 313, "dislikes": 79, - "stats": "{\"totalAccepted\": \"31.7K\", \"totalSubmission\": \"74.5K\", \"totalAcceptedRaw\": 31678, \"totalSubmissionRaw\": 74533, \"acRate\": \"42.5%\"}", + "stats": "{\"totalAccepted\": \"33.2K\", \"totalSubmission\": \"78.2K\", \"totalAcceptedRaw\": 33210, \"totalSubmissionRaw\": 78211, \"acRate\": \"42.5%\"}", "similarQuestions": "[{\"title\": \"Median Employee Salary\", \"titleSlug\": \"median-employee-salary\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -21515,9 +21515,9 @@ "questionFrontendId": "572", "title": "Subtree of Another Tree", "content": "
Given the roots of two binary trees root
and subRoot
, return true
if there is a subtree of root
with the same structure and node values of subRoot
and false
otherwise.
A subtree of a binary tree tree
is a tree that consists of a node in tree
and all of this node's descendants. The tree tree
could also be considered as a subtree of itself.
\n
Example 1:
\n\nInput: root = [3,4,5,1,2], subRoot = [4,1,2]\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\nOutput: false\n\n\n
\n
Constraints:
\n\nroot
tree is in the range [1, 2000]
.subRoot
tree is in the range [1, 1000]
.-104 <= root.val <= 104
-104 <= subRoot.val <= 104
Alice has n
candies, where the ith
candy is of type candyType[i]
. Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2
of the candies she has (n
is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.
Given the integer array candyType
of length n
, return the maximum number of different types of candies she can eat if she only eats n / 2
of them.
\n
Example 1:
\n\n\nInput: candyType = [1,1,2,2,3,3]\nOutput: 3\nExplanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.\n\n\n
Example 2:
\n\n\nInput: candyType = [1,1,2,3]\nOutput: 2\nExplanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.\n\n\n
Example 3:
\n\n\nInput: candyType = [6,6,6,6]\nOutput: 1\nExplanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.\n\n\n
\n
Constraints:
\n\nn == candyType.length
2 <= n <= 104
n
is even.-105 <= candyType[i] <= 105
There is an m x n
grid with a ball. The ball is initially at the position [startRow, startColumn]
. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove
moves to the ball.
Given the five integers m
, n
, maxMove
, startRow
, startColumn
, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\nOutput: 6\n\n\n
Example 2:
\n\nInput: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\nOutput: 12\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 50
0 <= maxMove <= 50
0 <= startRow < m
0 <= startColumn < n
Table: Employee
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| empId | int |\n| name | varchar |\n| supervisor | int |\n| salary | int |\n+-------------+---------+\nempId is the column with unique values for this table.\nEach row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.\n\n\n
\n\n
Table: Bonus
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| empId | int |\n| bonus | int |\n+-------------+------+\nempId is the column of unique values for this table.\nempId is a foreign key (reference column) to empId from the Employee table.\nEach row of this table contains the id of an employee and their respective bonus.\n\n\n
\n\n
Write a solution to report the name and bonus amount of each employee with a bonus less than 1000
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+-------+--------+------------+--------+\n| empId | name | supervisor | salary |\n+-------+--------+------------+--------+\n| 3 | Brad | null | 4000 |\n| 1 | John | 3 | 1000 |\n| 2 | Dan | 3 | 2000 |\n| 4 | Thomas | 3 | 4000 |\n+-------+--------+------------+--------+\nBonus table:\n+-------+-------+\n| empId | bonus |\n+-------+-------+\n| 2 | 500 |\n| 4 | 2000 |\n+-------+-------+\nOutput: \n+------+-------+\n| name | bonus |\n+------+-------+\n| Brad | null |\n| John | null |\n| Dan | 500 |\n+------+-------+\n\n", - "likes": 1179, - "dislikes": 251, - "stats": "{\"totalAccepted\": \"624.8K\", \"totalSubmission\": \"812K\", \"totalAcceptedRaw\": 624790, \"totalSubmissionRaw\": 812048, \"acRate\": \"76.9%\"}", + "likes": 1277, + "dislikes": 264, + "stats": "{\"totalAccepted\": \"753.4K\", \"totalSubmission\": \"977.3K\", \"totalAcceptedRaw\": 753447, \"totalSubmissionRaw\": 977335, \"acRate\": \"77.1%\"}", "similarQuestions": "[{\"title\": \"Combine Two Tables\", \"titleSlug\": \"combine-two-tables\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [ @@ -21743,8 +21743,8 @@ "title": "Get Highest Answer Rate Question", "content": null, "likes": 132, - "dislikes": 916, - "stats": "{\"totalAccepted\": \"61K\", \"totalSubmission\": \"151.7K\", \"totalAcceptedRaw\": 61025, \"totalSubmissionRaw\": 151708, \"acRate\": \"40.2%\"}", + "dislikes": 917, + "stats": "{\"totalAccepted\": \"63.8K\", \"totalSubmission\": \"158.7K\", \"totalAcceptedRaw\": 63810, \"totalSubmissionRaw\": 158668, \"acRate\": \"40.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -21777,9 +21777,9 @@ "questionFrontendId": "579", "title": "Find Cumulative Salary of an Employee", "content": null, - "likes": 244, + "likes": 246, "dislikes": 404, - "stats": "{\"totalAccepted\": \"38.4K\", \"totalSubmission\": \"79.6K\", \"totalAcceptedRaw\": 38396, \"totalSubmissionRaw\": 79638, \"acRate\": \"48.2%\"}", + "stats": "{\"totalAccepted\": \"40.4K\", \"totalSubmission\": \"82.5K\", \"totalAcceptedRaw\": 40370, \"totalSubmissionRaw\": 82536, \"acRate\": \"48.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -21812,9 +21812,9 @@ "questionFrontendId": "580", "title": "Count Student Number in Departments", "content": null, - "likes": 249, - "dislikes": 36, - "stats": "{\"totalAccepted\": \"71.8K\", \"totalSubmission\": \"120.6K\", \"totalAcceptedRaw\": 71803, \"totalSubmissionRaw\": 120568, \"acRate\": \"59.6%\"}", + "likes": 251, + "dislikes": 37, + "stats": "{\"totalAccepted\": \"74.1K\", \"totalSubmission\": \"124K\", \"totalAcceptedRaw\": 74079, \"totalSubmissionRaw\": 124005, \"acRate\": \"59.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -21846,10 +21846,10 @@ "questionFrontendId": "581", "title": "Shortest Unsorted Continuous Subarray", "content": "
Given an integer array nums
, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.
Return the shortest such subarray and output its length.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,6,4,8,10,9,15]\nOutput: 5\nExplanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: nums = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-105 <= nums[i] <= 105
\nFollow up: Can you solve it in
O(n)
time complexity?",
- "likes": 7833,
- "dislikes": 268,
- "stats": "{\"totalAccepted\": \"348.5K\", \"totalSubmission\": \"936.2K\", \"totalAcceptedRaw\": 348495, \"totalSubmissionRaw\": 936172, \"acRate\": \"37.2%\"}",
- "similarQuestions": "[]",
+ "likes": 7874,
+ "dislikes": 272,
+ "stats": "{\"totalAccepted\": \"359.4K\", \"totalSubmission\": \"960.3K\", \"totalAcceptedRaw\": 359419, \"totalSubmissionRaw\": 960290, \"acRate\": \"37.4%\"}",
+ "similarQuestions": "[{\"title\": \"Smallest Subarray to Sort in Every Sliding Window\", \"titleSlug\": \"smallest-subarray-to-sort-in-every-sliding-window\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
"topicTags": [
@@ -21892,9 +21892,9 @@
"questionFrontendId": "582",
"title": "Kill Process",
"content": null,
- "likes": 1119,
+ "likes": 1122,
"dislikes": 21,
- "stats": "{\"totalAccepted\": \"90.9K\", \"totalSubmission\": \"130K\", \"totalAcceptedRaw\": 90882, \"totalSubmissionRaw\": 129996, \"acRate\": \"69.9%\"}",
+ "stats": "{\"totalAccepted\": \"92.4K\", \"totalSubmission\": \"131.9K\", \"totalAcceptedRaw\": 92444, \"totalSubmissionRaw\": 131936, \"acRate\": \"70.1%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -21935,9 +21935,9 @@
"questionFrontendId": "583",
"title": "Delete Operation for Two Strings",
"content": "Given two strings word1
and word2
, return the minimum number of steps required to make word1
and word2
the same.
In one step, you can delete exactly one character in either string.
\n\n\n
Example 1:
\n\n\nInput: word1 = "sea", word2 = "eat"\nOutput: 2\nExplanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".\n\n\n
Example 2:
\n\n\nInput: word1 = "leetcode", word2 = "etco"\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 500
word1
and word2
consist of only lowercase English letters.Table: Customer
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| name | varchar |\n| referee_id | int |\n+-------------+---------+\nIn SQL, id is the primary key column for this table.\nEach row of this table indicates the id of a customer, their name, and the id of the customer who referred them.\n\n\n
\n\n
Find the names of the customer that are not referred by the customer with id = 2
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCustomer table:\n+----+------+------------+\n| id | name | referee_id |\n+----+------+------------+\n| 1 | Will | null |\n| 2 | Jane | null |\n| 3 | Alex | 2 |\n| 4 | Bill | null |\n| 5 | Zack | 1 |\n| 6 | Mark | 2 |\n+----+------+------------+\nOutput: \n+------+\n| name |\n+------+\n| Will |\n| Jane |\n| Bill |\n| Zack |\n+------+\n\n", - "likes": 2402, - "dislikes": 386, - "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"1.9M\", \"totalAcceptedRaw\": 1375951, \"totalSubmissionRaw\": 1924277, \"acRate\": \"71.5%\"}", + "likes": 2578, + "dislikes": 397, + "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1604660, \"totalSubmissionRaw\": 2237493, \"acRate\": \"71.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22002,9 +22002,9 @@ "questionFrontendId": "585", "title": "Investments in 2016", "content": "
Table: Insurance
\n+-------------+-------+\n| Column Name | Type |\n+-------------+-------+\n| pid | int |\n| tiv_2015 | float |\n| tiv_2016 | float |\n| lat | float |\n| lon | float |\n+-------------+-------+\npid is the primary key (column with unique values) for this table.\nEach row of this table contains information about one policy where:\npid is the policyholder's policy ID.\ntiv_2015 is the total investment value in 2015 and tiv_2016 is the total investment value in 2016.\nlat is the latitude of the policy holder's city. It's guaranteed that lat is not NULL.\nlon is the longitude of the policy holder's city. It's guaranteed that lon is not NULL.\n\n\n
\n\n
Write a solution to report the sum of all total investment values in 2016 tiv_2016
, for all policyholders who:
tiv_2015
value as one or more other policyholders, andlat, lon
) attribute pairs must be unique).Round tiv_2016
to two decimal places.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nInsurance table:\n+-----+----------+----------+-----+-----+\n| pid | tiv_2015 | tiv_2016 | lat | lon |\n+-----+----------+----------+-----+-----+\n| 1 | 10 | 5 | 10 | 10 |\n| 2 | 20 | 20 | 20 | 20 |\n| 3 | 10 | 30 | 20 | 20 |\n| 4 | 10 | 40 | 40 | 40 |\n+-----+----------+----------+-----+-----+\nOutput: \n+----------+\n| tiv_2016 |\n+----------+\n| 45.00 |\n+----------+\nExplanation: \nThe first record in the table, like the last record, meets both of the two criteria.\nThe tiv_2015 value 10 is the same as the third and fourth records, and its location is unique.\n\nThe second record does not meet any of the two criteria. Its tiv_2015 is not like any other policyholders and its location is the same as the third record, which makes the third record fail, too.\nSo, the result is the sum of tiv_2016 of the first and last record, which is 45.\n\n", - "likes": 679, - "dislikes": 552, - "stats": "{\"totalAccepted\": \"177.5K\", \"totalSubmission\": \"357.7K\", \"totalAcceptedRaw\": 177501, \"totalSubmissionRaw\": 357666, \"acRate\": \"49.6%\"}", + "likes": 738, + "dislikes": 576, + "stats": "{\"totalAccepted\": \"214.3K\", \"totalSubmission\": \"428K\", \"totalAcceptedRaw\": 214332, \"totalSubmissionRaw\": 428032, \"acRate\": \"50.1%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22035,9 +22035,9 @@ "questionFrontendId": "586", "title": "Customer Placing the Largest Number of Orders", "content": "
Table: Orders
\n+-----------------+----------+\n| Column Name | Type |\n+-----------------+----------+\n| order_number | int |\n| customer_number | int |\n+-----------------+----------+\norder_number is the primary key (column with unique values) for this table.\nThis table contains information about the order ID and the customer ID.\n\n\n
\n\n
Write a solution to find the customer_number
for the customer who has placed the largest number of orders.
The test cases are generated so that exactly one customer will have placed more orders than any other customer.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nOrders table:\n+--------------+-----------------+\n| order_number | customer_number |\n+--------------+-----------------+\n| 1 | 1 |\n| 2 | 2 |\n| 3 | 3 |\n| 4 | 3 |\n+--------------+-----------------+\nOutput: \n+-----------------+\n| customer_number |\n+-----------------+\n| 3 |\n+-----------------+\nExplanation: \nThe customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. \nSo the result is customer_number 3.\n\n\n
\n
Follow up: What if more than one customer has the largest number of orders, can you find all the customer_number
in this case?
You are given an array trees
where trees[i] = [xi, yi]
represents the location of a tree in the garden.
Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed.
\n\nReturn the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.
\n\n\n
Example 1:
\n\nInput: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\nOutput: [[1,1],[2,0],[4,2],[3,3],[2,4]]\nExplanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.\n\n\n
Example 2:
\n\nInput: trees = [[1,2],[2,2],[4,2]]\nOutput: [[4,2],[2,2],[1,2]]\nExplanation: The fence forms a line that passes through all the trees.\n\n\n
\n
Constraints:
\n\n1 <= trees.length <= 3000
trees[i].length == 2
0 <= xi, yi <= 100
Given the root
of an n-ary tree, return the preorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
\n\n\n
Example 1:
\n\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [1,3,5,6,2,4]\n\n\n
Example 2:
\n\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n\n\n
\n
Constraints:
\n\n[0, 104]
.0 <= Node.val <= 104
1000
.\n
Follow up: Recursive solution is trivial, could you do it iteratively?
\n", - "likes": 3197, + "likes": 3219, "dislikes": 203, - "stats": "{\"totalAccepted\": \"454.6K\", \"totalSubmission\": \"598.1K\", \"totalAcceptedRaw\": 454575, \"totalSubmissionRaw\": 598059, \"acRate\": \"76.0%\"}", + "stats": "{\"totalAccepted\": \"467.2K\", \"totalSubmission\": \"613K\", \"totalAcceptedRaw\": 467226, \"totalSubmissionRaw\": 612983, \"acRate\": \"76.2%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Preorder Traversal\", \"titleSlug\": \"binary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Level Order Traversal\", \"titleSlug\": \"n-ary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Postorder Traversal\", \"titleSlug\": \"n-ary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -22185,9 +22185,9 @@ "questionFrontendId": "590", "title": "N-ary Tree Postorder Traversal", "content": "Given the root
of an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
\n\n\n
Example 1:
\n\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [5,6,3,2,4,1]\n\n\n
Example 2:
\n\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n\n\n
\n
Constraints:
\n\n[0, 104]
.0 <= Node.val <= 104
1000
.\n
Follow up: Recursive solution is trivial, could you do it iteratively?
\n", - "likes": 2694, + "likes": 2712, "dislikes": 119, - "stats": "{\"totalAccepted\": \"389.7K\", \"totalSubmission\": \"483.9K\", \"totalAcceptedRaw\": 389676, \"totalSubmissionRaw\": 483871, \"acRate\": \"80.5%\"}", + "stats": "{\"totalAccepted\": \"401.6K\", \"totalSubmission\": \"497.7K\", \"totalAcceptedRaw\": 401576, \"totalSubmissionRaw\": 497743, \"acRate\": \"80.7%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Postorder Traversal\", \"titleSlug\": \"binary-tree-postorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Level Order Traversal\", \"titleSlug\": \"n-ary-tree-level-order-traversal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"N-ary Tree Preorder Traversal\", \"titleSlug\": \"n-ary-tree-preorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -22223,8 +22223,8 @@ "title": "Tag Validator", "content": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.
\n\nA code snippet is valid if all the following rules hold:
\n\n<TAG_NAME>TAG_CONTENT</TAG_NAME>
. Among them, <TAG_NAME>
is the start tag, and </TAG_NAME>
is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.TAG_NAME
only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME
is invalid.TAG_CONTENT
may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <
, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT
is invalid.<
is unmatched if you cannot find a subsequent >
. And when you find a <
or </
, all the subsequent characters until the next >
should be parsed as TAG_NAME (not necessarily valid).<![CDATA[CDATA_CONTENT]]>
. The range of CDATA_CONTENT
is defined as the characters between <![CDATA[
and the first subsequent ]]>
.CDATA_CONTENT
may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT
, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.\n
Example 1:
\n\n\nInput: code = "<DIV>This is the first line <![CDATA[<div>]]></DIV>"\nOutput: true\nExplanation: \nThe code is wrapped in a closed tag : <DIV> and </DIV>. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.\n\n\n
Example 2:
\n\n\nInput: code = "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>"\nOutput: true\nExplanation:\nWe first separate the code into : start_tag|tag_content|end_tag.\nstart_tag -> "<DIV>"\nend_tag -> "</DIV>"\ntag_content could also be separated into : text1|cdata|text2.\ntext1 -> ">> ![cdata[]] "\ncdata -> "<![CDATA[<div>]>]]>", where the CDATA_CONTENT is "<div>]>"\ntext2 -> "]]>>]"\nThe reason why start_tag is NOT "<DIV>>>" is because of the rule 6.\nThe reason why cdata is NOT "<![CDATA[<div>]>]]>]]>" is because of the rule 7.\n\n\n
Example 3:
\n\n\nInput: code = "<A> <B> </A> </B>"\nOutput: false\nExplanation: Unbalanced. If "<A>" is closed, then "<B>" must be unmatched, and vice versa.\n\n\n
\n
Constraints:
\n\n1 <= code.length <= 500
code
consists of English letters, digits, '<'
, '>'
, '/'
, '!'
, '['
, ']'
, '.'
, and ' '
.Given a string expression
representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1
. So in this case, 2
should be converted to 2/1
.
\n
Example 1:
\n\n\nInput: expression = "-1/2+1/2"\nOutput: "0/1"\n\n\n
Example 2:
\n\n\nInput: expression = "-1/2+1/2+1/3"\nOutput: "1/3"\n\n\n
Example 3:
\n\n\nInput: expression = "1/3-1/2"\nOutput: "-1/6"\n\n\n
\n
Constraints:
\n\n'0'
to '9'
, '/'
, '+'
and '-'
. So does the output.±numerator/denominator
. If the first input fraction or the output is positive, then '+'
will be omitted.[1, 10]
. If the denominator is 1
, it means this fraction is actually an integer in a fraction format defined above.[1, 10]
.Given the coordinates of four points in 2D space p1
, p2
, p3
and p4
, return true
if the four points construct a square.
The coordinate of a point pi
is represented as [xi, yi]
. The input is not given in any order.
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
\n\n\n
Example 1:
\n\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\nOutput: true\n\n\n
Example 2:
\n\n\nInput: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\nOutput: true\n\n\n
\n
Constraints:
\n\np1.length == p2.length == p3.length == p4.length == 2
-104 <= xi, yi <= 104
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1
.
Given an integer array nums
, return the length of its longest harmonious subsequence among all its possible subsequences.
\n
Example 1:
\n\nInput: nums = [1,3,2,2,5,2,3,7]
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest harmonious subsequence is [3,2,2,2,3]
.
Example 2:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 2
\n\nExplanation:
\n\nThe longest harmonious subsequences are [1,2]
, [2,3]
, and [3,4]
, all of which have a length of 2.
Example 3:
\n\nInput: nums = [1,1,1,1]
\n\nOutput: 0
\n\nExplanation:
\n\nNo harmonic subsequence exists.
\n\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109
Table: World
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| name | varchar |\n| continent | varchar |\n| area | int |\n| population | int |\n| gdp | bigint |\n+-------------+---------+\nname is the primary key (column with unique values) for this table.\nEach row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.\n\n\n
\n\n
A country is big if:
\n\n3000000 km2
), or25000000
).Write a solution to find the name, population, and area of the big countries.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nWorld table:\n+-------------+-----------+---------+------------+--------------+\n| name | continent | area | population | gdp |\n+-------------+-----------+---------+------------+--------------+\n| Afghanistan | Asia | 652230 | 25500100 | 20343000000 |\n| Albania | Europe | 28748 | 2831741 | 12960000000 |\n| Algeria | Africa | 2381741 | 37100000 | 188681000000 |\n| Andorra | Europe | 468 | 78115 | 3712000000 |\n| Angola | Africa | 1246700 | 20609294 | 100990000000 |\n+-------------+-----------+---------+------------+--------------+\nOutput: \n+-------------+------------+---------+\n| name | population | area |\n+-------------+------------+---------+\n| Afghanistan | 25500100 | 652230 |\n| Algeria | 37100000 | 2381741 |\n+-------------+------------+---------+\n\n", - "likes": 2931, - "dislikes": 1341, - "stats": "{\"totalAccepted\": \"1.7M\", \"totalSubmission\": \"2.4M\", \"totalAcceptedRaw\": 1652468, \"totalSubmissionRaw\": 2423499, \"acRate\": \"68.2%\"}", + "likes": 3056, + "dislikes": 1353, + "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"2.7M\", \"totalAcceptedRaw\": 1870360, \"totalSubmissionRaw\": 2742857, \"acRate\": \"68.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -22399,11 +22399,11 @@ "question": { "questionId": "596", "questionFrontendId": "596", - "title": "Classes More Than 5 Students", + "title": "Classes With at Least 5 Students", "content": "
Table: Courses
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| student | varchar |\n| class | varchar |\n+-------------+---------+\n(student, class) is the primary key (combination of columns with unique values) for this table.\nEach row of this table indicates the name of a student and the class in which they are enrolled.\n\n\n
\n\n
Write a solution to find all the classes that have at least five students.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCourses table:\n+---------+----------+\n| student | class |\n+---------+----------+\n| A | Math |\n| B | English |\n| C | Math |\n| D | Biology |\n| E | Math |\n| F | Computer |\n| G | Math |\n| H | Math |\n| I | Math |\n+---------+----------+\nOutput: \n+---------+\n| class |\n+---------+\n| Math |\n+---------+\nExplanation: \n- Math has 6 students, so we include it.\n- English has 1 student, so we do not include it.\n- Biology has 1 student, so we do not include it.\n- Computer has 1 student, so we do not include it.\n\n", - "likes": 1122, - "dislikes": 1078, - "stats": "{\"totalAccepted\": \"564.5K\", \"totalSubmission\": \"952.4K\", \"totalAcceptedRaw\": 564454, \"totalSubmissionRaw\": 952434, \"acRate\": \"59.3%\"}", + "likes": 1177, + "dislikes": 1081, + "stats": "{\"totalAccepted\": \"642.6K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 642558, \"totalSubmissionRaw\": 1058976, \"acRate\": \"60.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -22421,7 +22421,7 @@ }, "hasSolution": true, "hasVideoSolution": false, - "url": "https://leetcode.com/problems/classes-more-than-5-students/" + "url": "https://leetcode.com/problems/classes-with-at-least-5-students/" } } }, @@ -22432,9 +22432,9 @@ "questionFrontendId": "597", "title": "Friend Requests I: Overall Acceptance Rate", "content": null, - "likes": 310, - "dislikes": 770, - "stats": "{\"totalAccepted\": \"79.9K\", \"totalSubmission\": \"192.2K\", \"totalAcceptedRaw\": 79860, \"totalSubmissionRaw\": 192167, \"acRate\": \"41.6%\"}", + "likes": 315, + "dislikes": 772, + "stats": "{\"totalAccepted\": \"82.3K\", \"totalSubmission\": \"198.9K\", \"totalAcceptedRaw\": 82340, \"totalSubmissionRaw\": 198949, \"acRate\": \"41.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22466,9 +22466,9 @@ "questionFrontendId": "598", "title": "Range Addition II", "content": "
You are given an m x n
matrix M
initialized with all 0
's and an array of operations ops
, where ops[i] = [ai, bi]
means M[x][y]
should be incremented by one for all 0 <= x < ai
and 0 <= y < bi
.
Count and return the number of maximum integers in the matrix after performing all the operations.
\n\n\n
Example 1:
\n\nInput: m = 3, n = 3, ops = [[2,2],[3,3]]\nOutput: 4\nExplanation: The maximum integer in M is 2, and there are four of it in M. So return 4.\n\n\n
Example 2:
\n\n\nInput: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\nOutput: 4\n\n\n
Example 3:
\n\n\nInput: m = 3, n = 3, ops = []\nOutput: 9\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 4 * 104
0 <= ops.length <= 104
ops[i].length == 2
1 <= ai <= m
1 <= bi <= n
Given two arrays of strings list1
and list2
, find the common strings with the least index sum.
A common string is a string that appeared in both list1
and list2
.
A common string with the least index sum is a common string such that if it appeared at list1[i]
and list2[j]
then i + j
should be the minimum value among all the other common strings.
Return all the common strings with the least index sum. Return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]\nOutput: ["Shogun"]\nExplanation: The only common string is "Shogun".\n\n\n
Example 2:
\n\n\nInput: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]\nOutput: ["Shogun"]\nExplanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1.\n\n\n
Example 3:
\n\n\nInput: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"]\nOutput: ["sad","happy"]\nExplanation: There are three common strings:\n"happy" with index sum = (0 + 1) = 1.\n"sad" with index sum = (1 + 0) = 1.\n"good" with index sum = (2 + 2) = 4.\nThe strings with the least index sum are "sad" and "happy".\n\n\n
\n
Constraints:
\n\n1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i]
and list2[i]
consist of spaces ' '
and English letters.list1
are unique.list2
are unique.list1
and list2
.Given a positive integer n
, return the number of the integers in the range [0, n]
whose binary representations do not contain consecutive ones.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: 5\nExplanation:\nHere are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: n = 2\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
Table: Stadium
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| visit_date | date |\n| people | int |\n+---------------+---------+\nvisit_date is the column with unique values for this table.\nEach row of this table contains the visit date and visit id to the stadium with the number of people during the visit.\nAs the id increases, the date increases as well.\n\n\n
\n\n
Write a solution to display the records with three or more rows with consecutive id
's, and the number of people is greater than or equal to 100 for each.
Return the result table ordered by visit_date
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nStadium table:\n+------+------------+-----------+\n| id | visit_date | people |\n+------+------------+-----------+\n| 1 | 2017-01-01 | 10 |\n| 2 | 2017-01-02 | 109 |\n| 3 | 2017-01-03 | 150 |\n| 4 | 2017-01-04 | 99 |\n| 5 | 2017-01-05 | 145 |\n| 6 | 2017-01-06 | 1455 |\n| 7 | 2017-01-07 | 199 |\n| 8 | 2017-01-09 | 188 |\n+------+------------+-----------+\nOutput: \n+------+------------+-----------+\n| id | visit_date | people |\n+------+------------+-----------+\n| 5 | 2017-01-05 | 145 |\n| 6 | 2017-01-06 | 1455 |\n| 7 | 2017-01-07 | 199 |\n| 8 | 2017-01-09 | 188 |\n+------+------------+-----------+\nExplanation: \nThe four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has >= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7.\nThe rows with ids 2 and 3 are not included because we need at least three consecutive ids.\n\n", - "likes": 727, + "likes": 757, "dislikes": 572, - "stats": "{\"totalAccepted\": \"120.6K\", \"totalSubmission\": \"244.1K\", \"totalAcceptedRaw\": 120611, \"totalSubmissionRaw\": 244092, \"acRate\": \"49.4%\"}", + "stats": "{\"totalAccepted\": \"132.3K\", \"totalSubmission\": \"265.9K\", \"totalAcceptedRaw\": 132309, \"totalSubmissionRaw\": 265908, \"acRate\": \"49.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -22599,9 +22599,9 @@ "questionFrontendId": "602", "title": "Friend Requests II: Who Has the Most Friends", "content": "
Table: RequestAccepted
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| requester_id | int |\n| accepter_id | int |\n| accept_date | date |\n+----------------+---------+\n(requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table.\nThis table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.\n\n\n
\n\n
Write a solution to find the people who have the most friends and the most friends number.
\n\nThe test cases are generated so that only one person has the most friends.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nRequestAccepted table:\n+--------------+-------------+-------------+\n| requester_id | accepter_id | accept_date |\n+--------------+-------------+-------------+\n| 1 | 2 | 2016/06/03 |\n| 1 | 3 | 2016/06/08 |\n| 2 | 3 | 2016/06/08 |\n| 3 | 4 | 2016/06/09 |\n+--------------+-------------+-------------+\nOutput: \n+----+-----+\n| id | num |\n+----+-----+\n| 3 | 3 |\n+----+-----+\nExplanation: \nThe person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others.\n\n\n
\n
Follow up: In the real world, multiple people could have the same most number of friends. Could you find all these people in this case?
\n", - "likes": 744, - "dislikes": 135, - "stats": "{\"totalAccepted\": \"205.2K\", \"totalSubmission\": \"342.9K\", \"totalAcceptedRaw\": 205154, \"totalSubmissionRaw\": 342926, \"acRate\": \"59.8%\"}", + "likes": 802, + "dislikes": 140, + "stats": "{\"totalAccepted\": \"244.7K\", \"totalSubmission\": \"402K\", \"totalAcceptedRaw\": 244664, \"totalSubmissionRaw\": 402003, \"acRate\": \"60.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22632,9 +22632,9 @@ "questionFrontendId": "603", "title": "Consecutive Available Seats", "content": null, - "likes": 646, - "dislikes": 78, - "stats": "{\"totalAccepted\": \"93.4K\", \"totalSubmission\": \"142.4K\", \"totalAcceptedRaw\": 93363, \"totalSubmissionRaw\": 142410, \"acRate\": \"65.6%\"}", + "likes": 650, + "dislikes": 80, + "stats": "{\"totalAccepted\": \"96.9K\", \"totalSubmission\": \"148.2K\", \"totalAcceptedRaw\": 96917, \"totalSubmissionRaw\": 148238, \"acRate\": \"65.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -22663,9 +22663,9 @@ "questionFrontendId": "604", "title": "Design Compressed String Iterator", "content": null, - "likes": 447, - "dislikes": 165, - "stats": "{\"totalAccepted\": \"35.9K\", \"totalSubmission\": \"89.6K\", \"totalAcceptedRaw\": 35877, \"totalSubmissionRaw\": 89571, \"acRate\": \"40.1%\"}", + "likes": 451, + "dislikes": 166, + "stats": "{\"totalAccepted\": \"37.2K\", \"totalSubmission\": \"92.6K\", \"totalAcceptedRaw\": 37199, \"totalSubmissionRaw\": 92575, \"acRate\": \"40.2%\"}", "similarQuestions": "[{\"title\": \"LRU Cache\", \"titleSlug\": \"lru-cache\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"String Compression\", \"titleSlug\": \"string-compression\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -22703,9 +22703,9 @@ "questionFrontendId": "605", "title": "Can Place Flowers", "content": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.
\n\nGiven an integer array flowerbed
containing 0
's and 1
's, where 0
means empty and 1
means not empty, and an integer n
, return true
if n
new flowers can be planted in the flowerbed
without violating the no-adjacent-flowers rule and false
otherwise.
\n
Example 1:
\nInput: flowerbed = [1,0,0,0,1], n = 1\nOutput: true\n
Example 2:
\nInput: flowerbed = [1,0,0,0,1], n = 2\nOutput: false\n\n
\n
Constraints:
\n\n1 <= flowerbed.length <= 2 * 104
flowerbed[i]
is 0
or 1
.flowerbed
.0 <= n <= flowerbed.length
Given the root
node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:
Node Representation: Each node in the tree should be represented by its integer value.
\n\tParentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:
\n\n\tOmitting Empty Parentheses: Any empty parentheses pairs (i.e., ()
) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.
In summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately.
\n\t\n
Example 1:
\n\nInput: root = [1,2,3,4]\nOutput: "1(2(4))(3)"\nExplanation: Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the empty parenthesis pairs. And it will be "1(2(4))(3)".\n\n\n
Example 2:
\n\nInput: root = [1,2,3,null,4]\nOutput: "1(2()(4))(3)"\nExplanation: Almost the same as the first example, except the\n\n()
after2
is necessary to indicate the absence of a left child for2
and the presence of a right child.\n
\n
Constraints:
\n\n[1, 104]
.-1000 <= Node.val <= 1000
Table: SalesPerson
\n+-----------------+---------+\n| Column Name | Type |\n+-----------------+---------+\n| sales_id | int |\n| name | varchar |\n| salary | int |\n| commission_rate | int |\n| hire_date | date |\n+-----------------+---------+\nsales_id is the primary key (column with unique values) for this table.\nEach row of this table indicates the name and the ID of a salesperson alongside their salary, commission rate, and hire date.\n\n\n
\n\n
Table: Company
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| com_id | int |\n| name | varchar |\n| city | varchar |\n+-------------+---------+\ncom_id is the primary key (column with unique values) for this table.\nEach row of this table indicates the name and the ID of a company and the city in which the company is located.\n\n\n
\n\n
Table: Orders
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| order_id | int |\n| order_date | date |\n| com_id | int |\n| sales_id | int |\n| amount | int |\n+-------------+------+\norder_id is the primary key (column with unique values) for this table.\ncom_id is a foreign key (reference column) to com_id from the Company table.\nsales_id is a foreign key (reference column) to sales_id from the SalesPerson table.\nEach row of this table contains information about one order. This includes the ID of the company, the ID of the salesperson, the date of the order, and the amount paid.\n\n\n
\n\n
Write a solution to find the names of all the salespersons who did not have any orders related to the company with the name "RED".
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSalesPerson table:\n+----------+------+--------+-----------------+------------+\n| sales_id | name | salary | commission_rate | hire_date |\n+----------+------+--------+-----------------+------------+\n| 1 | John | 100000 | 6 | 4/1/2006 |\n| 2 | Amy | 12000 | 5 | 5/1/2010 |\n| 3 | Mark | 65000 | 12 | 12/25/2008 |\n| 4 | Pam | 25000 | 25 | 1/1/2005 |\n| 5 | Alex | 5000 | 10 | 2/3/2007 |\n+----------+------+--------+-----------------+------------+\nCompany table:\n+--------+--------+----------+\n| com_id | name | city |\n+--------+--------+----------+\n| 1 | RED | Boston |\n| 2 | ORANGE | New York |\n| 3 | YELLOW | Boston |\n| 4 | GREEN | Austin |\n+--------+--------+----------+\nOrders table:\n+----------+------------+--------+----------+--------+\n| order_id | order_date | com_id | sales_id | amount |\n+----------+------------+--------+----------+--------+\n| 1 | 1/1/2014 | 3 | 4 | 10000 |\n| 2 | 2/1/2014 | 4 | 5 | 5000 |\n| 3 | 3/1/2014 | 1 | 1 | 50000 |\n| 4 | 4/1/2014 | 1 | 4 | 25000 |\n+----------+------------+--------+----------+--------+\nOutput: \n+------+\n| name |\n+------+\n| Amy |\n| Mark |\n| Alex |\n+------+\nExplanation: \nAccording to orders 3 and 4 in the Orders table, it is easy to tell that only salesperson John and Pam have sales to company RED, so we report all the other names in the table salesperson.\n\n", - "likes": 1238, - "dislikes": 104, - "stats": "{\"totalAccepted\": \"259K\", \"totalSubmission\": \"393.7K\", \"totalAcceptedRaw\": 259016, \"totalSubmissionRaw\": 393668, \"acRate\": \"65.8%\"}", + "likes": 1286, + "dislikes": 107, + "stats": "{\"totalAccepted\": \"287.1K\", \"totalSubmission\": \"435.6K\", \"totalAcceptedRaw\": 287101, \"totalSubmissionRaw\": 435585, \"acRate\": \"65.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22810,9 +22810,9 @@ "questionFrontendId": "608", "title": "Tree Node", "content": "
Table: Tree
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| id | int |\n| p_id | int |\n+-------------+------+\nid is the column with unique values for this table.\nEach row of this table contains information about the id of a node and the id of its parent node in a tree.\nThe given structure is always a valid tree.\n\n\n
\n\n
Each node in the tree can be one of three types:
\n\nWrite a solution to report the type of each node in the tree.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\nInput: \nTree table:\n+----+------+\n| id | p_id |\n+----+------+\n| 1 | null |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 2 |\n| 5 | 2 |\n+----+------+\nOutput: \n+----+-------+\n| id | type |\n+----+-------+\n| 1 | Root |\n| 2 | Inner |\n| 3 | Leaf |\n| 4 | Leaf |\n| 5 | Leaf |\n+----+-------+\nExplanation: \nNode 1 is the root node because its parent node is null and it has child nodes 2 and 3.\nNode 2 is an inner node because it has parent node 1 and child node 4 and 5.\nNodes 3, 4, and 5 are leaf nodes because they have parent nodes and they do not have child nodes.\n\n\n
Example 2:
\n\nInput: \nTree table:\n+----+------+\n| id | p_id |\n+----+------+\n| 1 | null |\n+----+------+\nOutput: \n+----+-------+\n| id | type |\n+----+-------+\n| 1 | Root |\n+----+-------+\nExplanation: If there is only one node on the tree, you only need to output its root attributes.\n\n\n
\n
Note: This question is the same as 3054: Binary Tree Nodes.
\n", - "likes": 1275, - "dislikes": 127, - "stats": "{\"totalAccepted\": \"182.4K\", \"totalSubmission\": \"248.3K\", \"totalAcceptedRaw\": 182398, \"totalSubmissionRaw\": 248344, \"acRate\": \"73.4%\"}", + "likes": 1303, + "dislikes": 128, + "stats": "{\"totalAccepted\": \"195.9K\", \"totalSubmission\": \"265.3K\", \"totalAcceptedRaw\": 195931, \"totalSubmissionRaw\": 265265, \"acRate\": \"73.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [ @@ -22843,9 +22843,9 @@ "questionFrontendId": "609", "title": "Find Duplicate File in System", "content": "Given a list paths
of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
A group of duplicate files consists of at least two files that have the same content.
\n\nA single directory info string in the input list has the following format:
\n\n"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
It means there are n
files (f1.txt, f2.txt ... fn.txt)
with content (f1_content, f2_content ... fn_content)
respectively in the directory "root/d1/d2/.../dm"
. Note that n >= 1
and m >= 0
. If m = 0
, it means the directory is just the root directory.
The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
\n\n"directory_path/file_name.txt"
\n
Example 1:
\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n
Example 2:
\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n\n
\n
Constraints:
\n\n1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 3000
1 <= sum(paths[i].length) <= 5 * 105
paths[i]
consist of English letters, digits, '/'
, '.'
, '('
, ')'
, and ' '
.\n
Follow up:
\n\nTable: Triangle
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| x | int |\n| y | int |\n| z | int |\n+-------------+------+\nIn SQL, (x, y, z) is the primary key column for this table.\nEach row of this table contains the lengths of three line segments.\n\n\n
\n\n
Report for every three line segments whether they can form a triangle.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTriangle table:\n+----+----+----+\n| x | y | z |\n+----+----+----+\n| 13 | 15 | 30 |\n| 10 | 20 | 15 |\n+----+----+----+\nOutput: \n+----+----+----+----------+\n| x | y | z | triangle |\n+----+----+----+----------+\n| 13 | 15 | 30 | No |\n| 10 | 20 | 15 | Yes |\n+----+----+----+----------+\n\n", - "likes": 662, - "dislikes": 192, - "stats": "{\"totalAccepted\": \"284.4K\", \"totalSubmission\": \"388.7K\", \"totalAcceptedRaw\": 284361, \"totalSubmissionRaw\": 388714, \"acRate\": \"73.2%\"}", + "likes": 713, + "dislikes": 215, + "stats": "{\"totalAccepted\": \"338.7K\", \"totalSubmission\": \"459.8K\", \"totalAcceptedRaw\": 338734, \"totalSubmissionRaw\": 459804, \"acRate\": \"73.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -22911,9 +22911,9 @@ "questionFrontendId": "611", "title": "Valid Triangle Number", "content": "
Given an integer array nums
, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
\n
Example 1:
\n\n\nInput: nums = [2,2,3,4]\nOutput: 3\nExplanation: Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3\n\n\n
Example 2:
\n\n\nInput: nums = [4,2,3,4]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] <= 1000
You are given two binary trees root1
and root2
.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
\n\nReturn the merged tree.
\n\nNote: The merging process must start from the root nodes of both trees.
\n\n\n
Example 1:
\n\nInput: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\nOutput: [3,4,5,5,4,null,7]\n\n\n
Example 2:
\n\n\nInput: root1 = [1], root2 = [1,2]\nOutput: [2,2]\n\n\n
\n
Constraints:
\n\n[0, 2000]
.-104 <= Node.val <= 104
Table: MyNumbers
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| num | int |\n+-------------+------+\nThis table may contain duplicates (In other words, there is no primary key for this table in SQL).\nEach row of this table contains an integer.\n\n\n
\n\n
A single number is a number that appeared only once in the MyNumbers
table.
Find the largest single number. If there is no single number, report null
.
The result format is in the following example.
\n\n
Example 1:
\n\n\nInput: \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8 |\n| 8 |\n| 3 |\n| 3 |\n| 1 |\n| 4 |\n| 5 |\n| 6 |\n+-----+\nOutput: \n+-----+\n| num |\n+-----+\n| 6 |\n+-----+\nExplanation: The single numbers are 1, 4, 5, and 6.\nSince 6 is the largest single number, we return it.\n\n\n
Example 2:
\n\n\nInput: \nMyNumbers table:\n+-----+\n| num |\n+-----+\n| 8 |\n| 8 |\n| 7 |\n| 7 |\n| 3 |\n| 3 |\n| 3 |\n+-----+\nOutput: \n+------+\n| num |\n+------+\n| null |\n+------+\nExplanation: There are no single numbers in the input table so we return null.\n\n", - "likes": 741, - "dislikes": 185, - "stats": "{\"totalAccepted\": \"327K\", \"totalSubmission\": \"480K\", \"totalAcceptedRaw\": 327021, \"totalSubmissionRaw\": 479954, \"acRate\": \"68.1%\"}", + "likes": 796, + "dislikes": 194, + "stats": "{\"totalAccepted\": \"391.9K\", \"totalSubmission\": \"563.7K\", \"totalAcceptedRaw\": 391916, \"totalSubmissionRaw\": 563660, \"acRate\": \"69.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -23220,9 +23220,9 @@ "questionFrontendId": "620", "title": "Not Boring Movies", "content": "
Table: Cinema
\n+----------------+----------+\n| Column Name | Type |\n+----------------+----------+\n| id | int |\n| movie | varchar |\n| description | varchar |\n| rating | float |\n+----------------+----------+\nid is the primary key (column with unique values) for this table.\nEach row contains information about the name of a movie, its genre, and its rating.\nrating is a 2 decimal places float in the range [0, 10]\n\n\n
\n\n
Write a solution to report the movies with an odd-numbered ID and a description that is not "boring"
.
Return the result table ordered by rating
in descending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCinema table:\n+----+------------+-------------+--------+\n| id | movie | description | rating |\n+----+------------+-------------+--------+\n| 1 | War | great 3D | 8.9 |\n| 2 | Science | fiction | 8.5 |\n| 3 | irish | boring | 6.2 |\n| 4 | Ice song | Fantacy | 8.6 |\n| 5 | House card | Interesting | 9.1 |\n+----+------------+-------------+--------+\nOutput: \n+----+------------+-------------+--------+\n| id | movie | description | rating |\n+----+------------+-------------+--------+\n| 5 | House card | Interesting | 9.1 |\n| 1 | War | great 3D | 8.9 |\n+----+------------+-------------+--------+\nExplanation: \nWe have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.\n\n", - "likes": 1247, - "dislikes": 547, - "stats": "{\"totalAccepted\": \"710.3K\", \"totalSubmission\": \"950.4K\", \"totalAcceptedRaw\": 710294, \"totalSubmissionRaw\": 950397, \"acRate\": \"74.7%\"}", + "likes": 1313, + "dislikes": 550, + "stats": "{\"totalAccepted\": \"819.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 819848, \"totalSubmissionRaw\": 1094176, \"acRate\": \"74.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -23251,9 +23251,9 @@ "questionFrontendId": "621", "title": "Task Scheduler", "content": "
You are given an array of CPU tasks
, each labeled with a letter from A to Z, and a number n
. Each CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order, but there's a constraint: there has to be a gap of at least n
intervals between two tasks with the same label.
Return the minimum number of CPU intervals required to complete all tasks.
\n\n\n
Example 1:
\n\nInput: tasks = ["A","A","A","B","B","B"], n = 2
\n\nOutput: 8
\n\nExplanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.
\n\nAfter completing task A, you must wait two intervals before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can do A again as 2 intervals have passed.
\nExample 2:
\n\nInput: tasks = ["A","C","A","B","D","B"], n = 1
\n\nOutput: 6
\n\nExplanation: A possible sequence is: A -> B -> C -> D -> A -> B.
\n\nWith a cooling interval of 1, you can repeat a task after just one other task.
\nExample 3:
\n\nInput: tasks = ["A","A","A", "B","B","B"], n = 3
\n\nOutput: 10
\n\nExplanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.
\n\nThere are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.
\n\n
Constraints:
\n\n1 <= tasks.length <= 104
tasks[i]
is an uppercase English letter.0 <= n <= 100
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".
\n\nOne 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.
\n\nImplement the MyCircularQueue
class:
MyCircularQueue(k)
Initializes the object with the size of the queue to be k
.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 enQueue(int 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.boolean isEmpty()
Checks whether the circular queue is empty or not.boolean isFull()
Checks whether the circular queue is full or not.You must solve the problem without using the built-in queue data structure in your programming language.
\n\n\n
Example 1:
\n\n\nInput\n["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 3, true, true, true, 4]\n\nExplanation\nMyCircularQueue myCircularQueue = new MyCircularQueue(3);\nmyCircularQueue.enQueue(1); // return True\nmyCircularQueue.enQueue(2); // return True\nmyCircularQueue.enQueue(3); // return True\nmyCircularQueue.enQueue(4); // return False\nmyCircularQueue.Rear(); // return 3\nmyCircularQueue.isFull(); // return True\nmyCircularQueue.deQueue(); // return True\nmyCircularQueue.enQueue(4); // return True\nmyCircularQueue.Rear(); // return 4\n\n\n
\n
Constraints:
\n\n1 <= k <= 1000
0 <= value <= 1000
3000
calls will be made to enQueue
, deQueue
, Front
, Rear
, isEmpty
, and isFull
.Given the root
of a binary tree and two integers val
and depth
, add a row of nodes with value val
at the given depth depth
.
Note that the root
node is at depth 1
.
The adding rule is:
\n\ndepth
, for each not null tree node cur
at the depth depth - 1
, create two tree nodes with value val
as cur
's left subtree root and right subtree root.cur
's original left subtree should be the left subtree of the new left subtree root.cur
's original right subtree should be the right subtree of the new right subtree root.depth == 1
that means there is no depth depth - 1
at all, then create a tree node with value val
as the new root of the whole original tree, and the original tree is the new root's left subtree.\n
Example 1:
\n\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput: [4,1,1,2,null,null,6,3,1,5]\n\n\n
Example 2:
\n\nInput: root = [4,2,null,3,1], val = 1, depth = 3\nOutput: [4,2,null,1,1,3,null,null,1]\n\n\n
\n
Constraints:
\n\n[1, 104]
.[1, 104]
.-100 <= Node.val <= 100
-105 <= val <= 105
1 <= depth <= the depth of tree + 1
You are given m
arrays
, where each array is sorted in ascending order.
You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a
and b
to be their absolute difference |a - b|
.
Return the maximum distance.
\n\n\n
Example 1:
\n\n\nInput: arrays = [[1,2,3],[4,5],[1,2,3]]\nOutput: 4\nExplanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.\n\n\n
Example 2:
\n\n\nInput: arrays = [[1],[1]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == arrays.length
2 <= m <= 105
1 <= arrays[i].length <= 500
-104 <= arrays[i][j] <= 104
arrays[i]
is sorted in ascending order.105
integers in all the arrays.Table: Seat
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| student | varchar |\n+-------------+---------+\nid is the primary key (unique value) column for this table.\nEach row of this table indicates the name and the ID of a student.\nThe ID sequence always starts from 1 and increments continuously.\n\n\n
\n\n
Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.
\n\nReturn the result table ordered by id
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSeat table:\n+----+---------+\n| id | student |\n+----+---------+\n| 1 | Abbot |\n| 2 | Doris |\n| 3 | Emerson |\n| 4 | Green |\n| 5 | Jeames |\n+----+---------+\nOutput: \n+----+---------+\n| id | student |\n+----+---------+\n| 1 | Doris |\n| 2 | Abbot |\n| 3 | Green |\n| 4 | Emerson |\n| 5 | Jeames |\n+----+---------+\nExplanation: \nNote that if the number of students is odd, there is no need to change the last one's seat.\n\n", - "likes": 1596, - "dislikes": 597, - "stats": "{\"totalAccepted\": \"302.9K\", \"totalSubmission\": \"421.3K\", \"totalAcceptedRaw\": 302906, \"totalSubmissionRaw\": 421301, \"acRate\": \"71.9%\"}", + "likes": 1685, + "dislikes": 607, + "stats": "{\"totalAccepted\": \"348K\", \"totalSubmission\": \"478.9K\", \"totalAcceptedRaw\": 347992, \"totalSubmissionRaw\": 478863, \"acRate\": \"72.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -23480,9 +23480,9 @@ "questionFrontendId": "627", "title": "Swap Salary", "content": "
Table: Salary
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| id | int |\n| name | varchar |\n| sex | ENUM |\n| salary | int |\n+-------------+----------+\nid is the primary key (column with unique values) for this table.\nThe sex column is ENUM (category) value of type ('m', 'f').\nThe table contains information about an employee.\n\n\n
\n\n
Write a solution to swap all 'f'
and 'm'
values (i.e., change all 'f'
values to 'm'
and vice versa) with a single update statement and no intermediate temporary tables.
Note that you must write a single update statement, do not write any select statement for this problem.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSalary table:\n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1 | A | m | 2500 |\n| 2 | B | f | 1500 |\n| 3 | C | m | 5500 |\n| 4 | D | f | 500 |\n+----+------+-----+--------+\nOutput: \n+----+------+-----+--------+\n| id | name | sex | salary |\n+----+------+-----+--------+\n| 1 | A | f | 2500 |\n| 2 | B | m | 1500 |\n| 3 | C | f | 5500 |\n| 4 | D | m | 500 |\n+----+------+-----+--------+\nExplanation: \n(1, A) and (3, C) were changed from 'm' to 'f'.\n(2, B) and (4, D) were changed from 'f' to 'm'.\n\n", - "likes": 1768, - "dislikes": 567, - "stats": "{\"totalAccepted\": \"450.2K\", \"totalSubmission\": \"537.6K\", \"totalAcceptedRaw\": 450246, \"totalSubmissionRaw\": 537582, \"acRate\": \"83.8%\"}", + "likes": 1798, + "dislikes": 568, + "stats": "{\"totalAccepted\": \"473.3K\", \"totalSubmission\": \"563.4K\", \"totalAcceptedRaw\": 473346, \"totalSubmissionRaw\": 563416, \"acRate\": \"84.0%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -23511,9 +23511,9 @@ "questionFrontendId": "628", "title": "Maximum Product of Three Numbers", "content": "
Given an integer array nums
, find three numbers whose product is maximum and return the maximum product.
\n
Example 1:
\nInput: nums = [1,2,3]\nOutput: 6\n
Example 2:
\nInput: nums = [1,2,3,4]\nOutput: 24\n
Example 3:
\nInput: nums = [-1,-2,-3]\nOutput: -6\n\n
\n
Constraints:
\n\n3 <= nums.length <= 104
-1000 <= nums[i] <= 1000
For an integer array nums
, an inverse pair is a pair of integers [i, j]
where 0 <= i < j < nums.length
and nums[i] > nums[j]
.
Given two integers n and k, return the number of different arrays consisting of numbers from 1
to n
such that there are exactly k
inverse pairs. Since the answer can be huge, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 3, k = 0\nOutput: 1\nExplanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n\n\n
Example 2:
\n\n\nInput: n = 3, k = 1\nOutput: 2\nExplanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
0 <= k <= 1000
There are n
different online courses numbered from 1
to n
. You are given an array courses
where courses[i] = [durationi, lastDayi]
indicate that the ith
course should be taken continuously for durationi
days and must be finished before or on lastDayi
.
You will start on the 1st
day and you cannot take two or more courses simultaneously.
Return the maximum number of courses that you can take.
\n\n\n
Example 1:
\n\n\nInput: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput: 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n\n\n
Example 2:
\n\n\nInput: courses = [[1,2]]\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: courses = [[3,2],[4,3]]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= courses.length <= 104
1 <= durationi, lastDayi <= 104
You have k
lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k
lists.
We define the range [a, b]
is smaller than range [c, d]
if b - a < d - c
or a < c
if b - a == d - c
.
\n
Example 1:
\n\n\nInput: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput: [20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].\n\n\n
Example 2:
\n\n\nInput: nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput: [1,1]\n\n\n
\n
Constraints:
\n\nnums.length == k
1 <= k <= 3500
1 <= nums[i].length <= 50
-105 <= nums[i][j] <= 105
nums[i]
is sorted in non-decreasing order.Given a non-negative integer c
, decide whether there're two integers a
and b
such that a2 + b2 = c
.
\n
Example 1:
\n\n\nInput: c = 5\nOutput: true\nExplanation: 1 * 1 + 2 * 2 = 5\n\n\n
Example 2:
\n\n\nInput: c = 3\nOutput: false\n\n\n
\n
Constraints:
\n\n0 <= c <= 231 - 1
On a single-threaded CPU, we execute a program containing n
functions. Each function has a unique ID between 0
and n-1
.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
\n\nYou are given a list logs
, where logs[i]
represents the ith
log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}"
. For example, "0:start:3"
means a function call with function ID 0
started at the beginning of timestamp 3
, and "1:end:2"
means a function call with function ID 1
ended at the end of timestamp 2
. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2
time units and another call executing for 1
time unit, the exclusive time is 2 + 1 = 3
.
Return the exclusive time of each function in an array, where the value at the ith
index represents the exclusive time for the function with ID i
.
\n
Example 1:
\n\nInput: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]\nOutput: [3,4]\nExplanation:\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n\n\n
Example 2:
\n\n\nInput: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]\nOutput: [8]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n\n\n
Example 3:
\n\n\nInput: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]\nOutput: [7,1]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
1 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
"end"
log for each "start"
log.On a single-threaded CPU, we execute a program containing n
functions. Each function has a unique ID between 0
and n-1
.
Function calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.
\n\nYou are given a list logs
, where logs[i]
represents the ith
log message formatted as a string "{function_id}:{"start" | "end"}:{timestamp}"
. For example, "0:start:3"
means a function call with function ID 0
started at the beginning of timestamp 3
, and "1:end:2"
means a function call with function ID 1
ended at the end of timestamp 2
. Note that a function can be called multiple times, possibly recursively.
A function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2
time units and another call executing for 1
time unit, the exclusive time is 2 + 1 = 3
.
Return the exclusive time of each function in an array, where the value at the ith
index represents the exclusive time for the function with ID i
.
\n
Example 1:
\n\nInput: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]\nOutput: [3,4]\nExplanation:\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n\n\n
Example 2:
\n\n\nInput: n = 1, logs = ["0:start:0","0:start:2","0:end:5","0:start:6","0:end:6","0:end:7"]\nOutput: [8]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n\n\n
Example 3:
\n\n\nInput: n = 2, logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]\nOutput: [7,1]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
2 <= logs.length <= 500
0 <= function_id < n
0 <= timestamp <= 109
"end"
log for each "start"
log.root
of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5
of the actual answer will be accepted.\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\n\n\n
Example 2:
\n\nInput: root = [3,9,20,15,7]\nOutput: [3.00000,14.50000,11.00000]\n\n\n
\n
Constraints:
\n\n[1, 104]
.-231 <= Node.val <= 231 - 1
In LeetCode Store, there are n
items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.
You are given an integer array price
where price[i]
is the price of the ith
item, and an integer array needs
where needs[i]
is the number of pieces of the ith
item you want to buy.
You are also given an array special
where special[i]
is of size n + 1
where special[i][j]
is the number of pieces of the jth
item in the ith
offer and special[i][n]
(i.e., the last integer in the array) is the price of the ith
offer.
Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.
\n\n\n
Example 1:
\n\n\nInput: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput: 14\nExplanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\n\n\n
Example 2:
\n\n\nInput: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput: 11\nExplanation: The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.\n\n\n
\n
Constraints:
\n\nn == price.length == needs.length
1 <= n <= 6
0 <= price[i], needs[i] <= 10
1 <= special.length <= 100
special[i].length == n + 1
0 <= special[i][j] <= 50
special[i][j]
is non-zero for 0 <= j <= n - 1
.A message containing letters from A-Z
can be encoded into numbers using the following mapping:
\n'A' -> "1"\n'B' -> "2"\n...\n'Z' -> "26"\n\n\n
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106"
can be mapped into:
"AAJF"
with the grouping (1 1 10 6)
"KJF"
with the grouping (11 10 6)
Note that the grouping (1 11 06)
is invalid because "06"
cannot be mapped into 'F'
since "6"
is different from "06"
.
In addition to the mapping above, an encoded message may contain the '*'
character, which can represent any digit from '1'
to '9'
('0'
is excluded). For example, the encoded message "1*"
may represent any of the encoded messages "11"
, "12"
, "13"
, "14"
, "15"
, "16"
, "17"
, "18"
, or "19"
. Decoding "1*"
is equivalent to decoding any of the encoded messages it can represent.
Given a string s
consisting of digits and '*'
characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "*"\nOutput: 9\nExplanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".\nEach of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.\nHence, there are a total of 9 ways to decode "*".\n\n\n
Example 2:
\n\n\nInput: s = "1*"\nOutput: 18\nExplanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".\nEach of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").\nHence, there are a total of 9 * 2 = 18 ways to decode "1*".\n\n\n
Example 3:
\n\n\nInput: s = "2*"\nOutput: 15\nExplanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".\n"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is a digit or '*'
.Solve a given equation and return the value of 'x'
in the form of a string "x=#value"
. The equation contains only '+'
, '-'
operation, the variable 'x'
and its coefficient. You should return "No solution"
if there is no solution for the equation, or "Infinite solutions"
if there are infinite solutions for the equation.
If there is exactly one solution for the equation, we ensure that the value of 'x'
is an integer.
\n
Example 1:
\n\n\nInput: equation = "x+5-3+x=6+x-2"\nOutput: "x=2"\n\n\n
Example 2:
\n\n\nInput: equation = "x=x"\nOutput: "Infinite solutions"\n\n\n
Example 3:
\n\n\nInput: equation = "2x=x"\nOutput: "x=0"\n\n\n
\n
Constraints:
\n\n3 <= equation.length <= 1000
equation
has exactly one '='
.equation
consists of integers with an absolute value in the range [0, 100]
without any leading zeros, and the variable 'x'
.Design your implementation of the circular double-ended queue (deque).
\n\nImplement the MyCircularDeque
class:
MyCircularDeque(int k)
Initializes the deque with a maximum size of k
.boolean insertFront()
Adds an item at the front of Deque. Returns true
if the operation is successful, or false
otherwise.boolean insertLast()
Adds an item at the rear of Deque. Returns true
if the operation is successful, or false
otherwise.boolean deleteFront()
Deletes an item from the front of Deque. Returns true
if the operation is successful, or false
otherwise.boolean deleteLast()
Deletes an item from the rear of Deque. Returns true
if the operation is successful, or false
otherwise.int getFront()
Returns the front item from the Deque. Returns -1
if the deque is empty.int getRear()
Returns the last item from Deque. Returns -1
if the deque is empty.boolean isEmpty()
Returns true
if the deque is empty, or false
otherwise.boolean isFull()
Returns true
if the deque is full, or false
otherwise.\n
Example 1:
\n\n\nInput\n["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]\n[[3], [1], [2], [3], [4], [], [], [], [4], []]\nOutput\n[null, true, true, true, false, 2, true, true, true, 4]\n\nExplanation\nMyCircularDeque myCircularDeque = new MyCircularDeque(3);\nmyCircularDeque.insertLast(1); // return True\nmyCircularDeque.insertLast(2); // return True\nmyCircularDeque.insertFront(3); // return True\nmyCircularDeque.insertFront(4); // return False, the queue is full.\nmyCircularDeque.getRear(); // return 2\nmyCircularDeque.isFull(); // return True\nmyCircularDeque.deleteLast(); // return True\nmyCircularDeque.insertFront(4); // return True\nmyCircularDeque.getFront(); // return 4\n\n\n
\n
Constraints:
\n\n1 <= k <= 1000
0 <= value <= 1000
2000
calls will be made to insertFront
, insertLast
, deleteFront
, deleteLast
, getFront
, getRear
, isEmpty
, isFull
.You are given an integer array nums
consisting of n
elements, and an integer k
.
Find a contiguous subarray whose length is equal to k
that has the maximum average value and return this value. Any answer with a calculation error less than 10-5
will be accepted.
\n
Example 1:
\n\n\nInput: nums = [1,12,-5,-6,50,3], k = 4\nOutput: 12.75000\nExplanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\n\n\n
Example 2:
\n\n\nInput: nums = [5], k = 1\nOutput: 5.00000\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104
You have a set of integers s
, which originally contains all the numbers from 1
to n
. Unfortunately, due to some error, one of the numbers in s
got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums
representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
\n\n\n
Example 1:
\nInput: nums = [1,2,2,4]\nOutput: [2,3]\n
Example 2:
\nInput: nums = [1,1]\nOutput: [1,2]\n\n
\n
Constraints:
\n\n2 <= nums.length <= 104
1 <= nums[i] <= 104
You are given an array of n
pairs pairs
where pairs[i] = [lefti, righti]
and lefti < righti
.
A pair p2 = [c, d]
follows a pair p1 = [a, b]
if b < c
. A chain of pairs can be formed in this fashion.
Return the length longest chain which can be formed.
\n\nYou do not need to use up all the given intervals. You can select pairs in any order.
\n\n\n
Example 1:
\n\n\nInput: pairs = [[1,2],[2,3],[3,4]]\nOutput: 2\nExplanation: The longest chain is [1,2] -> [3,4].\n\n\n
Example 2:
\n\n\nInput: pairs = [[1,2],[7,8],[4,5]]\nOutput: 3\nExplanation: The longest chain is [1,2] -> [4,5] -> [7,8].\n\n\n
\n
Constraints:
\n\nn == pairs.length
1 <= n <= 1000
-1000 <= lefti < righti <= 1000
Given a string s
, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
\n\nA substring is a contiguous sequence of characters within the string.
\n\n\n
Example 1:
\n\n\nInput: s = "abc"\nOutput: 3\nExplanation: Three palindromic strings: "a", "b", "c".\n\n\n
Example 2:
\n\n\nInput: s = "aaa"\nOutput: 6\nExplanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of lowercase English letters.In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word derivative. For example, when the root "help"
is followed by the word "ful"
, we can form a derivative "helpful"
.
Given a dictionary
consisting of many roots and a sentence
consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.
Return the sentence
after the replacement.
\n
Example 1:
\n\n\nInput: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"\nOutput: "the cat was rat by the bat"\n\n\n
Example 2:
\n\n\nInput: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"\nOutput: "a a b c"\n\n\n
\n
Constraints:
\n\n1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i]
consists of only lower-case letters.1 <= sentence.length <= 106
sentence
consists of only lower-case letters and spaces.sentence
is in the range [1, 1000]
sentence
is in the range [1, 1000]
sentence
will be separated by exactly one space.sentence
does not have leading or trailing spaces.In the world of Dota2, there are two parties: the Radiant and the Dire.
\n\nThe Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:
\n\nGiven a string senate
representing each senator's party belonging. The character 'R'
and 'D'
represent the Radiant party and the Dire party. Then if there are n
senators, the size of the given string will be n
.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
\n\nSuppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be "Radiant"
or "Dire"
.
\n
Example 1:
\n\n\nInput: senate = "RD"\nOutput: "Radiant"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\n
Example 2:
\n\n\nInput: senate = "RDD"\nOutput: "Dire"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n\n\n
\n
Constraints:
\n\nn == senate.length
1 <= n <= 104
senate[i]
is either 'R'
or 'D'
.There is only one character 'A'
on the screen of a notepad. You can perform one of two operations on this notepad for each step:
Given an integer n
, return the minimum number of operations to get the character 'A'
exactly n
times on the screen.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 3\nExplanation: Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
Given the root
of a binary tree, return all duplicate subtrees.
For each kind of duplicate subtrees, you only need to return the root node of any one of them.
\n\nTwo trees are duplicate if they have the same structure with the same node values.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,4,null,2,4,null,null,4]\nOutput: [[2,4],[4]]\n\n\n
Example 2:
\n\nInput: root = [2,1,1]\nOutput: [[1]]\n\n\n
Example 3:
\n\nInput: root = [2,2,2,3,null,3,null]\nOutput: [[2,3],[3]]\n\n\n
\n
Constraints:
\n\n[1, 5000]
-200 <= Node.val <= 200
Given the root
of a binary search tree and an integer k
, return true
if there exist two elements in the BST such that their sum is equal to k
, or false
otherwise.
\n
Example 1:
\n\nInput: root = [5,3,6,2,4,null,7], k = 9\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [5,3,6,2,4,null,7], k = 28\nOutput: false\n\n\n
\n
Constraints:
\n\n[1, 104]
.-104 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.-105 <= k <= 105
You are given an integer array nums
with no duplicates. A maximum binary tree can be built recursively from nums
using the following algorithm:
nums
.Return the maximum binary tree built from nums
.
\n
Example 1:
\n\nInput: nums = [3,2,1,6,0,5]\nOutput: [6,3,5,null,2,0,null,null,1]\nExplanation: The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.\n\n\n
Example 2:
\n\nInput: nums = [3,2,1]\nOutput: [3,null,2,null,1]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] <= 1000
nums
are unique.Given the root
of a binary tree, construct a 0-indexed m x n
string matrix res
that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:
height
and the number of rows m
should be equal to height + 1
.n
should be equal to 2height+1 - 1
.res[0][(n-1)/2]
).res[r][c]
, place its left child at res[r+1][c-2height-r-1]
and its right child at res[r+1][c+2height-r-1]
.""
.Return the constructed matrix res
.
\n
Example 1:
\n\nInput: root = [1,2]\nOutput: \n[["","1",""],\n ["2","",""]]\n\n\n
Example 2:
\n\nInput: root = [1,2,3,null,4]\nOutput: \n[["","","","1","","",""],\n ["","2","","","","3",""],\n ["","","4","","","",""]]\n\n\n
\n
Constraints:
\n\n[1, 210]
.-99 <= Node.val <= 99
[1, 10]
.There is a robot starting at the position (0, 0)
, the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0)
after it completes its moves.
You are given a string moves
that represents the move sequence of the robot where moves[i]
represents its ith
move. Valid moves are 'R'
(right), 'L'
(left), 'U'
(up), and 'D'
(down).
Return true
if the robot returns to the origin after it finishes all of its moves, or false
otherwise.
Note: The way that the robot is "facing" is irrelevant. 'R'
will always make the robot move to the right once, 'L'
will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.
\n
Example 1:
\n\n\nInput: moves = "UD"\nOutput: true\nExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\n\n\n
Example 2:
\n\n\nInput: moves = "LL"\nOutput: false\nExplanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.\n\n\n
\n
Constraints:
\n\n1 <= moves.length <= 2 * 104
moves
only contains the characters 'U'
, 'D'
, 'L'
and 'R'
.Given a sorted integer array arr
, two integers k
and x
, return the k
closest integers to x
in the array. The result should also be sorted in ascending order.
An integer a
is closer to x
than an integer b
if:
|a - x| < |b - x|
, or|a - x| == |b - x|
and a < b
\n
Example 1:
\n\nInput: arr = [1,2,3,4,5], k = 4, x = 3
\n\nOutput: [1,2,3,4]
\nExample 2:
\n\nInput: arr = [1,1,2,3,4,5], k = 4, x = -1
\n\nOutput: [1,1,2,3]
\n\n
Constraints:
\n\n1 <= k <= arr.length
1 <= arr.length <= 104
arr
is sorted in ascending order.-104 <= arr[i], x <= 104
You are given an integer array nums
that is sorted in non-decreasing order.
Determine if it is possible to split nums
into one or more subsequences such that both of the following conditions are true:
3
or more.Return true
if you can split nums
according to the above conditions, or false
otherwise.
A subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5]
is a subsequence of [1,2,3,4,5]
while [1,3,2]
is not).
\n
Example 1:
\n\n\nInput: nums = [1,2,3,3,4,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,3,4,4,5,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,4,5]\nOutput: false\nExplanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
nums
is sorted in non-decreasing order.An image smoother is a filter of the size 3 x 3
that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).
Given an m x n
integer matrix img
representing the grayscale of an image, return the image after applying the smoother on each cell of it.
\n
Example 1:
\n\nInput: img = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: [[0,0,0],[0,0,0],[0,0,0]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\nFor the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\nFor the point (1,1): floor(8/9) = floor(0.88888889) = 0\n\n\n
Example 2:
\n\nInput: img = [[100,200,100],[200,50,200],[100,200,100]]\nOutput: [[137,141,137],[141,138,141],[137,141,137]]\nExplanation:\nFor the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\nFor the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\nFor the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n\n\n
\n
Constraints:
\n\nm == img.length
n == img[i].length
1 <= m, n <= 200
0 <= img[i][j] <= 255
Given the root
of a binary tree, return the maximum width of the given tree.
The maximum width of a tree is the maximum width among all levels.
\n\nThe width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.
\n\nIt is guaranteed that the answer will in the range of a 32-bit signed integer.
\n\n\n
Example 1:
\n\nInput: root = [1,3,2,5,3,null,9]\nOutput: 4\nExplanation: The maximum width exists in the third level with length 4 (5,3,null,9).\n\n\n
Example 2:
\n\nInput: root = [1,3,2,5,null,null,9,6,null,7]\nOutput: 7\nExplanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).\n\n\n
Example 3:
\n\nInput: root = [1,3,2,5]\nOutput: 2\nExplanation: The maximum width exists in the second level with length 2 (3,2).\n\n\n
\n
Constraints:
\n\n[1, 3000]
.-100 <= Node.val <= 100
There is a strange printer with the following two special properties:
\n\nGiven a string s
, return the minimum number of turns the printer needed to print it.
\n
Example 1:
\n\n\nInput: s = "aaabbb"\nOutput: 2\nExplanation: Print "aaa" first and then print "bbb".\n\n\n
Example 2:
\n\n\nInput: s = "aba"\nOutput: 2\nExplanation: Print "aaa" first and then print "b" from the second place of the string, which will cover the existing character 'a'.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters.Given an array nums
with n
integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1]
holds for every i
(0-based) such that (0 <= i <= n - 2
).
\n
Example 1:
\n\n\nInput: nums = [4,2,3]\nOutput: true\nExplanation: You could modify the first 4 to 1 to get a non-decreasing array.\n\n\n
Example 2:
\n\n\nInput: nums = [4,2,1]\nOutput: false\nExplanation: You cannot get a non-decreasing array by modifying at most one element.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105
Given two integers n
and k
, construct a list answer
that contains n
different positive integers ranging from 1
to n
and obeys the following requirement:
answer = [a1, a2, a3, ... , an]
, then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|]
has exactly k
distinct integers.Return the list answer
. If there multiple valid answers, return any of them.
\n
Example 1:
\n\n\nInput: n = 3, k = 1\nOutput: [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n\n\n
Example 2:
\n\n\nInput: n = 3, k = 2\nOutput: [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n\n\n
\n
Constraints:
\n\n1 <= k < n <= 104
Nearly everyone has used the Multiplication Table. The multiplication table of size m x n
is an integer matrix mat
where mat[i][j] == i * j
(1-indexed).
Given three integers m
, n
, and k
, return the kth
smallest element in the m x n
multiplication table.
\n
Example 1:
\n\nInput: m = 3, n = 3, k = 5\nOutput: 3\nExplanation: The 5th smallest number is 3.\n\n\n
Example 2:
\n\nInput: m = 2, n = 3, k = 6\nOutput: 6\nExplanation: The 6th smallest number is 6.\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 3 * 104
1 <= k <= m * n
Given the root
of a binary search tree and the lowest and highest boundaries as low
and high
, trim the tree so that all its elements lies in [low, high]
. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
\n\n\n
Example 1:
\n\nInput: root = [1,0,2], low = 1, high = 2\nOutput: [1,null,2]\n\n\n
Example 2:
\n\nInput: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput: [3,2,null,1]\n\n\n
\n
Constraints:
\n\n[1, 104]
.0 <= Node.val <= 104
root
is guaranteed to be a valid binary search tree.0 <= low <= high <= 104
You are given an integer num
. You can swap two digits at most once to get the maximum valued number.
Return the maximum valued number you can get.
\n\n\n
Example 1:
\n\n\nInput: num = 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\n\n\n
Example 2:
\n\n\nInput: num = 9973\nOutput: 9973\nExplanation: No swap.\n\n\n
\n
Constraints:
\n\n0 <= num <= 108
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two
or zero
sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val)
always holds.
Given such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.
\n\nIf no such second minimum value exists, output -1 instead.
\n\n\n\n
\n
Example 1:
\n\nInput: root = [2,2,5,null,null,5,7]\nOutput: 5\nExplanation: The smallest value is 2, the second smallest value is 5.\n\n\n
Example 2:
\n\nInput: root = [2,2,2]\nOutput: -1\nExplanation: The smallest value is 2, but there isn't any second smallest value.\n\n\n
\n
Constraints:
\n\n[1, 25]
.1 <= Node.val <= 231 - 1
root.val == min(root.left.val, root.right.val)
for each internal node of the tree.There is a room with n
bulbs labeled from 1
to n
that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:
2, 4, ...
).1, 3, ...
).j = 3k + 1
where k = 0, 1, 2, ...
(i.e., 1, 4, 7, 10, ...
).You must make exactly presses
button presses in total. For each press, you may pick any of the four buttons to press.
Given the two integers n
and presses
, return the number of different possible statuses after performing all presses
button presses.
\n
Example 1:
\n\n\nInput: n = 1, presses = 1\nOutput: 2\nExplanation: Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2\n\n\n
Example 2:
\n\n\nInput: n = 2, presses = 1\nOutput: 3\nExplanation: Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3\n\n\n
Example 3:
\n\n\nInput: n = 3, presses = 1\nOutput: 4\nExplanation: Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
0 <= presses <= 1000
Given an integer array nums
, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,5,4,7]\nOutput: 2\nExplanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2,2,2]\nOutput: 5\nExplanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2000
-106 <= nums[i] <= 106
Given an unsorted array of integers nums
, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l
and r
(l < r
) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]
and for each l <= i < r
, nums[i] < nums[i + 1]
.
\n
Example 1:
\n\n\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2,2,2]\nOutput: 1\nExplanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-109 <= nums[i] <= 109
You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n
matrix. In this matrix:
0
means the cell cannot be walked through.1
represents an empty cell that can be walked through.1
represents a tree in a cell that can be walked through, and this number is the tree's height.In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.
\n\nYou must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1
(an empty cell).
Starting from the point (0, 0)
, return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1
.
Note: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.
\n\n\n
Example 1:
\n\nInput: forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput: 6\nExplanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n\n\n
Example 2:
\n\nInput: forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput: -1\nExplanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n\n\n
Example 3:
\n\n\nInput: forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput: 6\nExplanation: You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n\n\n
\n
Constraints:
\n\nm == forest.length
n == forest[i].length
1 <= m, n <= 50
0 <= forest[i][j] <= 109
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
\n\nImplement the MagicDictionary
class:
MagicDictionary()
Initializes the object.void buildDict(String[] dictionary)
Sets the data structure with an array of distinct strings dictionary
.bool search(String searchWord)
Returns true
if you can change exactly one character in searchWord
to match any string in the data structure, otherwise returns false
.\n
Example 1:
\n\n\nInput\n["MagicDictionary", "buildDict", "search", "search", "search", "search"]\n[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]\nOutput\n[null, null, false, true, false, false]\n\nExplanation\nMagicDictionary magicDictionary = new MagicDictionary();\nmagicDictionary.buildDict(["hello", "leetcode"]);\nmagicDictionary.search("hello"); // return False\nmagicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True\nmagicDictionary.search("hell"); // return False\nmagicDictionary.search("leetcoded"); // return False\n\n\n
\n
Constraints:
\n\n1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
dictionary[i]
consists of only lower-case English letters.dictionary
are distinct.1 <= searchWord.length <= 100
searchWord
consists of only lower-case English letters.buildDict
will be called only once before search
.100
calls will be made to search
.Design a map that allows you to do the following:
\n\nImplement the MapSum
class:
MapSum()
Initializes the MapSum
object.void insert(String key, int val)
Inserts the key-val
pair into the map. If the key
already existed, the original key-value
pair will be overridden to the new one.int sum(string prefix)
Returns the sum of all the pairs' value whose key
starts with the prefix
.\n
Example 1:
\n\n\nInput\n["MapSum", "insert", "sum", "insert", "sum"]\n[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]\nOutput\n[null, null, 3, null, 5]\n\nExplanation\nMapSum mapSum = new MapSum();\nmapSum.insert("apple", 3); \nmapSum.sum("ap"); // return 3 (apple = 3)\nmapSum.insert("app", 2); \nmapSum.sum("ap"); // return 5 (apple + app = 3 + 2 = 5)\n\n\n
\n
Constraints:
\n\n1 <= key.length, prefix.length <= 50
key
and prefix
consist of only lowercase English letters.1 <= val <= 1000
50
calls will be made to insert
and sum
.Given a string s
containing only three types of characters: '('
, ')'
and '*'
, return true
if s
is valid.
The following rules define a valid string:
\n\n'('
must have a corresponding right parenthesis ')'
.')'
must have a corresponding left parenthesis '('
.'('
must go before the corresponding right parenthesis ')'
.'*'
could be treated as a single right parenthesis ')'
or a single left parenthesis '('
or an empty string ""
.\n
Example 1:
\nInput: s = \"()\"\nOutput: true\n
Example 2:
\nInput: s = \"(*)\"\nOutput: true\n
Example 3:
\nInput: s = \"(*))\"\nOutput: true\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s[i]
is '('
, ')'
or '*'
.You are given an integer array cards
of length 4
. You have four cards, each containing a number in the range [1, 9]
. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/']
and the parentheses '('
and ')'
to get the value 24.
You are restricted with the following rules:
\n\n'/'
represents real division, not integer division.\n\n\t4 / (1 - 2 / 3) = 4 / (1 / 3) = 12
.'-'
as a unary operator.\n\tcards = [1, 1, 1, 1]
, the expression "-1 - 1 - 1 - 1"
is not allowed.cards = [1, 2, 1, 2]
, the expression "12 + 12"
is not valid.Return true
if you can get such expression that evaluates to 24
, and false
otherwise.
\n
Example 1:
\n\n\nInput: cards = [4,1,8,7]\nOutput: true\nExplanation: (8-4) * (7-1) = 24\n\n\n
Example 2:
\n\n\nInput: cards = [1,2,1,2]\nOutput: false\n\n\n
\n
Constraints:
\n\ncards.length == 4
1 <= cards[i] <= 9
Given a string s
, return true
if the s
can be palindrome after deleting at most one character from it.
\n
Example 1:
\n\n\nInput: s = "aba"\nOutput: true\n\n\n
Example 2:
\n\n\nInput: s = "abca"\nOutput: true\nExplanation: You could delete the character 'c'.\n\n\n
Example 3:
\n\n\nInput: s = "abc"\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
\n\nYou 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:
x
.\n\n\tx
.'+'
.\n\t'D'
.\n\t'C'
.\n\tReturn the sum of all the scores on the record after applying all the operations.
\n\nThe test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.
\n\n\n
Example 1:
\n\n\nInput: ops = ["5","2","C","D","+"]\nOutput: 30\nExplanation:\n"5" - Add 5 to the record, record is now [5].\n"2" - Add 2 to the record, record is now [5, 2].\n"C" - Invalidate and remove the previous score, record is now [5].\n"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\n\n\n
Example 2:
\n\n\nInput: ops = ["5","-2","4","C","D","9","+","+"]\nOutput: 27\nExplanation:\n"5" - Add 5 to the record, record is now [5].\n"-2" - Add -2 to the record, record is now [5, -2].\n"4" - Add 4 to the record, record is now [5, -2, 4].\n"C" - Invalidate and remove the previous score, record is now [5, -2].\n"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n"9" - Add 9 to the record, record is now [5, -2, -4, 9].\n"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n\n\n
Example 3:
\n\n\nInput: ops = ["1","C"]\nOutput: 0\nExplanation:\n"1" - Add 1 to the record, record is now [1].\n"C" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n\n\n
\n
Constraints:
\n\n1 <= operations.length <= 1000
operations[i]
is "C"
, "D"
, "+"
, or a string representing an integer in the range [-3 * 104, 3 * 104]
."+"
, there will always be at least two previous scores on the record."C"
and "D"
, there will always be at least one previous score on the record.In this problem, a tree is an undirected graph that is connected and has no cycles.
\n\nYou are given a graph that started as a tree with n
nodes labeled from 1
to n
, with one additional edge added. The added edge has two different vertices chosen from 1
to n
, and was not an edge that already existed. The graph is represented as an array edges
of length n
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n
nodes. If there are multiple answers, return the answer that occurs last in the input.
\n
Example 1:
\n\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\n\n
Example 2:
\n\nInput: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput: [1,4]\n\n\n
\n
Constraints:
\n\nn == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ai < bi <= edges.length
ai != bi
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
\n\nThe given input is a directed graph that started as a rooted tree with n
nodes (with distinct values from 1
to n
), with one additional directed edge added. The added edge has two different vertices chosen from 1
to n
, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges
. Each element of edges
is a pair [ui, vi]
that represents a directed edge connecting nodes ui
and vi
, where ui
is a parent of child vi
.
Return an edge that can be removed so that the resulting graph is a rooted tree of n
nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
\n
Example 1:
\n\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\n\n\n
Example 2:
\n\nInput: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\nOutput: [4,1]\n\n\n
\n
Constraints:
\n\nn == edges.length
3 <= n <= 1000
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
Given two strings a
and b
, return the minimum number of times you should repeat string a
so that string b
is a substring of it. If it is impossible for b
\u200b\u200b\u200b\u200b\u200b\u200b to be a substring of a
after repeating it, return -1
.
Notice: string "abc"
repeated 0 times is ""
, repeated 1 time is "abc"
and repeated 2 times is "abcabc"
.
\n
Example 1:
\n\n\nInput: a = "abcd", b = "cdabcdab"\nOutput: 3\nExplanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.\n\n\n
Example 2:
\n\n\nInput: a = "a", b = "aa"\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= a.length, b.length <= 104
a
and b
consist of lowercase English letters.Given the root
of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
\n\n\n
Example 1:
\n\nInput: root = [5,4,5,1,1,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 5).\n\n\n
Example 2:
\n\nInput: root = [1,4,5,4,4,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 4).\n\n\n
\n
Constraints:
\n\n[0, 104]
.-1000 <= Node.val <= 1000
1000
.On an n x n
chessboard, a knight starts at the cell (row, column)
and attempts to make exactly k
moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0)
, and the bottom-right cell is (n - 1, n - 1)
.
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
\nEach time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
\n\nThe knight continues moving until it has made exactly k
moves or has moved off the chessboard.
Return the probability that the knight remains on the board after it has stopped moving.
\n\n\n
Example 1:
\n\n\nInput: n = 3, k = 2, row = 0, column = 0\nOutput: 0.06250\nExplanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.\n\n\n
Example 2:
\n\n\nInput: n = 1, k = 0, row = 0, column = 0\nOutput: 1.00000\n\n\n
\n
Constraints:
\n\n1 <= n <= 25
0 <= k <= 100
0 <= row, column <= n - 1
Given an integer array nums
and an integer k
, find three non-overlapping subarrays of length k
with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,2,6,7,5,1], k = 2\nOutput: [0,3,5]\nExplanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically smaller.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput: [0,2,4]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= nums[i] < 216
1 <= k <= floor(nums.length / 3)
Given an integer array nums
and an integer k
, find three non-overlapping subarrays of length k
with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,2,6,7,5,1], k = 2\nOutput: [0,3,5]\nExplanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput: [0,2,4]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= nums[i] < 216
1 <= k <= floor(nums.length / 3)
You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
\n\nYou are given an array of employees employees
where:
employees[i].id
is the ID of the ith
employee.employees[i].importance
is the importance value of the ith
employee.employees[i].subordinates
is a list of the IDs of the direct subordinates of the ith
employee.Given an integer id
that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.
\n
Example 1:
\n\nInput: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput: 11\nExplanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.\n\n\n
Example 2:
\n\nInput: employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput: -3\nExplanation: Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.\n\n\n
\n
Constraints:
\n\n1 <= employees.length <= 2000
1 <= employees[i].id <= 2000
employees[i].id
are unique.-100 <= employees[i].importance <= 100
employees[i].subordinates
are valid IDs.We are given n
different types of stickers
. Each sticker has a lowercase English word on it.
You would like to spell out the given string target
by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target
. If the task is impossible, return -1
.
Note: In all test cases, all words were chosen randomly from the 1000
most common US English words, and target
was chosen as a concatenation of two random words.
\n
Example 1:
\n\n\nInput: stickers = ["with","example","science"], target = "thehat"\nOutput: 3\nExplanation:\nWe can use 2 "with" stickers, and 1 "example" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target "thehat".\nAlso, this is the minimum number of stickers necessary to form the target string.\n\n\n
Example 2:
\n\n\nInput: stickers = ["notice","possible"], target = "basicbasic"\nOutput: -1\nExplanation:\nWe cannot form the target "basicbasic" from cutting letters from the given stickers.\n\n\n
\n
Constraints:
\n\nn == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target.length <= 15
stickers[i]
and target
consist of lowercase English letters.Given an array of strings words
and an integer k
, return the k
most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
\n\n\n
Example 1:
\n\n\nInput: words = ["i","love","leetcode","i","love","coding"], k = 2\nOutput: ["i","love"]\nExplanation: "i" and "love" are the two most frequent words.\nNote that "i" comes before "love" due to a lower alphabetical order.\n\n\n
Example 2:
\n\n\nInput: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4\nOutput: ["the","is","sunny","day"]\nExplanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 500
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.k
is in the range [1, The number of unique words[i]]
\n
Follow-up: Could you solve it in O(n log(k))
time and O(n)
extra space?
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
\n\n\n
Example 1:
\n\n\nInput: n = 5\nOutput: true\nExplanation: The binary representation of 5 is: 101\n\n\n
Example 2:
\n\n\nInput: n = 7\nOutput: false\nExplanation: The binary representation of 7 is: 111.\n\n
Example 3:
\n\n\nInput: n = 11\nOutput: false\nExplanation: The binary representation of 11 is: 1011.\n\n
\n
Constraints:
\n\n1 <= n <= 231 - 1
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.
The area of an island is the number of cells with a value 1
in the island.
Return the maximum area of an island in grid
. If there is no island, return 0
.
\n
Example 1:
\n\nInput: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\nOutput: 6\nExplanation: The answer is not 11, because the island must be connected 4-directionally.\n\n\n
Example 2:
\n\n\nInput: grid = [[0,0,0,0,0,0,0,0]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
is either 0
or 1
.Given a binary string s
, return the number of non-empty substrings that have the same number of 0
's and 1
's, and all the 0
's and all the 1
's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.
\n\n\n
Example 1:
\n\n\nInput: s = "00110011"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.\n\n\n
Example 2:
\n\n\nInput: s = "10101"\nOutput: 4\nExplanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.Given a non-empty array of non-negative integers nums
, the degree of this array is defined as the maximum frequency of any one of its elements.
Your task is to find the smallest possible length of a (contiguous) subarray of nums
, that has the same degree as nums
.
\n
Example 1:
\n\n\nInput: nums = [1,2,2,3,1]\nOutput: 2\nExplanation: \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,2,3,1,4,2]\nOutput: 6\nExplanation: \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n\n\n
\n
Constraints:
\n\nnums.length
will be between 1 and 50,000.nums[i]
will be an integer between 0 and 49,999.Given an integer array nums
and an integer k
, return true
if it is possible to divide this array into k
non-empty subsets whose sums are all equal.
\n
Example 1:
\n\n\nInput: nums = [4,3,2,3,5,2,1], k = 4\nOutput: true\nExplanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4], k = 3\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 16
1 <= nums[i] <= 104
[1, 4]
.There are several squares being dropped onto the X-axis of a 2D plane.
\n\nYou are given a 2D integer array positions
where positions[i] = [lefti, sideLengthi]
represents the ith
square with a side length of sideLengthi
that is dropped with its left edge aligned with X-coordinate lefti
.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
\n\nAfter each square is dropped, you must record the height of the current tallest stack of squares.
\n\nReturn an integer array ans
where ans[i]
represents the height described above after dropping the ith
square.
\n
Example 1:
\n\nInput: positions = [[1,2],[2,3],[6,1]]\nOutput: [2,5,5]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].\n\n\n
Example 2:
\n\n\nInput: positions = [[100,100],[200,100]]\nOutput: [100,100]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.\n\n\n
\n
Constraints:
\n\n1 <= positions.length <= 1000
1 <= lefti <= 108
1 <= sideLengthi <= 106
You are given the root
of a binary search tree (BST) and an integer val
.
Find the node in the BST that the node's value equals val
and return the subtree rooted with that node. If such a node does not exist, return null
.
\n
Example 1:
\n\nInput: root = [4,2,7,1,3], val = 2\nOutput: [2,1,3]\n\n\n
Example 2:
\n\nInput: root = [4,2,7,1,3], val = 5\nOutput: []\n\n\n
\n
Constraints:
\n\n[1, 5000]
.1 <= Node.val <= 107
root
is a binary search tree.1 <= val <= 107
You are given the root
node of a binary search tree (BST) and a value
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.
Notice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.
\n\n\n
Example 1:
\n\nInput: root = [4,2,7,1,3], val = 5\nOutput: [4,2,7,1,3,5]\nExplanation: Another accepted tree is:\n\n\n\n
Example 2:
\n\n\nInput: root = [40,20,60,10,30,50,70], val = 25\nOutput: [40,20,60,10,30,50,70,null,null,25]\n\n\n
Example 3:
\n\n\nInput: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput: [4,2,7,1,3,5]\n\n\n
\n
Constraints:
\n\n[0, 104]
.-108 <= Node.val <= 108
Node.val
are unique.-108 <= val <= 108
val
does not exist in the original BST.You are part of a university admissions office and need to keep track of the kth
highest test score from applicants in real-time. This helps to determine cut-off marks for interviews and admissions dynamically as new applicants submit their scores.
You are tasked to implement a class which, for a given integer k
, maintains a stream of test scores and continuously returns the k
th highest test score after a new score has been submitted. More specifically, we are looking for the k
th highest score in the sorted list of all scores.
Implement the KthLargest
class:
KthLargest(int k, int[] nums)
Initializes the object with the integer k
and the stream of test scores nums
.int add(int val)
Adds a new test score val
to the stream and returns the element representing the kth
largest element in the pool of test scores so far.\n
Example 1:
\n\nInput:
\n["KthLargest", "add", "add", "add", "add", "add"]
\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output: [null, 4, 5, 5, 8, 8]
\n\nExplanation:
\n\nKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
\nkthLargest.add(3); // return 4
\nkthLargest.add(5); // return 5
\nkthLargest.add(10); // return 5
\nkthLargest.add(9); // return 8
\nkthLargest.add(4); // return 8
Example 2:
\n\nInput:
\n["KthLargest", "add", "add", "add", "add"]
\n[[4, [7, 7, 7, 7, 8, 3]], [2], [10], [9], [9]]
Output: [null, 7, 7, 7, 8]
\n\nExplanation:
\nKthLargest kthLargest = new KthLargest(4, [7, 7, 7, 7, 8, 3]);\n
Constraints:
\n\n0 <= nums.length <= 104
1 <= k <= nums.length + 1
-104 <= nums[i] <= 104
-104 <= val <= 104
104
calls will be made to add
.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.
\n
Example 1:
\n\n\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\n\n
Example 2:
\n\n\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-104 < nums[i], target < 104
nums
are unique.nums
is sorted in ascending order.Design a HashSet without using any built-in hash table libraries.
\n\nImplement MyHashSet
class:
void add(key)
Inserts the value key
into the HashSet.bool contains(key)
Returns whether the value key
exists in the HashSet or not.void remove(key)
Removes the value key
in the HashSet. If key
does not exist in the HashSet, do nothing.\n
Example 1:
\n\n\nInput\n["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\nOutput\n[null, null, null, true, false, null, true, null, false]\n\nExplanation\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)\n\n
\n
Constraints:
\n\n0 <= key <= 106
104
calls will be made to add
, remove
, and contains
.Design a HashMap without using any built-in hash table libraries.
\n\nImplement the MyHashMap
class:
MyHashMap()
initializes the object with an empty map.void put(int key, int value)
inserts a (key, value)
pair into the HashMap. If the key
already exists in the map, update the corresponding value
.int get(int key)
returns the value
to which the specified key
is mapped, or -1
if this map contains no mapping for the key
.void remove(key)
removes the key
and its corresponding value
if the map contains the mapping for the key
.\n
Example 1:
\n\n\nInput\n["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]\n[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\nOutput\n[null, null, null, 1, -1, null, 1, null, -1]\n\nExplanation\nMyHashMap myHashMap = new MyHashMap();\nmyHashMap.put(1, 1); // The map is now [[1,1]]\nmyHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\nmyHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\nmyHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\nmyHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\nmyHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\nmyHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\nmyHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]\n\n\n
\n
Constraints:
\n\n0 <= key, value <= 106
104
calls will be made to put
, get
, and remove
.Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
\nA node in a singly linked list should have two attributes: val
and next
. val
is the value of the current node, and next
is a pointer/reference to the next node.
\nIf you want to use the doubly linked list, you will need one more attribute prev
to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList
class:
MyLinkedList()
Initializes the MyLinkedList
object.int get(int index)
Get the value of the indexth
node in the linked list. If the index is invalid, return -1
.void addAtHead(int val)
Add a node of value val
before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.void addAtTail(int val)
Append a node of value val
as the last element of the linked list.void addAtIndex(int index, int val)
Add a node of value val
before the indexth
node in the linked list. If index
equals the length of the linked list, the node will be appended to the end of the linked list. If index
is greater than the length, the node will not be inserted.void deleteAtIndex(int index)
Delete the indexth
node in the linked list, if the index is valid.\n
Example 1:
\n\n\nInput\n["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]\n[[], [1], [3], [1, 2], [1], [1], [1]]\nOutput\n[null, null, null, null, 2, null, 3]\n\nExplanation\nMyLinkedList myLinkedList = new MyLinkedList();\nmyLinkedList.addAtHead(1);\nmyLinkedList.addAtTail(3);\nmyLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\nmyLinkedList.get(1); // return 2\nmyLinkedList.deleteAtIndex(1); // now the linked list is 1->3\nmyLinkedList.get(1); // return 3\n\n\n
\n
Constraints:
\n\n0 <= index, val <= 1000
2000
calls will be made to get
, addAtHead
, addAtTail
, addAtIndex
and deleteAtIndex
.Given a string s
, return the string after replacing every uppercase letter with the same lowercase letter.
\n
Example 1:
\n\n\nInput: s = "Hello"\nOutput: "hello"\n\n\n
Example 2:
\n\n\nInput: s = "here"\nOutput: "here"\n\n\n
Example 3:
\n\n\nInput: s = "LOVELY"\nOutput: "lovely"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of printable ASCII characters.You are given an integer n
and an array of unique integers blacklist
. Design an algorithm to pick a random integer in the range [0, n - 1]
that is not in blacklist
. Any integer that is in the mentioned range and not in blacklist
should be equally likely to be returned.
Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.
\n\nImplement the Solution
class:
Solution(int n, int[] blacklist)
Initializes the object with the integer n
and the blacklisted integers blacklist
.int pick()
Returns a random integer in the range [0, n - 1]
and not in blacklist
.\n
Example 1:
\n\n\nInput\n["Solution", "pick", "pick", "pick", "pick", "pick", "pick", "pick"]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]\nOutput\n[null, 0, 4, 1, 6, 1, 0, 4]\n\nExplanation\nSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
0 <= blacklist.length <= min(105, n - 1)
0 <= blacklist[i] < n
blacklist
are unique.2 * 104
calls will be made to pick
.Given two strings s1
and s2
, return the lowest ASCII sum of deleted characters to make two strings equal.
\n
Example 1:
\n\n\nInput: s1 = "sea", s2 = "eat"\nOutput: 231\nExplanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.\nDeleting "t" from "eat" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n\n\n
Example 2:
\n\n\nInput: s1 = "delete", s2 = "leet"\nOutput: 403\nExplanation: Deleting "dee" from "delete" to turn the string into "let",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting "e" from "leet" adds 101[e] to the sum.\nAt the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 1000
s1
and s2
consist of lowercase English letters.Given an array of integers nums
and an integer k
, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k
.
\n
Example 1:
\n\n\nInput: nums = [10,5,2,6], k = 100\nOutput: 8\nExplanation: The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3], k = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
1 <= nums[i] <= 1000
0 <= k <= 106
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day, and an integer fee
representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
\n\nNote:
\n\n\n
Example 1:
\n\n\nInput: prices = [1,3,2,8,4,9], fee = 2\nOutput: 8\nExplanation: The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n\n\n
Example 2:
\n\n\nInput: prices = [1,3,7,5,10,3], fee = 3\nOutput: 6\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 5 * 104
1 <= prices[i] < 5 * 104
0 <= fee < 5 * 104
A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.
\n\nA half-open interval [left, right)
denotes all the real numbers x
where left <= x < right
.
Implement the RangeModule
class:
RangeModule()
Initializes the object of the data structure.void addRange(int left, int right)
Adds the half-open interval [left, right)
, tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right)
that are not already tracked.boolean queryRange(int left, int right)
Returns true
if every real number in the interval [left, right)
is currently being tracked, and false
otherwise.void removeRange(int left, int right)
Stops tracking every real number currently being tracked in the half-open interval [left, right)
.\n
Example 1:
\n\n\nInput\n["RangeModule", "addRange", "removeRange", "queryRange", "queryRange", "queryRange"]\n[[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\nOutput\n[null, null, null, true, false, true]\n\nExplanation\nRangeModule rangeModule = new RangeModule();\nrangeModule.addRange(10, 20);\nrangeModule.removeRange(14, 16);\nrangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\nrangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\nrangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n\n\n
\n
Constraints:
\n\n1 <= left < right <= 109
104
calls will be made to addRange
, queryRange
, and removeRange
.We have two special characters:
\n\n0
.10
or 11
).Given a binary array bits
that ends with 0
, return true
if the last character must be a one-bit character.
\n
Example 1:
\n\n\nInput: bits = [1,0,0]\nOutput: true\nExplanation: The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.\n\n\n
Example 2:
\n\n\nInput: bits = [1,1,1,0]\nOutput: false\nExplanation: The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.\n\n\n
\n
Constraints:
\n\n1 <= bits.length <= 1000
bits[i]
is either 0
or 1
.Given two integer arrays nums1
and nums2
, return the maximum length of a subarray that appears in both arrays.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\nOutput: 3\nExplanation: The repeated subarray with maximum length is [3,2,1].\n\n\n
Example 2:
\n\n\nInput: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\nOutput: 5\nExplanation: The repeated subarray with maximum length is [0,0,0,0,0].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100
The distance of a pair of integers a
and b
is defined as the absolute difference between a
and b
.
Given an integer array nums
and an integer k
, return the kth
smallest distance among all the pairs nums[i]
and nums[j]
where 0 <= i < j < nums.length
.
\n
Example 1:
\n\n\nInput: nums = [1,3,1], k = 1\nOutput: 0\nExplanation: Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1], k = 2\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: nums = [1,6,1], k = 3\nOutput: 5\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
Given an array of strings words
representing an English Dictionary, return the longest word in words
that can be built one character at a time by other words in words
.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.
\n\nNote that the word should be built from left to right with each additional character being added to the end of a previous word.
\n\n\n
Example 1:
\n\n\nInput: words = ["w","wo","wor","worl","world"]\nOutput: "world"\nExplanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".\n\n\n
Example 2:
\n\n\nInput: words = ["a","banana","app","appl","ap","apply","apple"]\nOutput: "apple"\nExplanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i]
consists of lowercase English letters.Given a list of accounts
where each element accounts[i]
is a list of strings, where the first element accounts[i][0]
is a name, and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
\n\nAfter merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
\n\n\n
Example 1:
\n\n\nInput: accounts = [["John","johnsmith@mail.com","john_newyork@mail.com"],["John","johnsmith@mail.com","john00@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]\nOutput: [["John","john00@mail.com","john_newyork@mail.com","johnsmith@mail.com"],["Mary","mary@mail.com"],["John","johnnybravo@mail.com"]]\nExplanation:\nThe first and second John's are the same person as they have the common email "johnsmith@mail.com".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\n\n\n
Example 2:
\n\n\nInput: accounts = [["Gabe","Gabe0@m.co","Gabe3@m.co","Gabe1@m.co"],["Kevin","Kevin3@m.co","Kevin5@m.co","Kevin0@m.co"],["Ethan","Ethan5@m.co","Ethan4@m.co","Ethan0@m.co"],["Hanzo","Hanzo3@m.co","Hanzo1@m.co","Hanzo0@m.co"],["Fern","Fern5@m.co","Fern1@m.co","Fern0@m.co"]]\nOutput: [["Ethan","Ethan0@m.co","Ethan4@m.co","Ethan5@m.co"],["Gabe","Gabe0@m.co","Gabe1@m.co","Gabe3@m.co"],["Hanzo","Hanzo0@m.co","Hanzo1@m.co","Hanzo3@m.co"],["Kevin","Kevin0@m.co","Kevin3@m.co","Kevin5@m.co"],["Fern","Fern0@m.co","Fern1@m.co","Fern5@m.co"]]\n\n\n
\n
Constraints:
\n\n1 <= accounts.length <= 1000
2 <= accounts[i].length <= 10
1 <= accounts[i][j].length <= 30
accounts[i][0]
consists of English letters.accounts[i][j] (for j > 0)
is a valid email.Given a C++ program, remove comments from it. The program source is an array of strings source
where source[i]
is the ith
line of the source code. This represents the result of splitting the original source code string by the newline character '\\n'
.
In C++, there are two types of comments, line comments, and block comments.
\n\n"//"
denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored."/*"
denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "*/"
should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string "/*/"
does not yet end the block comment, as the ending would be overlapping the beginning.The first effective comment takes precedence over others.
\n\n"//"
occurs in a block comment, it is ignored."/*"
occurs in a line or block comment, it is also ignored.If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
\n\nThere will be no control characters, single quote, or double quote characters.
\n\nsource = "string s = "/* Not a comment. */";"
will not be a test case.Also, nothing else such as defines or macros will interfere with the comments.
\n\nIt is guaranteed that every open block comment will eventually be closed, so "/*"
outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
\n\nAfter removing the comments from the source code, return the source code in the same format.
\n\n\n
Example 1:
\n\n\nInput: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]\nOutput: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]\nExplanation: The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n // variable declaration \nint a, b, c;\n/* This is a test\n multiline \n comment for \n testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n \nint a, b, c;\na = b + c;\n}\n\n\n
Example 2:
\n\n\nInput: source = ["a/*comment", "line", "more_comment*/b"]\nOutput: ["ab"]\nExplanation: The original source string is "a/*comment\\nline\\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].\n\n\n
\n
Constraints:
\n\n1 <= source.length <= 100
0 <= source[i].length <= 80
source[i]
consists of printable ASCII characters.Given an array of integers nums
, calculate the pivot index of this array.
The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.
\n\nIf the index is on the left edge of the array, then the left sum is 0
because there are no elements to the left. This also applies to the right edge of the array.
Return the leftmost pivot index. If no such index exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\n\n
Example 3:
\n\n\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-1000 <= nums[i] <= 1000
\n
Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/
\n", - "likes": 8637, - "dislikes": 879, - "stats": "{\"totalAccepted\": \"1.3M\", \"totalSubmission\": \"2.2M\", \"totalAcceptedRaw\": 1303973, \"totalSubmissionRaw\": 2184300, \"acRate\": \"59.7%\"}", + "likes": 8794, + "dislikes": 897, + "stats": "{\"totalAccepted\": \"1.4M\", \"totalSubmission\": \"2.3M\", \"totalAcceptedRaw\": 1404664, \"totalSubmissionRaw\": 2320176, \"acRate\": \"60.5%\"}", "similarQuestions": "[{\"title\": \"Subarray Sum Equals K\", \"titleSlug\": \"subarray-sum-equals-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find the Middle Index in Array\", \"titleSlug\": \"find-the-middle-index-in-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Split Array\", \"titleSlug\": \"number-of-ways-to-split-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Sum Score of Array\", \"titleSlug\": \"maximum-sum-score-of-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Left and Right Sum Differences\", \"titleSlug\": \"left-and-right-sum-differences\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -27305,9 +27317,9 @@ "questionFrontendId": "725", "title": "Split Linked List in Parts", "content": "Given the head
of a singly linked list and an integer k
, split the linked list into k
consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
\n\nThe parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
\n\nReturn an array of the k
parts.
\n
Example 1:
\n\nInput: head = [1,2,3], k = 5\nOutput: [[1],[2],[3],[],[]]\nExplanation:\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\n\n\n
Example 2:
\n\nInput: head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput: [[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation:\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n\n\n
\n
Constraints:
\n\n[0, 1000]
.0 <= Node.val <= 1000
1 <= k <= 50
Given a string formula
representing a chemical formula, return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
\n\nOne or more digits representing that element's count may follow if the count is greater than 1
. If the count is 1
, no digits will follow.
"H2O"
and "H2O2"
are possible, but "H1O2"
is impossible.Two formulas are concatenated together to produce another formula.
\n\n"H2O2He3Mg4"
is also a formula.A formula placed in parentheses, and a count (optionally added) is also a formula.
\n\n"(H2O2)"
and "(H2O2)3"
are formulas.Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1
), followed by the second name (in sorted order), followed by its count (if that count is more than 1
), and so on.
The test cases are generated so that all the values in the output fit in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: formula = "H2O"\nOutput: "H2O"\nExplanation: The count of elements are {'H': 2, 'O': 1}.\n\n\n
Example 2:
\n\n\nInput: formula = "Mg(OH)2"\nOutput: "H2MgO2"\nExplanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n\n\n
Example 3:
\n\n\nInput: formula = "K4(ON(SO3)2)2"\nOutput: "K4N2O14S4"\nExplanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n\n\n
\n
Constraints:
\n\n1 <= formula.length <= 1000
formula
consists of English letters, digits, '('
, and ')'
.formula
is always valid.A self-dividing number is a number that is divisible by every digit it contains.
\n\n128
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.
\n\nGiven two integers left
and right
, return a list of all the self-dividing numbers in the range [left, right]
(both inclusive).
\n
Example 1:
\nInput: left = 1, right = 22\nOutput: [1,2,3,4,5,6,7,8,9,11,12,15,22]\n
Example 2:
\nInput: left = 47, right = 85\nOutput: [48,55,66,77]\n\n
\n
Constraints:
\n\n1 <= left <= right <= 104
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.
\n\nA double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
\n\nThe event can be represented as a pair of integers startTime
and endTime
that represents a booking on the half-open interval [startTime, endTime)
, the range of real numbers x
such that startTime <= x < endTime
.
Implement the MyCalendar
class:
MyCalendar()
Initializes the calendar object.boolean book(int startTime, int endTime)
Returns true
if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false
and do not add the event to the calendar.\n
Example 1:
\n\n\nInput\n["MyCalendar", "book", "book", "book"]\n[[], [10, 20], [15, 25], [20, 30]]\nOutput\n[null, true, false, true]\n\nExplanation\nMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.\n\n
\n
Constraints:
\n\n0 <= start < end <= 109
1000
calls will be made to book
.Given a string s, return the number of different non-empty palindromic subsequences in s
. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence of a string is obtained by deleting zero or more characters from the string.
\n\nA sequence is palindromic if it is equal to the sequence reversed.
\n\nTwo sequences a1, a2, ...
and b1, b2, ...
are different if there is some i
for which ai != bi
.
\n
Example 1:
\n\n\nInput: s = "bccb"\nOutput: 6\nExplanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.\n\n\n
Example 2:
\n\n\nInput: s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"\nOutput: 104860361\nExplanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either 'a'
, 'b'
, 'c'
, or 'd'
.You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
\n\nA triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
\n\nThe event can be represented as a pair of integers startTime
and endTime
that represents a booking on the half-open interval [startTime, endTime)
, the range of real numbers x
such that startTime <= x < endTime
.
Implement the MyCalendarTwo
class:
MyCalendarTwo()
Initializes the calendar object.boolean book(int startTime, int endTime)
Returns true
if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false
and do not add the event to the calendar.\n
Example 1:
\n\n\nInput\n["MyCalendarTwo", "book", "book", "book", "book", "book", "book"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, true, true, true, false, true, true]\n\nExplanation\nMyCalendarTwo myCalendarTwo = new MyCalendarTwo();\nmyCalendarTwo.book(10, 20); // return True, The event can be booked. \nmyCalendarTwo.book(50, 60); // return True, The event can be booked. \nmyCalendarTwo.book(10, 40); // return True, The event can be double booked. \nmyCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\nmyCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\nmyCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.\n\n\n
\n
Constraints:
\n\n0 <= start < end <= 109
1000
calls will be made to book
.A k
-booking happens when k
events have some non-empty intersection (i.e., there is some time that is common to all k
events.)
You are given some events [startTime, endTime)
, after each given event, return an integer k
representing the maximum k
-booking between all the previous events.
Implement the MyCalendarThree
class:
MyCalendarThree()
Initializes the object.int book(int startTime, int endTime)
Returns an integer k
representing the largest integer such that there exists a k
-booking in the calendar.\n
Example 1:
\n\n\nInput\n["MyCalendarThree", "book", "book", "book", "book", "book", "book"]\n[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\nOutput\n[null, 1, 1, 2, 3, 3, 3]\n\nExplanation\nMyCalendarThree myCalendarThree = new MyCalendarThree();\nmyCalendarThree.book(10, 20); // return 1\nmyCalendarThree.book(50, 60); // return 1\nmyCalendarThree.book(10, 40); // return 2\nmyCalendarThree.book(5, 15); // return 3\nmyCalendarThree.book(5, 10); // return 3\nmyCalendarThree.book(25, 55); // return 3\n\n\n\n
\n
Constraints:
\n\n0 <= startTime < endTime <= 109
400
calls will be made to book
.You are given an image represented by an m x n
grid of integers image
, where image[i][j]
represents the pixel value of the image. You are also given three integers sr
, sc
, and color
. Your task is to perform a flood fill on the image starting from the pixel image[sr][sc]
.
To perform a flood fill:
\n\ncolor
.Return the modified image after performing the flood fill.
\n\n\n
Example 1:
\n\nInput: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
\n\nOutput: [[2,2,2],[2,2,0],[2,0,1]]
\n\nExplanation:
\n\nFrom the center of the image with position (sr, sc) = (1, 1)
(i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not horizontally or vertically connected to the starting pixel.
\nExample 2:
\n\nInput: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
\n\nOutput: [[0,0,0],[0,0,0]]
\n\nExplanation:
\n\nThe starting pixel is already colored with 0, which is the same as the target color. Therefore, no changes are made to the image.
\n\n
Constraints:
\n\nm == image.length
n == image[i].length
1 <= m, n <= 50
0 <= image[i][j], color < 216
0 <= sr < m
0 <= sc < n
We are given an array asteroids
of integers representing asteroids in a row. The indices of the asteriod in the array represent their relative position in space.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
\n\nFind out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
\n\n\n
Example 1:
\n\n\nInput: asteroids = [5,10,-5]\nOutput: [5,10]\nExplanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\n\n\n
Example 2:
\n\n\nInput: asteroids = [8,-8]\nOutput: []\nExplanation: The 8 and -8 collide exploding each other.\n\n\n
Example 3:
\n\n\nInput: asteroids = [10,2,-5]\nOutput: [10]\nExplanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n\n\n
\n
Constraints:
\n\n2 <= asteroids.length <= 104
-1000 <= asteroids[i] <= 1000
asteroids[i] != 0
You are given a string expression representing a Lisp-like expression to return the integer value of.
\n\nThe syntax for these expressions is given as follows.
\n\n"(let v1 e1 v2 e2 ... vn en expr)"
, where let is always the string "let"
, then there are one or more pairs of alternating variables and expressions, meaning that the first variable v1
is assigned the value of the expression e1
, the second variable v2
is assigned the value of the expression e2
, and so on sequentially; and then the value of this let expression is the value of the expression expr
."(add e1 e2)"
where add is always the string "add"
, there are always two expressions e1
, e2
and the result is the addition of the evaluation of e1
and the evaluation of e2
."(mult e1 e2)"
where mult is always the string "mult"
, there are always two expressions e1
, e2
and the result is the multiplication of the evaluation of e1 and the evaluation of e2."add"
, "let"
, and "mult"
are protected and will never be used as variable names.\n
Example 1:
\n\n\nInput: expression = "(let x 2 (mult x (let x 3 y 4 (add x y))))"\nOutput: 14\nExplanation: In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.\n\n\n
Example 2:
\n\n\nInput: expression = "(let x 3 x 2 x)"\nOutput: 2\nExplanation: Assignment in let statements is processed sequentially.\n\n\n
Example 3:
\n\n\nInput: expression = "(let x 1 y 2 x (add x y) (add x y))"\nOutput: 5\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.\n\n\n
\n
Constraints:
\n\n1 <= expression.length <= 2000
expression
.expression
.An integer has monotone increasing digits if and only if each pair of adjacent digits x
and y
satisfy x <= y
.
Given an integer n
, return the largest number that is less than or equal to n
with monotone increasing digits.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 9\n\n\n
Example 2:
\n\n\nInput: n = 1234\nOutput: 1234\n\n\n
Example 3:
\n\n\nInput: n = 332\nOutput: 299\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
Given an array of integers temperatures
represents the daily temperatures, return an array answer
such that answer[i]
is the number of days you have to wait after the ith
day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0
instead.
\n
Example 1:
\nInput: temperatures = [73,74,75,71,69,72,76,73]\nOutput: [1,1,4,2,1,1,0,0]\n
Example 2:
\nInput: temperatures = [30,40,50,60]\nOutput: [1,1,1,0]\n
Example 3:
\nInput: temperatures = [30,60,90]\nOutput: [1,1,0]\n\n
\n
Constraints:
\n\n1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
You are given an integer array nums
. You want to maximize the number of points you get by performing the following operation any number of times:
nums[i]
and delete it to earn nums[i]
points. Afterwards, you must delete every element equal to nums[i] - 1
and every element equal to nums[i] + 1
.Return the maximum number of points you can earn by applying the above operation some number of times.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,4,2]\nOutput: 6\nExplanation: You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,3,3,3,4]\nOutput: 9\nExplanation: You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= nums[i] <= 104
You are given an n x n
grid
representing a field of cherries, each cell is one of three possible integers.
0
means the cell is empty, so you can pass through,1
means the cell contains a cherry that you can pick up and pass through, or-1
means the cell contains a thorn that blocks your way.Return the maximum number of cherries you can collect by following the rules below:
\n\n(0, 0)
and reaching (n - 1, n - 1)
by moving right or down through valid path cells (cells with value 0
or 1
).(n - 1, n - 1)
, returning to (0, 0)
by moving left or up through valid path cells.0
.(0, 0)
and (n - 1, n - 1)
, then no cherries can be collected.\n
Example 1:
\n\nInput: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput: 5\nExplanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.\n\n\n
Example 2:
\n\n\nInput: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
1 <= n <= 50
grid[i][j]
is -1
, 0
, or 1
.grid[0][0] != -1
grid[n - 1][n - 1] != -1
You are given a network of n
nodes, labeled from 1
to n
. You are also given times
, a list of travel times as directed edges times[i] = (ui, vi, wi)
, where ui
is the source node, vi
is the target node, and wi
is the time it takes for a signal to travel from source to target.
We will send a signal from a given node k
. Return the minimum time it takes for all the n
nodes to receive the signal. If it is impossible for all the n
nodes to receive the signal, return -1
.
\n
Example 1:
\n\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: times = [[1,2,1]], n = 2, k = 1\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: times = [[1,2,1]], n = 2, k = 2\nOutput: -1\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 100
1 <= times.length <= 6000
times[i].length == 3
1 <= ui, vi <= n
ui != vi
0 <= wi <= 100
(ui, vi)
are unique. (i.e., no multiple edges.)You are given an array of characters letters
that is sorted in non-decreasing order, and a character target
. There are at least two different characters in letters
.
Return the smallest character in letters
that is lexicographically greater than target
. If such a character does not exist, return the first character in letters
.
\n
Example 1:
\n\n\nInput: letters = ["c","f","j"], target = "a"\nOutput: "c"\nExplanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.\n\n\n
Example 2:
\n\n\nInput: letters = ["c","f","j"], target = "c"\nOutput: "f"\nExplanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.\n\n\n
Example 3:
\n\n\nInput: letters = ["x","x","y","y"], target = "z"\nOutput: "x"\nExplanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].\n\n\n
\n
Constraints:
\n\n2 <= letters.length <= 104
letters[i]
is a lowercase English letter.letters
is sorted in non-decreasing order.letters
contains at least two different characters.target
is a lowercase English letter.Design a special dictionary that searches the words in it by a prefix and a suffix.
\n\nImplement the WordFilter
class:
WordFilter(string[] words)
Initializes the object with the words
in the dictionary.f(string pref, string suff)
Returns the index of the word in the dictionary, which has the prefix pref
and the suffix suff
. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1
.\n
Example 1:
\n\n\nInput\n["WordFilter", "f"]\n[[["apple"]], ["a", "e"]]\nOutput\n[null, 0]\nExplanation\nWordFilter wordFilter = new WordFilter(["apple"]);\nwordFilter.f("a", "e"); // return 0, because the word at index 0 has prefix = "a" and suffix = "e".\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 104
1 <= words[i].length <= 7
1 <= pref.length, suff.length <= 7
words[i]
, pref
and suff
consist of lowercase English letters only.104
calls will be made to the function f
.You are given an integer array cost
where cost[i]
is the cost of ith
step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0
, or the step with index 1
.
Return the minimum cost to reach the top of the floor.
\n\n\n
Example 1:
\n\n\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\n\n\n
Example 2:
\n\n\nInput: cost = [1,100,1,1,1,100,1,1,100,1]\nOutput: 6\nExplanation: You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.\n\n\n
\n
Constraints:
\n\n2 <= cost.length <= 1000
0 <= cost[i] <= 999
You are given an integer array nums
where the largest integer is unique.
Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1
otherwise.
\n
Example 1:
\n\n\nInput: nums = [3,6,1,0]\nOutput: 1\nExplanation: 6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: -1\nExplanation: 4 is less than twice the value of 3, so we return -1.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 50
0 <= nums[i] <= 100
nums
is unique.Given a string licensePlate
and an array of strings words
, find the shortest completing word in words
.
A completing word is a word that contains all the letters in licensePlate
. Ignore numbers and spaces in licensePlate
, and treat letters as case insensitive. If a letter appears more than once in licensePlate
, then it must appear in the word the same number of times or more.
For example, if licensePlate
= "aBc 12c"
, then it contains letters 'a'
, 'b'
(ignoring case), and 'c'
twice. Possible completing words are "abccdef"
, "caaacab"
, and "cbca"
.
Return the shortest completing word in words
. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words
.
\n
Example 1:
\n\n\nInput: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]\nOutput: "steps"\nExplanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n"step" contains 't' and 'p', but only contains 1 's'.\n"steps" contains 't', 'p', and both 's' characters.\n"stripe" is missing an 's'.\n"stepple" is missing an 's'.\nSince "steps" is the only word containing all the letters, that is the answer.\n\n\n
Example 2:
\n\n\nInput: licensePlate = "1s3 456", words = ["looks","pest","stew","show"]\nOutput: "pest"\nExplanation: licensePlate only contains the letter 's'. All the words contain 's', but among these "pest", "stew", and "show" are shortest. The answer is "pest" because it is the word that appears earliest of the 3.\n\n\n
\n
Constraints:
\n\n1 <= licensePlate.length <= 7
licensePlate
contains digits, letters (uppercase or lowercase), or space ' '
.1 <= words.length <= 1000
1 <= words[i].length <= 15
words[i]
consists of lower case English letters.A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
\n\nThe world is modeled as an m x n
binary grid isInfected
, where isInfected[i][j] == 0
represents uninfected cells, and isInfected[i][j] == 1
represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.
\n\nReturn the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.
\n\n\n
Example 1:
\n\nInput: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]\nOutput: 10\nExplanation: There are 2 contaminated regions.\nOn the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n\n\n\nOn the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n
\n
Example 2:
\n\nInput: isInfected = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 4\nExplanation: Even though there is only one cell saved, there are 4 walls built.\nNotice that walls are only built on the shared boundary of two different cells.\n\n\n
Example 3:
\n\n\nInput: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]\nOutput: 13\nExplanation: The region on the left only builds two new walls.\n\n\n
\n
Constraints:
\n\nm == isInfected.length
n == isInfected[i].length
1 <= m, n <= 50
isInfected[i][j]
is either 0
or 1
.You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
. The wheels can rotate freely and wrap around: for example we can turn '9'
to be '0'
, or '0'
to be '9'
. Each move consists of turning one wheel one slot.
The lock initially starts at '0000'
, a string representing the state of the 4 wheels.
You are given a list of deadends
dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a target
representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
\n
Example 1:
\n\n\nInput: deadends = ["0201","0101","0102","1212","2002"], target = "0202"\nOutput: 6\nExplanation: \nA sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".\nNote that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end "0102".\n\n\n
Example 2:
\n\n\nInput: deadends = ["8888"], target = "0009"\nOutput: 1\nExplanation: We can turn the last wheel in reverse to move from "0000" -> "0009".\n\n\n
Example 3:
\n\n\nInput: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"\nOutput: -1\nExplanation: We cannot reach the target without getting stuck.\n\n\n
\n
Constraints:
\n\n1 <= deadends.length <= 500
deadends[i].length == 4
target.length == 4
deadends
.target
and deadends[i]
consist of digits only.There is a safe protected by a password. The password is a sequence of n
digits where each digit can be in the range [0, k - 1]
.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n
digits that were entered each time you type a digit.
"345"
and you enter in "012345"
:\n\n\t0
, the most recent 3
digits is "0"
, which is incorrect.1
, the most recent 3
digits is "01"
, which is incorrect.2
, the most recent 3
digits is "012"
, which is incorrect.3
, the most recent 3
digits is "123"
, which is incorrect.4
, the most recent 3
digits is "234"
, which is incorrect.5
, the most recent 3
digits is "345"
, which is correct and the safe unlocks.Return any string of minimum length that will unlock the safe at some point of entering it.
\n\n\n
Example 1:
\n\n\nInput: n = 1, k = 2\nOutput: "10"\nExplanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.\n\n\n
Example 2:
\n\n\nInput: n = 2, k = 2\nOutput: "01100"\nExplanation: For each possible password:\n- "00" is typed in starting from the 4th digit.\n- "01" is typed in starting from the 1st digit.\n- "10" is typed in starting from the 3rd digit.\n- "11" is typed in starting from the 2nd digit.\nThus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.\n\n\n
\n
Constraints:
\n\n1 <= n <= 4
1 <= k <= 10
1 <= kn <= 4096
You are standing at position 0
on an infinite number line. There is a destination at position target
.
You can make some number of moves numMoves
so that:
ith
move (starting from i == 1
to i == numMoves
), you take i
steps in the chosen direction.Given the integer target
, return the minimum number of moves required (i.e., the minimum numMoves
) to reach the destination.
\n
Example 1:
\n\n\nInput: target = 2\nOutput: 3\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to -1 (2 steps).\nOn the 3rd move, we step from -1 to 2 (3 steps).\n\n\n
Example 2:
\n\n\nInput: target = 3\nOutput: 2\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to 3 (2 steps).\n\n\n
\n
Constraints:
\n\n-109 <= target <= 109
target != 0
You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.
\n\nTo make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed
, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
"ABC"
represents a triangular pattern with a 'C'
block stacked on top of an 'A'
(left) and 'B'
(right) block. Note that this is different from "BAC"
where 'B'
is on the left bottom and 'A'
is on the right bottom.You start with a bottom row of blocks bottom
, given as a single string, that you must use as the base of the pyramid.
Given bottom
and allowed
, return true
if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed
, or false
otherwise.
\n
Example 1:
\n\nInput: bottom = "BCD", allowed = ["BCC","CDE","CEA","FFF"]\nOutput: true\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build "CE" on level 2 and then build "A" on level 1.\nThere are three triangular patterns in the pyramid, which are "BCC", "CDE", and "CEA". All are allowed.\n\n\n
Example 2:
\n\nInput: bottom = "AAAA", allowed = ["AAB","AAC","BCD","BBE","DEF"]\nOutput: false\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.\n\n\n
\n
Constraints:
\n\n2 <= bottom.length <= 6
0 <= allowed.length <= 216
allowed[i].length == 3
{'A', 'B', 'C', 'D', 'E', 'F'}
.allowed
are unique.You are given a 2D integer array intervals
where intervals[i] = [starti, endi]
represents all the integers from starti
to endi
inclusively.
A containing set is an array nums
where each interval from intervals
has at least two integers in nums
.
intervals = [[1,3], [3,7], [8,9]]
, then [1,2,4,7,8,9]
and [2,3,4,8,9]
are containing sets.Return the minimum possible size of a containing set.
\n\n\n
Example 1:
\n\n\nInput: intervals = [[1,3],[3,7],[8,9]]\nOutput: 5\nExplanation: let nums = [2, 3, 4, 8, 9].\nIt can be shown that there cannot be any containing array of size 4.\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput: 3\nExplanation: let nums = [2, 3, 4].\nIt can be shown that there cannot be any containing array of size 2.\n\n\n
Example 3:
\n\n\nInput: intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput: 5\nExplanation: let nums = [1, 2, 3, 4, 5].\nIt can be shown that there cannot be any containing array of size 4.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 3000
intervals[i].length == 2
0 <= starti < endi <= 108
Special binary strings are binary strings with the following two properties:
\n\n0
's is equal to the number of 1
's.1
's as 0
's.You are given a special binary string s
.
A move consists of choosing two consecutive, non-empty, special substrings of s
, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.
Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.
\n\n\n
Example 1:
\n\n\nInput: s = "11011000"\nOutput: "11100100"\nExplanation: The strings "10" [occuring at s[1]] and "1100" [at s[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.\n\n\n
Example 2:
\n\n\nInput: s = "10"\nOutput: "10"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 50
s[i]
is either '0'
or '1'
.s
is a special binary string.Given two integers left
and right
, return the count of numbers in the inclusive range [left, right]
having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1
's present when written in binary.
21
written in binary is 10101
, which has 3
set bits.\n
Example 1:
\n\n\nInput: left = 6, right = 10\nOutput: 4\nExplanation:\n6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.\n\n\n
Example 2:
\n\n\nInput: left = 10, right = 15\nOutput: 5\nExplanation:\n10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.\n\n\n
\n
Constraints:
\n\n1 <= left <= right <= 106
0 <= right - left <= 104
You are given a string s
. We want to partition the string into as many parts as possible so that each letter appears in at most one part.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s
.
Return a list of integers representing the size of these parts.
\n\n\n
Example 1:
\n\n\nInput: s = "ababcbacadefegdehijhklij"\nOutput: [9,7,8]\nExplanation:\nThe partition is "ababcbaca", "defegde", "hijhklij".\nThis is a partition so that each letter appears in at most one part.\nA partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.\n\n\n
Example 2:
\n\n\nInput: s = "eccbbbbdec"\nOutput: [10]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of lowercase English letters.You are given a string s
. We want to partition the string into as many parts as possible so that each letter appears in at most one part. For example, the string "ababcc"
can be partitioned into ["abab", "cc"]
, but partitions such as ["aba", "bcc"]
or ["ab", "ab", "cc"]
are invalid.
Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s
.
Return a list of integers representing the size of these parts.
\n\n\n
Example 1:
\n\n\nInput: s = "ababcbacadefegdehijhklij"\nOutput: [9,7,8]\nExplanation:\nThe partition is "ababcbaca", "defegde", "hijhklij".\nThis is a partition so that each letter appears in at most one part.\nA partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.\n\n\n
Example 2:
\n\n\nInput: s = "eccbbbbdec"\nOutput: [10]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of lowercase English letters.You are given an integer n
. You have an n x n
binary grid grid
with all values initially 1
's except for some indices given in the array mines
. The ith
element of the array mines
is defined as mines[i] = [xi, yi]
where grid[xi][yi] == 0
.
Return the order of the largest axis-aligned plus sign of 1's contained in grid
. If there is none, return 0
.
An axis-aligned plus sign of 1
's of order k
has some center grid[r][c] == 1
along with four arms of length k - 1
going up, down, left, and right, and made of 1
's. Note that there could be 0
's or 1
's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1
's.
\n
Example 1:
\n\nInput: n = 5, mines = [[4,2]]\nOutput: 2\nExplanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\n\n\n
Example 2:
\n\nInput: n = 1, mines = [[0,0]]\nOutput: 0\nExplanation: There is no plus sign, so return 0.\n\n\n
\n
Constraints:
\n\n1 <= n <= 500
1 <= mines.length <= 5000
0 <= xi, yi < n
(xi, yi)
are unique.There are n
couples sitting in 2n
seats arranged in a row and want to hold hands.
The people and seats are represented by an integer array row
where row[i]
is the ID of the person sitting in the ith
seat. The couples are numbered in order, the first couple being (0, 1)
, the second couple being (2, 3)
, and so on with the last couple being (2n - 2, 2n - 1)
.
Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.
\n\n\n
Example 1:
\n\n\nInput: row = [0,2,1,3]\nOutput: 1\nExplanation: We only need to swap the second (row[1]) and third (row[2]) person.\n\n\n
Example 2:
\n\n\nInput: row = [3,2,0,1]\nOutput: 0\nExplanation: All couples are already seated side by side.\n\n\n
\n
Constraints:
\n\n2n == row.length
2 <= n <= 30
n
is even.0 <= row[i] < 2n
row
are unique.Given an m x n
matrix
, return true
if the matrix is Toeplitz. Otherwise, return false
.
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.
\n\n\n
Example 1:
\n\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: true\nExplanation:\nIn the above grid, the diagonals are:\n"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".\nIn each diagonal all elements are the same, so the answer is True.\n\n\n
Example 2:
\n\nInput: matrix = [[1,2],[2,2]]\nOutput: false\nExplanation:\nThe diagonal "[1, 2]" has different elements.\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 20
0 <= matrix[i][j] <= 99
\n
Follow up:
\n\nmatrix
is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?matrix
is so large that you can only load up a partial row into the memory at once?Given a string s
, rearrange the characters of s
so that any two adjacent characters are not the same.
Return any possible rearrangement of s
or return ""
if not possible.
\n
Example 1:
\nInput: s = \"aab\"\nOutput: \"aba\"\n
Example 2:
\nInput: s = \"aaab\"\nOutput: \"\"\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of lowercase English letters.You are given an integer array arr
.
We split arr
into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n\n\n
Example 2:
\n\n\nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 2000
0 <= arr[i] <= 108
You are given an integer array arr
of length n
that represents a permutation of the integers in the range [0, n - 1]
.
We split arr
into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [4,3,2,1,0]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\n\n\n
Example 2:
\n\n\nInput: arr = [1,0,2,3,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n\n\n
\n
Constraints:
\n\nn == arr.length
1 <= n <= 10
0 <= arr[i] < n
arr
are unique.Given an expression such as expression = "e + 8 - a + 5"
and an evaluation map such as {"e": 1}
(given in terms of evalvars = ["e"]
and evalints = [1]
), return a list of tokens representing the simplified expression, such as ["-1*a","14"]
"2x"
or "-x"
.Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.
\n\nexpression = "1 + 2 * 3"
has an answer of ["7"]
.The format of the output is as follows:
\n\n"b*a*c"
, only "a*b*c"
."a*a*b*c"
has degree 4
.["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]
.0
are not included.\n\t"0"
has an output of []
.Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1]
.
\n
Example 1:
\n\n\nInput: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]\nOutput: ["-1*a","14"]\n\n\n
Example 2:
\n\n\nInput: expression = "e - 8 + temperature - pressure", evalvars = ["e", "temperature"], evalints = [1, 12]\nOutput: ["-1*pressure","5"]\n\n\n
Example 3:
\n\n\nInput: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []\nOutput: ["1*e*e","-64"]\n\n\n
\n
Constraints:
\n\n1 <= expression.length <= 250
expression
consists of lowercase English letters, digits, '+'
, '-'
, '*'
, '('
, ')'
, ' '
.expression
does not contain any leading or trailing spaces.expression
are separated by a single space.0 <= evalvars.length <= 100
1 <= evalvars[i].length <= 20
evalvars[i]
consists of lowercase English letters.evalints.length == evalvars.length
-100 <= evalints[i] <= 100
You're given strings jewels
representing the types of stones that are jewels, and stones
representing the stones you have. Each character in stones
is a type of stone you have. You want to know how many of the stones you have are also jewels.
Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
\n
Example 1:
\nInput: jewels = \"aA\", stones = \"aAAbbbb\"\nOutput: 3\n
Example 2:
\nInput: jewels = \"z\", stones = \"ZZ\"\nOutput: 0\n\n
\n
Constraints:
\n\n1 <= jewels.length, stones.length <= 50
jewels
and stones
consist of only English letters.jewels
are unique.On an 2 x 3
board, there are five tiles labeled from 1
to 5
, and an empty square represented by 0
. A move consists of choosing 0
and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]
.
Given the puzzle board board
, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1
.
\n
Example 1:
\n\nInput: board = [[1,2,3],[4,0,5]]\nOutput: 1\nExplanation: Swap the 0 and the 5 in one move.\n\n\n
Example 2:
\n\nInput: board = [[1,2,3],[5,4,0]]\nOutput: -1\nExplanation: No number of moves will make the board solved.\n\n\n
Example 3:
\n\nInput: board = [[4,1,2],[5,0,3]]\nOutput: 5\nExplanation: 5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\n\n\n
\n
Constraints:
\n\nboard.length == 2
board[i].length == 3
0 <= board[i][j] <= 5
board[i][j]
is unique.You are given an integer array nums
of length n
which represents a permutation of all the integers in the range [0, n - 1]
.
The number of global inversions is the number of the different pairs (i, j)
where:
0 <= i < j < n
nums[i] > nums[j]
The number of local inversions is the number of indices i
where:
0 <= i < n - 1
nums[i] > nums[i + 1]
Return true
if the number of global inversions is equal to the number of local inversions.
\n
Example 1:
\n\n\nInput: nums = [1,0,2]\nOutput: true\nExplanation: There is 1 global inversion and 1 local inversion.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,0]\nOutput: false\nExplanation: There are 2 global inversions and 1 local inversion.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
0 <= nums[i] < n
nums
are unique.nums
is a permutation of all the numbers in the range [0, n - 1]
.In a string composed of 'L'
, 'R'
, and 'X'
characters, like "RXXLRXRXL"
, a move consists of either replacing one occurrence of "XL"
with "LX"
, or replacing one occurrence of "RX"
with "XR"
. Given the starting string start
and the ending string result
, return True
if and only if there exists a sequence of moves to transform start
to result
.
\n
Example 1:
\n\n\nInput: start = "RXXLRXRXL", result = "XRLXXRRLX"\nOutput: true\nExplanation: We can transform start to result following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\n\n\n
Example 2:
\n\n\nInput: start = "X", result = "L"\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= start.length <= 104
start.length == result.length
start
and result
will only consist of characters in 'L'
, 'R'
, and 'X'
.You are given an n x n
integer matrix grid
where each value grid[i][j]
represents the elevation at that point (i, j)
.
The rain starts to fall. At time t
, the depth of the water everywhere is t
. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both squares individually are at most t
. You can swim infinite distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.
Return the least time until you can reach the bottom right square (n - 1, n - 1)
if you start at the top left square (0, 0)
.
\n
Example 1:
\n\nInput: grid = [[0,2],[1,3]]\nOutput: 3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.\n\n\n
Example 2:
\n\nInput: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\nOutput: 16\nExplanation: The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] < n2
grid[i][j]
is unique.We build a table of n
rows (1-indexed). We start by writing 0
in the 1st
row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0
with 01
, and each occurrence of 1
with 10
.
n = 3
, the 1st
row is 0
, the 2nd
row is 01
, and the 3rd
row is 0110
.Given two integer n
and k
, return the kth
(1-indexed) symbol in the nth
row of a table of n
rows.
\n
Example 1:
\n\n\nInput: n = 1, k = 1\nOutput: 0\nExplanation: row 1: 0\n\n\n
Example 2:
\n\n\nInput: n = 2, k = 1\nOutput: 0\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\n
Example 3:
\n\n\nInput: n = 2, k = 2\nOutput: 1\nExplanation: \nrow 1: 0\nrow 2: 01\n\n\n
\n
Constraints:
\n\n1 <= n <= 30
1 <= k <= 2n - 1
Given four integers sx
, sy
, tx
, and ty
, return true
if it is possible to convert the point (sx, sy)
to the point (tx, ty)
through some operations, or false
otherwise.
The allowed operation on some point (x, y)
is to convert it to either (x, x + y)
or (x + y, y)
.
\n
Example 1:
\n\n\nInput: sx = 1, sy = 1, tx = 3, ty = 5\nOutput: true\nExplanation:\nOne series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)\n\n\n
Example 2:
\n\n\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: false\n\n\n
Example 3:
\n\n\nInput: sx = 1, sy = 1, tx = 1, ty = 1\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= sx, sy, tx, ty <= 109
There is a forest with an unknown number of rabbits. We asked n rabbits "How many rabbits have the same color as you?" and collected the answers in an integer array answers
where answers[i]
is the answer of the ith
rabbit.
Given the array answers
, return the minimum number of rabbits that could be in the forest.
\n
Example 1:
\n\n\nInput: answers = [1,1,2]\nOutput: 5\nExplanation:\nThe two rabbits that answered "1" could both be the same color, say red.\nThe rabbit that answered "2" can't be red or the answers would be inconsistent.\nSay the rabbit that answered "2" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n\n\n
Example 2:
\n\n\nInput: answers = [10,10,10]\nOutput: 11\n\n\n
\n
Constraints:
\n\n1 <= answers.length <= 1000
0 <= answers[i] < 1000
You are given an n x n
binary grid board
. In each move, you can swap any two rows with each other, or any two columns with each other.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1
.
A chessboard board is a board where no 0
's and no 1
's are 4-directionally adjacent.
\n
Example 1:
\n\nInput: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput: 2\nExplanation: One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.\n\n\n
Example 2:
\n\nInput: board = [[0,1],[1,0]]\nOutput: 0\nExplanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\n\n\n
Example 3:
\n\nInput: board = [[1,0],[1,0]]\nOutput: -1\nExplanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n\n\n
\n
Constraints:
\n\nn == board.length
n == board[i].length
2 <= n <= 30
board[i][j]
is either 0
or 1
.Given the root
of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.
\n
Example 1:
\n\nInput: root = [4,2,6,1,3]\nOutput: 1\n\n\n
Example 2:
\n\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n\n\n
\n
Constraints:
\n\n[2, 100]
.0 <= Node.val <= 105
\n
Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
\n", - "likes": 3547, - "dislikes": 425, - "stats": "{\"totalAccepted\": \"276.4K\", \"totalSubmission\": \"460.2K\", \"totalAcceptedRaw\": 276394, \"totalSubmissionRaw\": 460160, \"acRate\": \"60.1%\"}", + "likes": 3588, + "dislikes": 431, + "stats": "{\"totalAccepted\": \"289.2K\", \"totalSubmission\": \"479.6K\", \"totalAcceptedRaw\": 289181, \"totalSubmissionRaw\": 479634, \"acRate\": \"60.3%\"}", "similarQuestions": "[{\"title\": \"Binary Tree Inorder Traversal\", \"titleSlug\": \"binary-tree-inorder-traversal\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -29608,9 +29623,9 @@ "questionFrontendId": "784", "title": "Letter Case Permutation", "content": "Given a string s
, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
\n\n\n
Example 1:
\n\n\nInput: s = "a1b2"\nOutput: ["a1b2","a1B2","A1b2","A1B2"]\n\n\n
Example 2:
\n\n\nInput: s = "3z4"\nOutput: ["3z4","3Z4"]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 12
s
consists of lowercase English letters, uppercase English letters, and digits.There is an undirected graph with n
nodes, where each node is numbered between 0
and n - 1
. You are given a 2D array graph
, where graph[u]
is an array of nodes that node u
is adjacent to. More formally, for each v
in graph[u]
, there is an undirected edge between node u
and node v
. The graph has the following properties:
graph[u]
does not contain u
).graph[u]
does not contain duplicate values).v
is in graph[u]
, then u
is in graph[v]
(the graph is undirected).u
and v
such that there is no path between them.A graph is bipartite if the nodes can be partitioned into two independent sets A
and B
such that every edge in the graph connects a node in set A
and a node in set B
.
Return true
if and only if it is bipartite.
\n
Example 1:
\n\nInput: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]\nOutput: false\nExplanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.\n\n
Example 2:
\n\nInput: graph = [[1,3],[0,2],[1,3],[0,2]]\nOutput: true\nExplanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.\n\n
\n
Constraints:
\n\ngraph.length == n
1 <= n <= 100
0 <= graph[u].length < n
0 <= graph[u][i] <= n - 1
graph[u]
does not contain u
.graph[u]
are unique.graph[u]
contains v
, then graph[v]
contains u
.You are given a sorted integer array arr
containing 1
and prime numbers, where all the integers of arr
are unique. You are also given an integer k
.
For every i
and j
where 0 <= i < j < arr.length
, we consider the fraction arr[i] / arr[j]
.
Return the kth
smallest fraction considered. Return your answer as an array of integers of size 2
, where answer[0] == arr[i]
and answer[1] == arr[j]
.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,5], k = 3\nOutput: [2,5]\nExplanation: The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5.\n\n\n
Example 2:
\n\n\nInput: arr = [1,7], k = 1\nOutput: [1,7]\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 1000
1 <= arr[i] <= 3 * 104
arr[0] == 1
arr[i]
is a prime number for i > 0
.arr
are unique and sorted in strictly increasing order.1 <= k <= arr.length * (arr.length - 1) / 2
\nFollow up: Can you solve the problem with better than
O(n2)
complexity?",
- "likes": 2047,
- "dislikes": 117,
- "stats": "{\"totalAccepted\": \"156.7K\", \"totalSubmission\": \"229.2K\", \"totalAcceptedRaw\": 156719, \"totalSubmissionRaw\": 229232, \"acRate\": \"68.4%\"}",
+ "likes": 2078,
+ "dislikes": 119,
+ "stats": "{\"totalAccepted\": \"160.9K\", \"totalSubmission\": \"234.8K\", \"totalAcceptedRaw\": 160866, \"totalSubmissionRaw\": 234776, \"acRate\": \"68.5%\"}",
"similarQuestions": "[{\"title\": \"Kth Smallest Element in a Sorted Matrix\", \"titleSlug\": \"kth-smallest-element-in-a-sorted-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Kth Smallest Number in Multiplication Table\", \"titleSlug\": \"kth-smallest-number-in-multiplication-table\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Find K-th Smallest Pair Distance\", \"titleSlug\": \"find-k-th-smallest-pair-distance\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -29728,9 +29743,9 @@
"questionFrontendId": "787",
"title": "Cheapest Flights Within K Stops",
"content": "There are n
cities connected by some number of flights. You are given an array flights
where flights[i] = [fromi, toi, pricei]
indicates that there is a flight from city fromi
to city toi
with cost pricei
.
You are also given three integers src
, dst
, and k
, return the cheapest price from src
to dst
with at most k
stops. If there is no such route, return -1
.
\n
Example 1:
\n\nInput: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\nOutput: 700\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\n\n\n
Example 2:
\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput: 200\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\n\n\n
Example 3:
\n\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput: 500\nExplanation:\nThe graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
0 <= flights.length <= (n * (n - 1) / 2)
flights[i].length == 3
0 <= fromi, toi < n
fromi != toi
1 <= pricei <= 104
0 <= src, dst, k < n
src != dst
An integer x
is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x
. Each digit must be rotated - we cannot choose to leave it alone.
A number is valid if each digit remains a digit after rotation. For example:
\n\n0
, 1
, and 8
rotate to themselves,2
and 5
rotate to each other (in this case they are rotated in a different direction, in other words, 2
or 5
gets mirrored),6
and 9
rotate to each other, andGiven an integer n
, return the number of good integers in the range [1, n]
.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 4\nExplanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: n = 2\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0]
, and you are given a destination point target = [xtarget, ytarget]
that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts
, where ghosts[i] = [xi, yi]
represents the starting position of the ith
ghost. All inputs are integral coordinates.
Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.
\n\nYou escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.
\n\nReturn true
if it is possible to escape regardless of how the ghosts move, otherwise return false
.
\n
Example 1:
\n\n\nInput: ghosts = [[1,0],[0,3]], target = [0,1]\nOutput: true\nExplanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\n\n\n
Example 2:
\n\n\nInput: ghosts = [[1,0]], target = [2,0]\nOutput: false\nExplanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\n\n\n
Example 3:
\n\n\nInput: ghosts = [[2,0]], target = [1,0]\nOutput: false\nExplanation: The ghost can reach the target at the same time as you.\n\n\n
\n
Constraints:
\n\n1 <= ghosts.length <= 100
ghosts[i].length == 2
-104 <= xi, yi <= 104
target.length == 2
-104 <= xtarget, ytarget <= 104
You have two types of tiles: a 2 x 1
domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n
board. Since the answer may be very large, return it modulo 109 + 7
.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
\n\n\n
Example 1:
\n\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are show above.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You have two types of tiles: a 2 x 1
domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n
board. Since the answer may be very large, return it modulo 109 + 7
.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
\n\n\n
Example 1:
\n\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are shown above.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You are given two strings order
and s
. All the characters of order
are unique and were sorted in some custom order previously.
Permute the characters of s
so that they match the order that order
was sorted. More specifically, if a character x
occurs before a character y
in order
, then x
should occur before y
in the permuted string.
Return any permutation of s
that satisfies this property.
\n
Example 1:
\n\nInput: order = "cba", s = "abcd"
\n\nOutput: "cbad"
\n\nExplanation: "a"
, "b"
, "c"
appear in order, so the order of "a"
, "b"
, "c"
should be "c"
, "b"
, and "a"
.
Since "d"
does not appear in order
, it can be at any position in the returned string. "dcba"
, "cdba"
, "cbda"
are also valid outputs.
Example 2:
\n\nInput: order = "bcafg", s = "abcd"
\n\nOutput: "bcad"
\n\nExplanation: The characters "b"
, "c"
, and "a"
from order
dictate the order for the characters in s
. The character "d"
in s
does not appear in order
, so its position is flexible.
Following the order of appearance in order
, "b"
, "c"
, and "a"
from s
should be arranged as "b"
, "c"
, "a"
. "d"
can be placed at any position since it's not in order. The output "bcad"
correctly follows this rule. Other arrangements like "dbca"
or "bcda"
would also be valid, as long as "b"
, "c"
, "a"
maintain their order.
\n
Constraints:
\n\n1 <= order.length <= 26
1 <= s.length <= 200
order
and s
consist of lowercase English letters.order
are unique.Given a string s
and an array of strings words
, return the number of words[i]
that is a subsequence of s
.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
\n\n"ace"
is a subsequence of "abcde"
.\n
Example 1:
\n\n\nInput: s = "abcde", words = ["a","bb","acd","ace"]\nOutput: 3\nExplanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".\n\n\n
Example 2:
\n\n\nInput: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
s
and words[i]
consist of only lowercase English letters.Let f(x)
be the number of zeroes at the end of x!
. Recall that x! = 1 * 2 * 3 * ... * x
and by convention, 0! = 1
.
f(3) = 0
because 3! = 6
has no zeroes at the end, while f(11) = 2
because 11! = 39916800
has two zeroes at the end.Given an integer k
, return the number of non-negative integers x
have the property that f(x) = k
.
\n
Example 1:
\n\n\nInput: k = 0\nOutput: 5\nExplanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.\n\n\n
Example 2:
\n\n\nInput: k = 5\nOutput: 0\nExplanation: There is no x such that x! ends in k = 5 zeroes.\n\n\n
Example 3:
\n\n\nInput: k = 3\nOutput: 5\n\n\n
\n
Constraints:
\n\n0 <= k <= 109
Given a Tic-Tac-Toe board as a string array board
, return true
if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3
array that consists of characters ' '
, 'X'
, and 'O'
. The ' '
character represents an empty square.
Here are the rules of Tic-Tac-Toe:
\n\n' '
.'X'
characters, while the second player always places 'O'
characters.'X'
and 'O'
characters are always placed into empty squares, never filled ones.\n
Example 1:
\n\nInput: board = ["O "," "," "]\nOutput: false\nExplanation: The first player always plays "X".\n\n\n
Example 2:
\n\nInput: board = ["XOX"," X "," "]\nOutput: false\nExplanation: Players take turns making moves.\n\n\n
Example 3:
\n\nInput: board = ["XOX","O O","XOX"]\nOutput: true\n\n\n
\n
Constraints:
\n\nboard.length == 3
board[i].length == 3
board[i][j]
is either 'X'
, 'O'
, or ' '
.Given an integer array nums
and two integers left
and right
, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]
.
The test cases are generated so that the answer will fit in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,4,3], left = 2, right = 3\nOutput: 3\nExplanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\n\n\n
Example 2:
\n\n\nInput: nums = [2,9,2,5,6], left = 2, right = 8\nOutput: 7\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= left <= right <= 109
Given two strings s
and goal
, return true
if and only if s
can become goal
after some number of shifts on s
.
A shift on s
consists of moving the leftmost character of s
to the rightmost position.
s = "abcde"
, then it will be "bcdea"
after one shift.\n
Example 1:
\nInput: s = \"abcde\", goal = \"cdeab\"\nOutput: true\n
Example 2:
\nInput: s = \"abcde\", goal = \"abced\"\nOutput: false\n\n
\n
Constraints:
\n\n1 <= s.length, goal.length <= 100
s
and goal
consist of lowercase English letters.Given a directed acyclic graph (DAG) of n
nodes labeled from 0
to n - 1
, find all possible paths from node 0
to node n - 1
and return them in any order.
The graph is given as follows: graph[i]
is a list of all nodes you can visit from node i
(i.e., there is a directed edge from node i
to node graph[i][j]
).
\n
Example 1:
\n\nInput: graph = [[1,2],[3],[3],[]]\nOutput: [[0,1,3],[0,2,3]]\nExplanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.\n\n\n
Example 2:
\n\nInput: graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n\n\n
\n
Constraints:
\n\nn == graph.length
2 <= n <= 15
0 <= graph[i][j] < n
graph[i][j] != i
(i.e., there will be no self-loops).graph[i]
are unique.You are given an array nums
. You can rotate it by a non-negative integer k
so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]
. Afterward, any entries that are less than or equal to their index are worth one point.
nums = [2,4,1,3,0]
, and we rotate by k = 2
, it becomes [1,3,0,2,4]
. This is worth 3
points because 1 > 0
[no points], 3 > 1
[no points], 0 <= 2
[one point], 2 <= 3
[one point], 4 <= 4
[one point].Return the rotation index k
that corresponds to the highest score we can achieve if we rotated nums
by it. If there are multiple answers, return the smallest such index k
.
\n
Example 1:
\n\n\nInput: nums = [2,3,1,4,0]\nOutput: 3\nExplanation: Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,0,2,4]\nOutput: 0\nExplanation: nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] < nums.length
We stack glasses in a pyramid, where the first row has 1
glass, the second row has 2
glasses, and so on until the 100th row. Each glass holds one cup of champagne.
Then, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)
\r\n\r\nFor example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.
\r\n\r\nNow after pouring some non-negative integer cups of champagne, return how full the jth
glass in the ith
row is (both i
and j
are 0-indexed.)
\r\n
Example 1:
\r\n\r\n\r\nInput: poured = 1, query_row = 1, query_glass = 1\r\nOutput: 0.00000\r\nExplanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: poured = 2, query_row = 1, query_glass = 1\r\nOutput: 0.50000\r\nExplanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: poured = 100000009, query_row = 33, query_glass = 17\r\nOutput: 1.00000\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n0 <= poured <= 109
0 <= query_glass <= query_row < 100
You are given two integer arrays of the same length nums1
and nums2
. In one operation, you are allowed to swap nums1[i]
with nums2[i]
.
nums1 = [1,2,3,8]
, and nums2 = [5,6,7,4]
, you can swap the element at i = 3
to obtain nums1 = [1,2,3,4]
and nums2 = [5,6,7,8]
.Return the minimum number of needed operations to make nums1
and nums2
strictly increasing. The test cases are generated so that the given input always makes it possible.
An array arr
is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]
.
\n
Example 1:
\n\n\nInput: nums1 = [1,3,5,4], nums2 = [1,2,3,7]\nOutput: 1\nExplanation: \nSwap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.\n\n\n
Example 2:
\n\n\nInput: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\nOutput: 1\n\n\n
\n
Constraints:
\n\n2 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 2 * 105
There is a directed graph of n
nodes with each node labeled from 0
to n - 1
. The graph is represented by a 0-indexed 2D integer array graph
where graph[i]
is an integer array of nodes adjacent to node i
, meaning there is an edge from node i
to each node in graph[i]
.
A node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).
\n\nReturn an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.
\n\n\n
Example 1:
\n\nInput: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput: [2,4,5,6]\nExplanation: The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\n\n
Example 2:
\n\n\nInput: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput: [4]\nExplanation:\nOnly node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n\n\n
\n
Constraints:
\n\nn == graph.length
1 <= n <= 104
0 <= graph[i].length <= n
0 <= graph[i][j] <= n - 1
graph[i]
is sorted in a strictly increasing order.[1, 4 * 104]
.You are given an m x n
binary grid
, where each 1
represents a brick and 0
represents an empty space. A brick is stable if:
You are also given an array hits
, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli)
. The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid
(i.e., it does not land on other stable bricks).
Return an array result
, where each result[i]
is the number of bricks that will fall after the ith
erasure is applied.
Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.
\n\n\n
Example 1:
\n\n\nInput: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\nOutput: [2]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,1,0]]\nWe erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,1,1,0]]\nThe two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n[[1,0,0,0],\n [0,0,0,0]]\nHence the result is [2].\n\n\n
Example 2:
\n\n\nInput: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\nOutput: [0,0]\nExplanation: Starting with the grid:\n[[1,0,0,0],\n [1,1,0,0]]\nWe erase the underlined brick at (1,1), resulting in the grid:\n[[1,0,0,0],\n [1,0,0,0]]\nAll remaining bricks are still stable, so no bricks fall. The grid remains the same:\n[[1,0,0,0],\n [1,0,0,0]]\nNext, we erase the underlined brick at (1,0), resulting in the grid:\n[[1,0,0,0],\n [0,0,0,0]]\nOnce again, all remaining bricks are still stable, so no bricks fall.\nHence the result is [0,0].\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 200
grid[i][j]
is 0
or 1
.1 <= hits.length <= 4 * 104
hits[i].length == 2
0 <= xi <= m - 1
0 <= yi <= n - 1
(xi, yi)
are unique.International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:
\n\n'a'
maps to ".-"
,'b'
maps to "-..."
,'c'
maps to "-.-."
, and so on.For convenience, the full table for the 26
letters of the English alphabet is given below:
\n[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]\n\n
Given an array of strings words
where each word can be written as a concatenation of the Morse code of each letter.
"cab"
can be written as "-.-..--..."
, which is the concatenation of "-.-."
, ".-"
, and "-..."
. We will call such a concatenation the transformation of a word.Return the number of different transformations among all words we have.
\n\n\n
Example 1:
\n\n\nInput: words = ["gin","zen","gig","msg"]\nOutput: 2\nExplanation: The transformation of each word is:\n"gin" -> "--...-."\n"zen" -> "--...-."\n"gig" -> "--...--."\n"msg" -> "--...--."\nThere are 2 different transformations: "--...-." and "--...--.".\n\n\n
Example 2:
\n\n\nInput: words = ["a"]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 12
words[i]
consists of lowercase English letters.You are given an integer array nums
.
You should move each element of nums
into one of the two arrays A
and B
such that A
and B
are non-empty, and average(A) == average(B)
.
Return true
if it is possible to achieve that and false
otherwise.
Note that for an array arr
, average(arr)
is the sum of all the elements of arr
over the length of arr
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6,7,8]\nOutput: true\nExplanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\n\n\n
Example 2:
\n\n\nInput: nums = [3,1]\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 30
0 <= nums[i] <= 104
You are given a string s
of lowercase English letters and an array widths
denoting how many pixels wide each lowercase English letter is. Specifically, widths[0]
is the width of 'a'
, widths[1]
is the width of 'b'
, and so on.
You are trying to write s
across several lines, where each line is no longer than 100
pixels. Starting at the beginning of s
, write as many letters on the first line such that the total width does not exceed 100
pixels. Then, from where you stopped in s
, continue writing as many letters as you can on the second line. Continue this process until you have written all of s
.
Return an array result
of length 2 where:
result[0]
is the total number of lines.result[1]
is the width of the last line in pixels.\n
Example 1:
\n\n\nInput: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "abcdefghijklmnopqrstuvwxyz"\nOutput: [3,60]\nExplanation: You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.\n\n
Example 2:
\n\n\nInput: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = "bbbcccdddaaa"\nOutput: [2,4]\nExplanation: You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.\n\n
\n
Constraints:
\n\nwidths.length == 26
2 <= widths[i] <= 10
1 <= s.length <= 1000
s
contains only lowercase English letters.There is a city composed of n x n
blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n
integer matrix grid
where grid[r][c]
represents the height of the building located in the block at row r
and column c
.
A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.
\n\nWe are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0
-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.
Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.
\n\n\n
Example 1:
\n\nInput: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\nOutput: 35\nExplanation: The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]\n\n\n
Example 2:
\n\n\nInput: grid = [[0,0,0],[0,0,0],[0,0,0]]\nOutput: 0\nExplanation: Increasing the height of any building will result in the skyline changing.\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[r].length
2 <= n <= 50
0 <= grid[r][c] <= 100
There are two types of soup: type A and type B. Initially, we have n
ml of each type of soup. There are four kinds of operations:
100
ml of soup A and 0
ml of soup B,75
ml of soup A and 25
ml of soup B,50
ml of soup A and 50
ml of soup B, and25
ml of soup A and 75
ml of soup B.When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25
. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.
Note that we do not have an operation where all 100
ml's of soup B are used first.
Return the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: n = 50\nOutput: 0.62500\nExplanation: If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.\n\n\n
Example 2:
\n\n\nInput: n = 100\nOutput: 0.71875\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
Sometimes people repeat letters to represent extra feeling. For example:
\n\n"hello" -> "heeellooo"
"hi" -> "hiiii"
In these strings like "heeellooo"
, we have groups of adjacent letters that are all the same: "h"
, "eee"
, "ll"
, "ooo"
.
You are given a string s
and an array of query strings words
. A query word is stretchy if it can be made to be equal to s
by any number of applications of the following extension operation: choose a group consisting of characters c
, and add some number of characters c
to the group so that the size of the group is three or more.
"hello"
, we could do an extension on the group "o"
to get "hellooo"
, but we cannot get "helloo"
since the group "oo"
has a size less than three. Also, we could do another extension like "ll" -> "lllll"
to get "helllllooo"
. If s = "helllllooo"
, then the query word "hello"
would be stretchy because of these two extension operations: query = "hello" -> "hellooo" -> "helllllooo" = s
.Return the number of query strings that are stretchy.
\n\n\n
Example 1:
\n\n\nInput: s = "heeellooo", words = ["hello", "hi", "helo"]\nOutput: 1\nExplanation: \nWe can extend "e" and "o" in the word "hello" to get "heeellooo".\nWe can't extend "helo" to get "heeellooo" because the group "ll" is not size 3 or more.\n\n\n
Example 2:
\n\n\nInput: s = "zzzzzyyyyy", words = ["zzyy","zy","zyy"]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= s.length, words.length <= 100
1 <= words[i].length <= 100
s
and words[i]
consist of lowercase letters.You are given an array of integers nums
represents the numbers written on a chalkboard.
Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0
, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0
.
Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0
, then that player wins.
Return true
if and only if Alice wins the game, assuming both players play optimally.
\n
Example 1:
\n\n\nInput: nums = [1,1,2]\nOutput: false\nExplanation: \nAlice has two choices: erase 1 or erase 2. \nIf she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1]\nOutput: true\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] < 216
A website domain "discuss.leetcode.com"
consists of various subdomains. At the top level, we have "com"
, at the next level, we have "leetcode.com"
and at the lowest level, "discuss.leetcode.com"
. When we visit a domain like "discuss.leetcode.com"
, we will also visit the parent domains "leetcode.com"
and "com"
implicitly.
A count-paired domain is a domain that has one of the two formats "rep d1.d2.d3"
or "rep d1.d2"
where rep
is the number of visits to the domain and d1.d2.d3
is the domain itself.
"9001 discuss.leetcode.com"
is a count-paired domain that indicates that discuss.leetcode.com
was visited 9001
times.Given an array of count-paired domains cpdomains
, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.
\n
Example 1:
\n\n\nInput: cpdomains = ["9001 discuss.leetcode.com"]\nOutput: ["9001 leetcode.com","9001 discuss.leetcode.com","9001 com"]\nExplanation: We only have one website domain: "discuss.leetcode.com".\nAs discussed above, the subdomain "leetcode.com" and "com" will also be visited. So they will all be visited 9001 times.\n\n\n
Example 2:
\n\n\nInput: cpdomains = ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"]\nOutput: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"]\nExplanation: We will visit "google.mail.com" 900 times, "yahoo.com" 50 times, "intel.mail.com" once and "wiki.org" 5 times.\nFor the subdomains, we will visit "mail.com" 900 + 1 = 901 times, "com" 900 + 50 + 1 = 951 times, and "org" 5 times.\n\n\n
\n
Constraints:
\n\n1 <= cpdomain.length <= 100
1 <= cpdomain[i].length <= 100
cpdomain[i]
follows either the "repi d1i.d2i.d3i"
format or the "repi d1i.d2i"
format.repi
is an integer in the range [1, 104]
.d1i
, d2i
, and d3i
consist of lowercase English letters.Given an array of points on the X-Y plane points
where points[i] = [xi, yi]
, return the area of the largest triangle that can be formed by any three different points. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\nInput: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput: 2.00000\nExplanation: The five points are shown in the above figure. The red triangle is the largest.\n\n\n
Example 2:
\n\n\nInput: points = [[1,0],[0,0],[0,1]]\nOutput: 0.50000\n\n\n
\n
Constraints:
\n\n3 <= points.length <= 50
-50 <= xi, yi <= 50
You are given an integer array nums
and an integer k
. You can partition the array into at most k
non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums
, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: nums = [9,1,2,3,9], k = 3\nOutput: 20.00000\nExplanation: \nThe best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5,6,7], k = 4\nOutput: 20.50000\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 104
1 <= k <= nums.length
Given the root
of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1
has been removed.
A subtree of a node node
is node
plus every node that is a descendant of node
.
\n
Example 1:
\n\nInput: root = [1,null,0,0,1]\nOutput: [1,null,0,null,1]\nExplanation: \nOnly the red nodes satisfy the property "every subtree not containing a 1".\nThe diagram on the right represents the answer.\n\n\n
Example 2:
\n\nInput: root = [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\n\n\n
Example 3:
\n\nInput: root = [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n\n\n
\n
Constraints:
\n\n[1, 200]
.Node.val
is either 0
or 1
.You are given an array routes
representing bus routes where routes[i]
is a bus route that the ith
bus repeats forever.
routes[0] = [1, 5, 7]
, this means that the 0th
bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...
forever.You will start at the bus stop source
(You are not on any bus initially), and you want to go to the bus stop target
. You can travel between bus stops by buses only.
Return the least number of buses you must take to travel from source
to target
. Return -1
if it is not possible.
\n
Example 1:
\n\n\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput: 2\nExplanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\n\n\n
Example 2:
\n\n\nInput: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput: -1\n\n\n
\n\n
\n
Constraints:
\n\n1 <= routes.length <= 500
.1 <= routes[i].length <= 105
routes[i]
are unique.sum(routes[i].length) <= 105
0 <= routes[i][j] < 106
0 <= source, target < 106
We had some 2-dimensional coordinates, like "(1, 3)"
or "(2, 0.5)"
. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
"(1, 3)"
becomes s = "(13)"
and "(2, 0.5)"
becomes s = "(205)"
.Return a list of strings representing all possibilities for what our original coordinates could have been.
\n\nOur original representation never had extraneous zeroes, so we never started with numbers like "00"
, "0.0"
, "0.00"
, "1.0"
, "001"
, "00.01"
, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like ".1"
.
The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
\n\n\n
Example 1:
\n\n\nInput: s = "(123)"\nOutput: ["(1, 2.3)","(1, 23)","(1.2, 3)","(12, 3)"]\n\n\n
Example 2:
\n\n\nInput: s = "(0123)"\nOutput: ["(0, 1.23)","(0, 12.3)","(0, 123)","(0.1, 2.3)","(0.1, 23)","(0.12, 3)"]\nExplanation: 0.0, 00, 0001 or 00.01 are not allowed.\n\n\n
Example 3:
\n\n\nInput: s = "(00011)"\nOutput: ["(0, 0.011)","(0.001, 1)"]\n\n\n
\n
Constraints:
\n\n4 <= s.length <= 12
s[0] == '('
and s[s.length - 1] == ')'
.s
are digits.You are given the head
of a linked list containing unique integer values and an integer array nums
that is a subset of the linked list values.
Return the number of connected components in nums
where two values are connected if they appear consecutively in the linked list.
\n
Example 1:
\n\nInput: head = [0,1,2,3], nums = [0,1,3]\nOutput: 2\nExplanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.\n\n\n
Example 2:
\n\nInput: head = [0,1,2,3,4], nums = [0,3,1,4]\nOutput: 2\nExplanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.\n\n\n
\n
Constraints:
\n\nn
.1 <= n <= 104
0 <= Node.val < n
Node.val
are unique.1 <= nums.length <= n
0 <= nums[i] < n
nums
are unique.Your car starts at position 0
and speed +1
on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A'
(accelerate) and 'R'
(reverse):
'A'
, your car does the following:\n\n\tposition += speed
speed *= 2
'R'
, your car does the following:\n\tspeed = -1
speed = 1
For example, after commands "AAR"
, your car goes to positions 0 --> 1 --> 3 --> 3
, and your speed goes to 1 --> 2 --> 4 --> -1
.
Given a target position target
, return the length of the shortest sequence of instructions to get there.
\n
Example 1:
\n\n\nInput: target = 3\nOutput: 2\nExplanation: \nThe shortest instruction sequence is "AA".\nYour position goes from 0 --> 1 --> 3.\n\n\n
Example 2:
\n\n\nInput: target = 6\nOutput: 5\nExplanation: \nThe shortest instruction sequence is "AAARA".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.\n\n\n
\n
Constraints:
\n\n1 <= target <= 104
Given a string paragraph
and a string array of the banned words banned
, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
\n
Example 1:
\n\n\nInput: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]\nOutput: "ball"\nExplanation: \n"hit" occurs 3 times, but it is a banned word.\n"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as "ball,"), \nand that "hit" isn't the answer even though it occurs more because it is banned.\n\n\n
Example 2:
\n\n\nInput: paragraph = "a.", banned = []\nOutput: "a"\n\n\n
\n
Constraints:
\n\n1 <= paragraph.length <= 1000
' '
, or one of the symbols: "!?',;."
.0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i]
consists of only lowercase English letters.Given a string paragraph
and a string array of the banned words banned
, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.
The words in paragraph
are case-insensitive and the answer should be returned in lowercase.
Note that words can not contain punctuation symbols.
\n\n\n
Example 1:
\n\n\nInput: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]\nOutput: "ball"\nExplanation: \n"hit" occurs 3 times, but it is a banned word.\n"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as "ball,"), \nand that "hit" isn't the answer even though it occurs more because it is banned.\n\n\n
Example 2:
\n\n\nInput: paragraph = "a.", banned = []\nOutput: "a"\n\n\n
\n
Constraints:
\n\n1 <= paragraph.length <= 1000
' '
, or one of the symbols: "!?',;."
.0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i]
consists of only lowercase English letters.A valid encoding of an array of words
is any reference string s
and array of indices indices
such that:
words.length == indices.length
s
ends with the '#'
character.indices[i]
, the substring of s
starting from indices[i]
and up to (but not including) the next '#'
character is equal to words[i]
.Given an array of words
, return the length of the shortest reference string s
possible of any valid encoding of words
.
\n
Example 1:
\n\n\nInput: words = ["time", "me", "bell"]\nOutput: 10\nExplanation: A valid encoding would be s = "time#bell#" and indices = [0, 2, 5
].\nwords[0] = "time", the substring of s starting from indices[0] = 0 to the next '#' is underlined in "time#bell#"\nwords[1] = "me", the substring of s starting from indices[1] = 2 to the next '#' is underlined in "time#bell#"\nwords[2] = "bell", the substring of s starting from indices[2] = 5 to the next '#' is underlined in "time#bell#"\n
\n\nExample 2:
\n\n\nInput: words = ["t"]\nOutput: 2\nExplanation: A valid encoding would be s = "t#" and indices = [0].\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i]
consists of only lowercase letters.Given a string s
and a character c
that occurs in s
, return an array of integers answer
where answer.length == s.length
and answer[i]
is the distance from index i
to the closest occurrence of character c
in s
.
The distance between two indices i
and j
is abs(i - j)
, where abs
is the absolute value function.
\n
Example 1:
\n\n\nInput: s = "loveleetcode", c = "e"\nOutput: [3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.\n\n\n
Example 2:
\n\n\nInput: s = "aaab", c = "b"\nOutput: [3,2,1,0]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s[i]
and c
are lowercase English letters.c
occurs at least once in s
.You are given two 0-indexed integer arrays fronts
and backs
of length n
, where the ith
card has the positive integer fronts[i]
printed on the front and backs[i]
printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).
After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.
\n\nReturn the minimum possible good integer after flipping the cards. If there are no good integers, return 0
.
\n
Example 1:
\n\n\nInput: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]\nOutput: 2\nExplanation:\nIf we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.\n\n\n
Example 2:
\n\n\nInput: fronts = [1], backs = [1]\nOutput: 0\nExplanation:\nThere are no good integers no matter how we flip the cards, so we return 0.\n\n\n
\n
Constraints:
\n\nn == fronts.length == backs.length
1 <= n <= 1000
1 <= fronts[i], backs[i] <= 2000
Given an array of unique integers, arr
, where each integer arr[i]
is strictly greater than 1
.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
\n\nReturn the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: arr = [2,4]\nOutput: 3\nExplanation: We can make these trees: [2], [4], [4, 2, 2]
\n\nExample 2:
\n\n\nInput: arr = [2,4,5,10]\nOutput: 7\nExplanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]
.
\n\n\n
Constraints:
\n\n1 <= arr.length <= 1000
2 <= arr[i] <= 109
arr
are unique.You are given a string sentence
that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.
We would like to convert the sentence to "Goat Latin" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:
\n\n'a'
, 'e'
, 'i'
, 'o'
, or 'u'
), append "ma"
to the end of the word.\n\n\t"apple"
becomes "applema"
."ma"
.\n\t"goat"
becomes "oatgma"
.'a'
to the end of each word per its word index in the sentence, starting with 1
.\n\t"a"
added to the end, the second word gets "aa"
added to the end, and so on.Return the final sentence representing the conversion from sentence to Goat Latin.
\n\n\n
Example 1:
\nInput: sentence = \"I speak Goat Latin\"\nOutput: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\n
Example 2:
\nInput: sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 150
sentence
consists of English letters and spaces.sentence
has no leading or trailing spaces.sentence
are separated by a single space.There are n
persons on a social media website. You are given an integer array ages
where ages[i]
is the age of the ith
person.
A Person x
will not send a friend request to a person y
(x != y
) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
Otherwise, x
will send a friend request to y
.
Note that if x
sends a request to y
, y
will not necessarily send a request to x
. Also, a person will not send a friend request to themself.
Return the total number of friend requests made.
\n\n\n
Example 1:
\n\n\nInput: ages = [16,16]\nOutput: 2\nExplanation: 2 people friend request each other.\n\n\n
Example 2:
\n\n\nInput: ages = [16,17,18]\nOutput: 2\nExplanation: Friend requests are made 17 -> 16, 18 -> 17.\n\n\n
Example 3:
\n\n\nInput: ages = [20,30,100,110,120]\nOutput: 3\nExplanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.\n\n\n
\n
Constraints:
\n\nn == ages.length
1 <= n <= 2 * 104
1 <= ages[i] <= 120
You have n
jobs and m
workers. You are given three arrays: difficulty
, profit
, and worker
where:
difficulty[i]
and profit[i]
are the difficulty and the profit of the ith
job, andworker[j]
is the ability of jth
worker (i.e., the jth
worker can only complete a job with difficulty at most worker[j]
).Every worker can be assigned at most one job, but one job can be completed multiple times.
\n\n$1
, then the total profit will be $3
. If a worker cannot complete any job, their profit is $0
.Return the maximum profit we can achieve after assigning the workers to the jobs.
\n\n\n
Example 1:
\n\n\nInput: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput: 100\nExplanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.\n\n\n
Example 2:
\n\n\nInput: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == difficulty.length
n == profit.length
m == worker.length
1 <= n, m <= 104
1 <= difficulty[i], profit[i], worker[i] <= 105
You are given an n x n
binary matrix grid
. You are allowed to change at most one 0
to be 1
.
Return the size of the largest island in grid
after applying this operation.
An island is a 4-directionally connected group of 1
s.
\n
Example 1:
\n\n\nInput: grid = [[1,0],[0,1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\n\n\n
Example 2:
\n\n\nInput: grid = [[1,1],[1,0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\n\n
Example 3:
\n\n\nInput: grid = [[1,1],[1,1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 4.\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
1 <= n <= 500
grid[i][j]
is either 0
or 1
.Let's define a function countUniqueChars(s)
that returns the number of unique characters in s
.
countUniqueChars(s)
if s = "LEETCODE"
then "L"
, "T"
, "C"
, "O"
, "D"
are the unique characters since they appear only once in s
, therefore countUniqueChars(s) = 5
.Given a string s
, return the sum of countUniqueChars(t)
where t
is a substring of s
. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
\n\n\n
Example 1:
\n\n\nInput: s = "ABC"\nOutput: 10\nExplanation: All possible substrings are: "A","B","C","AB","BC" and "ABC".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n\n\n
Example 2:
\n\n\nInput: s = "ABA"\nOutput: 8\nExplanation: The same as example 1, except countUniqueChars
("ABA") = 1.\n
\n\nExample 3:
\n\n\nInput: s = "LEETCODE"\nOutput: 92\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of uppercase English letters only.Given an integer n
, return the number of ways you can write n
as the sum of consecutive positive integers.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: 2\nExplanation: 5 = 2 + 3\n\n\n
Example 2:
\n\n\nInput: n = 9\nOutput: 3\nExplanation: 9 = 4 + 5 = 2 + 3 + 4\n\n\n
Example 3:
\n\n\nInput: n = 15\nOutput: 4\nExplanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
In a string s
of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like s = "abbxxxxzyy"
has the groups "a"
, "bb"
, "xxxx"
, "z"
, and "yy"
.
A group is identified by an interval [start, end]
, where start
and end
denote the start and end indices (inclusive) of the group. In the above example, "xxxx"
has the interval [3,6]
.
A group is considered large if it has 3 or more characters.
\n\nReturn the intervals of every large group sorted in increasing order by start index.
\n\n\n
Example 1:
\n\n\nInput: s = "abbxxxxzzy"\nOutput: [[3,6]]\nExplanation: "xxxx" is the only
large group with start index 3 and end index 6.\n
\n\nExample 2:
\n\n\nInput: s = "abc"\nOutput: []\nExplanation: We have groups "a", "b", and "c", none of which are large groups.\n\n\n
Example 3:
\n\n\nInput: s = "abcdddeeeeaabbbcd"\nOutput: [[3,5],[6,9],[12,14]]\nExplanation: The large groups are "ddd", "eeee", and "bbb".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
contains lowercase English letters only.You are given a personal information string s
, representing either an email address or a phone number. Return the masked personal information using the below rules.
Email address:
\n\nAn email address is:
\n\n'@'
symbol, followed by'.'
somewhere in the middle (not the first or last character).To mask an email:
\n\n"*****"
.Phone number:
\n\nA phone number is formatted as follows:
\n\n{'+', '-', '(', ')', ' '}
separate the above digits in some way.To mask a phone number:
\n\n"***-***-XXXX"
if the country code has 0 digits."+*-***-***-XXXX"
if the country code has 1 digit."+**-***-***-XXXX"
if the country code has 2 digits."+***-***-***-XXXX"
if the country code has 3 digits."XXXX"
is the last 4 digits of the local number.\n
Example 1:
\n\n\nInput: s = "LeetCode@LeetCode.com"\nOutput: "l*****e@leetcode.com"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\n\n\n
Example 2:
\n\n\nInput: s = "AB@qq.com"\nOutput: "a*****b@qq.com"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though "ab" is 2 characters, it still must have 5 asterisks in the middle.\n\n\n
Example 3:
\n\n\nInput: s = "1(234)567-890"\nOutput: "***-***-7890"\nExplanation: s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is "***-***-7890".\n\n\n
\n
Constraints:
\n\ns
is either a valid email or a phone number.s
is an email:\n\t8 <= s.length <= 40
s
consists of uppercase and lowercase English letters and exactly one '@'
symbol and '.'
symbol.s
is a phone number:\n\t10 <= s.length <= 20
s
consists of digits, spaces, and the symbols '('
, ')'
, '-'
, and '+'
.Given an n x n
binary matrix image
, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
\n\n[1,1,0]
horizontally results in [0,1,1]
.To invert an image means that each 0
is replaced by 1
, and each 1
is replaced by 0
.
[0,1,1]
results in [1,0,0]
.\n
Example 1:
\n\n\nInput: image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n\n\n
Example 2:
\n\n\nInput: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n\n\n
\n
Constraints:
\n\nn == image.length
n == image[i].length
1 <= n <= 20
images[i][j]
is either 0
or 1
.You are given a 0-indexed string s
that you must perform k
replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices
, sources
, and targets
, all of length k
.
To complete the ith
replacement operation:
sources[i]
occurs at index indices[i]
in the original string s
.targets[i]
.For example, if s = "abcd"
, indices[i] = 0
, sources[i] = "ab"
, and targets[i] = "eee"
, then the result of this replacement will be "eeecd"
.
All replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.
\n\ns = "abc"
, indices = [0, 1]
, and sources = ["ab","bc"]
will not be generated because the "ab"
and "bc"
replacements overlap.Return the resulting string after performing all replacement operations on s
.
A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\nInput: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]\nOutput: "eeebffff"\nExplanation:\n"a" occurs at index 0 in s, so we replace it with "eee".\n"cd" occurs at index 2 in s, so we replace it with "ffff".\n\n\n
Example 2:
\n\nInput: s = "abcd", indices = [0, 2], sources = ["ab","ec"], targets = ["eee","ffff"]\nOutput: "eeecd"\nExplanation:\n"ab" occurs at index 0 in s, so we replace it with "eee".\n"ec" does not occur at index 2 in s, so we do nothing.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
k == indices.length == sources.length == targets.length
1 <= k <= 100
0 <= indexes[i] < s.length
1 <= sources[i].length, targets[i].length <= 50
s
consists of only lowercase English letters.sources[i]
and targets[i]
consist of only lowercase English letters.There is an undirected connected tree with n
nodes labeled from 0
to n - 1
and n - 1
edges.
You are given the integer n
and the array edges
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
Return an array answer
of length n
where answer[i]
is the sum of the distances between the ith
node in the tree and all other nodes.
\n
Example 1:
\n\nInput: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput: [8,12,6,10,10,10]\nExplanation: The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.\n\n\n
Example 2:
\n\nInput: n = 1, edges = []\nOutput: [0]\n\n\n
Example 3:
\n\nInput: n = 2, edges = [[1,0]]\nOutput: [1,1]\n\n\n
\n
Constraints:
\n\n1 <= n <= 3 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
You are given two images, img1
and img2
, represented as binary, square matrices of size n x n
. A binary matrix has only 0
s and 1
s as values.
We translate one image however we choose by sliding all the 1
bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1
in both images.
Note also that a translation does not include any kind of rotation. Any 1
bits that are translated outside of the matrix borders are erased.
Return the largest possible overlap.
\n\n\n
Example 1:
\n\nInput: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\nOutput: 3\nExplanation: We translate img1 to right by 1 unit and down by 1 unit.\n\n\n\nThe number of positions that have a 1 in both images is 3 (shown in red).\n
\n
Example 2:
\n\n\nInput: img1 = [[1]], img2 = [[1]]\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: img1 = [[0]], img2 = [[0]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == img1.length == img1[i].length
n == img2.length == img2[i].length
1 <= n <= 30
img1[i][j]
is either 0
or 1
.img2[i][j]
is either 0
or 1
.An axis-aligned rectangle is represented as a list [x1, y1, x2, y2]
, where (x1, y1)
is the coordinate of its bottom-left corner, and (x2, y2)
is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
\n\nGiven two axis-aligned rectangles rec1
and rec2
, return true
if they overlap, otherwise return false
.
\n
Example 1:
\nInput: rec1 = [0,0,2,2], rec2 = [1,1,3,3]\nOutput: true\n
Example 2:
\nInput: rec1 = [0,0,1,1], rec2 = [1,0,2,1]\nOutput: false\n
Example 3:
\nInput: rec1 = [0,0,1,1], rec2 = [2,2,3,3]\nOutput: false\n\n
\n
Constraints:
\n\nrec1.length == 4
rec2.length == 4
-109 <= rec1[i], rec2[i] <= 109
rec1
and rec2
represent a valid rectangle with a non-zero area.Alice plays the following game, loosely based on the card game "21".
\n\nAlice starts with 0
points and draws numbers while she has less than k
points. During each draw, she gains an integer number of points randomly from the range [1, maxPts]
, where maxPts
is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets k
or more points.
Return the probability that Alice has n
or fewer points.
Answers within 10-5
of the actual answer are considered accepted.
\n
Example 1:
\n\n\nInput: n = 10, k = 1, maxPts = 10\nOutput: 1.00000\nExplanation: Alice gets a single card, then stops.\n\n\n
Example 2:
\n\n\nInput: n = 6, k = 1, maxPts = 10\nOutput: 0.60000\nExplanation: Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.\n\n\n
Example 3:
\n\n\nInput: n = 21, k = 17, maxPts = 10\nOutput: 0.73278\n\n\n
\n
Constraints:
\n\n0 <= k <= n <= 104
1 <= maxPts <= 104
There are n
dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
\n\nWhen a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
\n\nFor the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
\n\nYou are given a string dominoes
representing the initial state where:
dominoes[i] = 'L'
, if the ith
domino has been pushed to the left,dominoes[i] = 'R'
, if the ith
domino has been pushed to the right, anddominoes[i] = '.'
, if the ith
domino has not been pushed.Return a string representing the final state.
\n\n\n
Example 1:
\n\n\nInput: dominoes = "RR.L"\nOutput: "RR.L"\nExplanation: The first domino expends no additional force on the second domino.\n\n\n
Example 2:
\n\nInput: dominoes = ".L.R...LR..L.."\nOutput: "LL.RR.LLRRLL.."\n\n\n
\n
Constraints:
\n\nn == dominoes.length
1 <= n <= 105
dominoes[i]
is either 'L'
, 'R'
, or '.'
.Two strings, X
and Y
, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X
.
For example, "tars"
and "rats"
are similar (swapping at positions 0
and 2
), and "rats"
and "arts"
are similar, but "star"
is not similar to "tars"
, "rats"
, or "arts"
.
Together, these form two connected groups by similarity: {"tars", "rats", "arts"}
and {"star"}
. Notice that "tars"
and "arts"
are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list strs
of strings where every string in strs
is an anagram of every other string in strs
. How many groups are there?
\n
Example 1:
\n\n\nInput: strs = ["tars","rats","arts","star"]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: strs = ["omv","ovm"]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= strs.length <= 300
1 <= strs[i].length <= 300
strs[i]
consists of lowercase letters only.strs
have the same length and are anagrams of each other.A 3 x 3
magic square is a 3 x 3
grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.
Given a row x col
grid
of integers, how many 3 x 3
magic square subgrids are there?
Note: while a magic square can only contain numbers from 1 to 9, grid
may contain numbers up to 15.
\n
Example 1:
\n\nInput: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput: 1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\n\n\n\nwhile this one is not:\n
\nIn total, there is only one magic square inside the given grid.\n
Example 2:
\n\n\nInput: grid = [[8]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nrow == grid.length
col == grid[i].length
1 <= row, col <= 10
0 <= grid[i][j] <= 15
There are n
rooms labeled from 0
to n - 1
and all the rooms are locked except for room 0
. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
\n\nGiven an array rooms
where rooms[i]
is the set of keys that you can obtain if you visited room i
, return true
if you can visit all the rooms, or false
otherwise.
\n
Example 1:
\n\n\nInput: rooms = [[1],[2],[3],[]]\nOutput: true\nExplanation: \nWe visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.\n\n\n
Example 2:
\n\n\nInput: rooms = [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n\n\n
\n
Constraints:
\n\nn == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
rooms[i]
are unique.You are given a string of digits num
, such as "123456579"
. We can split it into a Fibonacci-like sequence [123, 456, 579]
.
Formally, a Fibonacci-like sequence is a list f
of non-negative integers such that:
0 <= f[i] < 231
, (that is, each integer fits in a 32-bit signed integer type),f.length >= 3
, andf[i] + f[i + 1] == f[i + 2]
for all 0 <= i < f.length - 2
.Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0
itself.
Return any Fibonacci-like sequence split from num
, or return []
if it cannot be done.
\n
Example 1:
\n\n\nInput: num = "1101111"\nOutput: [11,0,11,11]\nExplanation: The output [110, 1, 111] would also be accepted.\n\n\n
Example 2:
\n\n\nInput: num = "112358130"\nOutput: []\nExplanation: The task is impossible.\n\n\n
Example 3:
\n\n\nInput: num = "0123"\nOutput: []\nExplanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 200
num
contains only digits.You are given an array of unique strings words
where words[i]
is six letters long. One word of words
was chosen as a secret word.
You are also given the helper object Master
. You may call Master.guess(word)
where word
is a six-letter-long string, and it must be from words
. Master.guess(word)
returns:
-1
if word
is not from words
, orThere is a parameter allowedGuesses
for each test case where allowedGuesses
is the maximum number of times you can call Master.guess(word)
.
For each test case, you should call Master.guess
with the secret word without exceeding the maximum number of allowed guesses. You will get:
"Either you took too many guesses, or you did not find the secret word."
if you called Master.guess
more than allowedGuesses
times or if you did not call Master.guess
with the secret word, or"You guessed the secret word correctly."
if you called Master.guess
with the secret word with the number of calls to Master.guess
less than or equal to allowedGuesses
.The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).
\n\n\n
Example 1:
\n\n\nInput: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation:\nmaster.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist.\nmaster.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches.\nmaster.guess("ccbazz") returns 3, because "ccbazz" has 3 matches.\nmaster.guess("eiowzz") returns 2, because "eiowzz" has 2 matches.\nmaster.guess("abcczz") returns 4, because "abcczz" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case.\n\n\n
Example 2:
\n\n\nInput: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation: Since there are two words, you can guess both.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
words[i].length == 6
words[i]
consist of lowercase English letters.wordlist
are unique.secret
exists in words
.10 <= allowedGuesses <= 30
Given two strings s
and t
, return true
if they are equal when both are typed into empty text editors. '#'
means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
\n\n\n
Example 1:
\n\n\nInput: s = "ab#c", t = "ad#c"\nOutput: true\nExplanation: Both s and t become "ac".\n\n\n
Example 2:
\n\n\nInput: s = "ab##", t = "c#d#"\nOutput: true\nExplanation: Both s and t become "".\n\n\n
Example 3:
\n\n\nInput: s = "a#c", t = "b"\nOutput: false\nExplanation: s becomes "c" while t becomes "b".\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 200
s
and t
only contain lowercase letters and '#'
characters.\n
Follow up: Can you solve it in O(n)
time and O(1)
space?
You may recall that an array arr
is a mountain array if and only if:
arr.length >= 3
i
(0-indexed) with 0 < i < arr.length - 1
such that:\n\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array arr
, return the length of the longest subarray, which is a mountain. Return 0
if there is no mountain subarray.
\n
Example 1:
\n\n\nInput: arr = [2,1,4,7,3,2,5]\nOutput: 5\nExplanation: The largest mountain is [1,4,7,3,2] which has length 5.\n\n\n
Example 2:
\n\n\nInput: arr = [2,2,2]\nOutput: 0\nExplanation: There is no mountain.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
0 <= arr[i] <= 104
\n
Follow up:
\n\nO(1)
space?Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize
, and consists of groupSize
consecutive cards.
Given an integer array hand
where hand[i]
is the value written on the ith
card and an integer groupSize
, return true
if she can rearrange the cards, or false
otherwise.
\n
Example 1:
\n\n\nInput: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput: true\nExplanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]\n\n\n
Example 2:
\n\n\nInput: hand = [1,2,3,4,5], groupSize = 4\nOutput: false\nExplanation: Alice's hand can not be rearranged into groups of 4.\n\n\n\n
\n
Constraints:
\n\n1 <= hand.length <= 104
0 <= hand[i] <= 109
1 <= groupSize <= hand.length
\n
Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
\n", - "likes": 3397, - "dislikes": 265, - "stats": "{\"totalAccepted\": \"347.8K\", \"totalSubmission\": \"611.9K\", \"totalAcceptedRaw\": 347814, \"totalSubmissionRaw\": 611919, \"acRate\": \"56.8%\"}", + "likes": 3474, + "dislikes": 276, + "stats": "{\"totalAccepted\": \"374.2K\", \"totalSubmission\": \"655.6K\", \"totalAcceptedRaw\": 374178, \"totalSubmissionRaw\": 655554, \"acRate\": \"57.1%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -31918,9 +31933,9 @@ "questionFrontendId": "847", "title": "Shortest Path Visiting All Nodes", "content": "You have an undirected, connected graph of n
nodes labeled from 0
to n - 1
. You are given an array graph
where graph[i]
is a list of all the nodes connected with node i
by an edge.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
\n\n\n
Example 1:
\n\nInput: graph = [[1,2,3],[0],[0],[0]]\nOutput: 4\nExplanation: One possible path is [1,0,2,0,3]\n\n\n
Example 2:
\n\nInput: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\nOutput: 4\nExplanation: One possible path is [0,1,4,2,3]\n\n\n
\n
Constraints:
\n\nn == graph.length
1 <= n <= 12
0 <= graph[i].length < n
graph[i]
does not contain i
.graph[a]
contains b
, then graph[b]
contains a
.You are given a string s
of lowercase English letters and an integer array shifts
of the same length.
Call the shift()
of a letter, the next letter in the alphabet, (wrapping around so that 'z'
becomes 'a'
).
shift('a') = 'b'
, shift('t') = 'u'
, and shift('z') = 'a'
.Now for each shifts[i] = x
, we want to shift the first i + 1
letters of s
, x
times.
Return the final string after all such shifts to s are applied.
\n\n\n
Example 1:
\n\n\nInput: s = "abc", shifts = [3,5,9]\nOutput: "rpl"\nExplanation: We start with "abc".\nAfter shifting the first 1 letters of s by 3, we have "dbc".\nAfter shifting the first 2 letters of s by 5, we have "igc".\nAfter shifting the first 3 letters of s by 9, we have "rpl", the answer.\n\n\n
Example 2:
\n\n\nInput: s = "aaa", shifts = [1,2,3]\nOutput: "gfd"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.shifts.length == s.length
0 <= shifts[i] <= 109
You are given an array representing a row of seats
where seats[i] = 1
represents a person sitting in the ith
seat, and seats[i] = 0
represents that the ith
seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
\n\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
\n\nReturn that maximum distance to the closest person.
\n\n\n
Example 1:
\n\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\n\n\n
Example 2:
\n\n\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\n\n\n
Example 3:
\n\n\nInput: seats = [0,1]\nOutput: 1\n\n\n
\n
Constraints:
\n\n2 <= seats.length <= 2 * 104
seats[i]
is 0
or 1
.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
in the plane. Any area covered by two or more rectangles should only be counted once.
Return the total area. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.\n\n\n
Example 2:
\n\n\nInput: rectangles = [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 1018 modulo (109 + 7), which is 49.\n\n\n
\n
Constraints:
\n\n1 <= rectangles.length <= 200
rectanges[i].length == 4
0 <= xi1, yi1, xi2, yi2 <= 109
xi1 <= xi2
yi1 <= yi2
There is a group of n
people labeled from 0
to n - 1
where each person has a different amount of money and a different level of quietness.
You are given an array richer
where richer[i] = [ai, bi]
indicates that ai
has more money than bi
and an integer array quiet
where quiet[i]
is the quietness of the ith
person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x
is richer than y
and y
is richer than x
at the same time).
Return an integer array answer
where answer[x] = y
if y
is the least quiet person (that is, the person y
with the smallest value of quiet[y]
) among all people who definitely have equal to or more money than the person x
.
\n
Example 1:
\n\n\nInput: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput: [5,5,2,5,4,5,6,7]\nExplanation: \nanswer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.\n\n\n
Example 2:
\n\n\nInput: richer = [], quiet = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\nn == quiet.length
1 <= n <= 500
0 <= quiet[i] < n
quiet
are unique.0 <= richer.length <= n * (n - 1) / 2
0 <= ai, bi < n
ai != bi
richer
are unique.richer
are all logically consistent.You are given an integer mountain array arr
of length n
where the values increase to a peak element and then decrease.
Return the index of the peak element.
\n\nYour task is to solve it in O(log(n))
time complexity.
\n
Example 1:
\n\nInput: arr = [0,1,0]
\n\nOutput: 1
\nExample 2:
\n\nInput: arr = [0,2,1,0]
\n\nOutput: 1
\nExample 3:
\n\nInput: arr = [0,10,5,2]
\n\nOutput: 1
\n\n
Constraints:
\n\n3 <= arr.length <= 105
0 <= arr[i] <= 106
arr
is guaranteed to be a mountain array.There are n
cars at given miles away from the starting mile 0, traveling to reach the mile target
.
You are given two integer array position
and speed
, both of length n
, where position[i]
is the starting mile of the ith
car and speed[i]
is the speed of the ith
car in miles per hour.
A car cannot pass another car, but it can catch up and then travel next to it at the speed of the slower car.
\n\nA car fleet is a car or cars driving next to each other. The speed of the car fleet is the minimum speed of any car in the fleet.
\n\nIf a car catches up to a car fleet at the mile target
, it will still be considered as part of the car fleet.
Return the number of car fleets that will arrive at the destination.
\n\n\n
Example 1:
\n\nInput: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
\n\nOutput: 3
\n\nExplanation:
\n\ntarget
.target
.Example 2:
\n\nInput: target = 10, position = [3], speed = [3]
\n\nOutput: 1
\n\nExplanation:
\nThere is only one car, hence there is only one fleet.Example 3:
\n\nInput: target = 100, position = [0,2,4], speed = [4,2,1]
\n\nOutput: 1
\n\nExplanation:
\n\ntarget
.\n
Constraints:
\n\nn == position.length == speed.length
1 <= n <= 105
0 < target <= 106
0 <= position[i] < target
position
are unique.0 < speed[i] <= 106
Strings s1
and s2
are k
-similar (for some non-negative integer k
) if we can swap the positions of two letters in s1
exactly k
times so that the resulting string equals s2
.
Given two anagrams s1
and s2
, return the smallest k
for which s1
and s2
are k
-similar.
\n
Example 1:
\n\n\nInput: s1 = "ab", s2 = "ba"\nOutput: 1\nExplanation: The two string are 1-similar because we can use one swap to change s1 to s2: "ab" --> "ba".\n\n\n
Example 2:
\n\n\nInput: s1 = "abc", s2 = "bca"\nOutput: 2\nExplanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: "abc" --> "bac" --> "bca".\n\n\n
\n
Constraints:
\n\n1 <= s1.length <= 20
s2.length == s1.length
s1
and s2
contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
.s2
is an anagram of s1
.There is an exam room with n
seats in a single row labeled from 0
to n - 1
.
When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0
.
Design a class that simulates the mentioned exam room.
\n\nImplement the ExamRoom
class:
ExamRoom(int n)
Initializes the object of the exam room with the number of the seats n
.int seat()
Returns the label of the seat at which the next student will set.void leave(int p)
Indicates that the student sitting at seat p
will leave the room. It is guaranteed that there will be a student sitting at seat p
.\n
Example 1:
\n\n\nInput\n["ExamRoom", "seat", "seat", "seat", "seat", "leave", "seat"]\n[[10], [], [], [], [], [4], []]\nOutput\n[null, 0, 9, 4, 2, null, 5]\n\nExplanation\nExamRoom examRoom = new ExamRoom(10);\nexamRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\nexamRoom.seat(); // return 9, the student sits at the last seat number 9.\nexamRoom.seat(); // return 4, the student sits at the last seat number 4.\nexamRoom.seat(); // return 2, the student sits at the last seat number 2.\nexamRoom.leave(4);\nexamRoom.seat(); // return 5, the student sits at the last seat number 5.\n\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
p
.104
calls will be made to seat
and leave
.Given a balanced parentheses string s
, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
\n\n"()"
has score 1
.AB
has score A + B
, where A
and B
are balanced parentheses strings.(A)
has score 2 * A
, where A
is a balanced parentheses string.\n
Example 1:
\n\n\nInput: s = "()"\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: s = "(())"\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: s = "()()"\nOutput: 2\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 50
s
consists of only '('
and ')'
.s
is a balanced parentheses string.There are n
workers. You are given two integer arrays quality
and wage
where quality[i]
is the quality of the ith
worker and wage[i]
is the minimum wage expectation for the ith
worker.
We want to hire exactly k
workers to form a paid group. To hire a group of k
workers, we must pay them according to the following rules:
Given the integer k
, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: quality = [10,20,5], wage = [70,50,30], k = 2\nOutput: 105.00000\nExplanation: We pay 70 to 0th worker and 35 to 2nd worker.\n\n\n
Example 2:
\n\n\nInput: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\nOutput: 30.66667\nExplanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.\n\n\n
\n
Constraints:
\n\nn == quality.length == wage.length
1 <= k <= n <= 104
1 <= quality[i], wage[i] <= 104
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0
, 1
, and 2
.
The square room has walls of length p
and a laser ray from the southwest corner first meets the east wall at a distance q
from the 0th
receptor.
Given the two integers p
and q
, return the number of the receptor that the ray meets first.
The test cases are guaranteed so that the ray will meet a receptor eventually.
\n\n\n
Example 1:
\n\nInput: p = 2, q = 1\nOutput: 2\nExplanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n\n\n
Example 2:
\n\n\nInput: p = 3, q = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= q <= p <= 1000
Given two strings s
and goal
, return true
if you can swap two letters in s
so the result is equal to goal
, otherwise, return false
.
Swapping letters is defined as taking two indices i
and j
(0-indexed) such that i != j
and swapping the characters at s[i]
and s[j]
.
0
and 2
in "abcd"
results in "cbad"
.\n
Example 1:
\n\n\nInput: s = "ab", goal = "ba"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.\n\n\n
Example 2:
\n\n\nInput: s = "ab", goal = "ab"\nOutput: false\nExplanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in "ba" != goal.\n\n\n
Example 3:
\n\n\nInput: s = "aa", goal = "aa"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'a' to get "aa", which is equal to goal.\n\n\n
\n
Constraints:
\n\n1 <= s.length, goal.length <= 2 * 104
s
and goal
consist of lowercase letters.At 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.
\n\nGiven an integer array bills
where bills[i]
is the bill the ith
customer pays, return true
if you can provide every customer with the correct change, or false
otherwise.
\n
Example 1:
\n\n\nInput: bills = [5,5,5,10,20]\nOutput: true\nExplanation: \nFrom the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.\n\n\n
Example 2:
\n\n\nInput: bills = [5,5,10,10,20]\nOutput: false\nExplanation: \nFrom the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.\n\n\n
\n
Constraints:
\n\n1 <= bills.length <= 105
bills[i]
is either 5
, 10
, or 20
.You are given an m x n
binary matrix grid
.
A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0
's to 1
's, and all 1
's to 0
's).
Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
\n\nReturn the highest possible score after making any number of moves (including zero moves).
\n\n\n
Example 1:
\n\nInput: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\nOutput: 39\nExplanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\n\n\n
Example 2:
\n\n\nInput: grid = [[0]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 20
grid[i][j]
is either 0
or 1
.Given an integer array nums
and an integer k
, return the length of the shortest non-empty subarray of nums
with a sum of at least k
. If there is no such subarray, return -1
.
A subarray is a contiguous part of an array.
\n\n\n
Example 1:
\nInput: nums = [1], k = 1\nOutput: 1\n
Example 2:
\nInput: nums = [1,2], k = 4\nOutput: -1\n
Example 3:
\nInput: nums = [2,-1,2], k = 3\nOutput: 3\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= k <= 109
Given the root
of a binary tree, the value of a target node target
, and an integer k
, return an array of the values of all nodes that have a distance k
from the target node.
You can return the answer in any order.
\n\n\n
Example 1:
\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput: [7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\n\n\n
Example 2:
\n\n\nInput: root = [1], target = 1, k = 3\nOutput: []\n\n\n
\n
Constraints:
\n\n[1, 500]
.0 <= Node.val <= 500
Node.val
are unique.target
is the value of one of the nodes in the tree.0 <= k <= 1000
You are given an m x n
grid grid
where:
'.'
is an empty cell.'#'
is a wall.'@'
is the starting point.You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
\n\nIf you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
\n\nFor some 1 <= k <= 6
, there is exactly one lowercase and one uppercase letter of the first k
letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys. If it is impossible, return -1
.
\n
Example 1:
\n\nInput: grid = ["@.a..","###.#","b.A.B"]\nOutput: 8\nExplanation: Note that the goal is to obtain all the keys not to open all the locks.\n\n\n
Example 2:
\n\nInput: grid = ["@..aA","..B#.","....b"]\nOutput: 6\n\n\n
Example 3:
\n\nInput: grid = ["@Aa"]\nOutput: -1\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j]
is either an English letter, '.'
, '#'
, or '@'
. '@'
in the grid.[1, 6]
.Given the root
of a binary tree, the depth of each node is the shortest distance to the root.
Return the smallest subtree such that it contains all the deepest nodes in the original tree.
\n\nA node is called the deepest if it has the largest depth possible among any node in the entire tree.
\n\nThe subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.
\n\n\n
Example 1:
\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.\n\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree.\n\n\n
Example 3:
\n\n\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.\n\n\n
\n
Constraints:
\n\n[1, 500]
.0 <= Node.val <= 500
\n
Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
\n", - "likes": 2689, - "dislikes": 376, - "stats": "{\"totalAccepted\": \"150.7K\", \"totalSubmission\": \"210.9K\", \"totalAcceptedRaw\": 150708, \"totalSubmissionRaw\": 210923, \"acRate\": \"71.5%\"}", + "likes": 2791, + "dislikes": 381, + "stats": "{\"totalAccepted\": \"164.5K\", \"totalSubmission\": \"227K\", \"totalAcceptedRaw\": 164519, \"totalSubmissionRaw\": 227039, \"acRate\": \"72.5%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -32636,9 +32651,9 @@ "questionFrontendId": "866", "title": "Prime Palindrome", "content": "Given an integer n, return the smallest prime palindrome greater than or equal to n
.
An integer is prime if it has exactly two divisors: 1
and itself. Note that 1
is not a prime number.
2
, 3
, 5
, 7
, 11
, and 13
are all primes.An integer is a palindrome if it reads the same from left to right as it does from right to left.
\n\n101
and 12321
are palindromes.The test cases are generated so that the answer always exists and is in the range [2, 2 * 108]
.
\n
Example 1:
\nInput: n = 6\nOutput: 7\n
Example 2:
\nInput: n = 8\nOutput: 11\n
Example 3:
\nInput: n = 13\nOutput: 101\n\n
\n
Constraints:
\n\n1 <= n <= 108
Given a 2D integer array matrix
, return the transpose of matrix
.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
\n\n\n
Example 1:
\n\n\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[1,4,7],[2,5,8],[3,6,9]]\n\n\n
Example 2:
\n\n\nInput: matrix = [[1,2,3],[4,5,6]]\nOutput: [[1,4],[2,5],[3,6]]\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Given a positive integer n
, find and return the longest distance between any two adjacent 1
's in the binary representation of n
. If there are no two adjacent 1
's, return 0
.
Two 1
's are adjacent if there are only 0
's separating them (possibly no 0
's). The distance between two 1
's is the absolute difference between their bit positions. For example, the two 1
's in "1001"
have a distance of 3.
\n
Example 1:
\n\n\nInput: n = 22\nOutput: 2\nExplanation: 22 in binary is "10110".\nThe first adjacent pair of 1's is "10110" with a distance of 2.\nThe second adjacent pair of 1's is "10110" with a distance of 1.\nThe answer is the largest of these two distances, which is 2.\nNote that "10110" is not a valid pair since there is a 1 separating the two 1's underlined.\n\n\n
Example 2:
\n\n\nInput: n = 8\nOutput: 0\nExplanation: 8 in binary is "1000".\nThere are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.\n\n\n
Example 3:
\n\n\nInput: n = 5\nOutput: 2\nExplanation: 5 in binary is "101".\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
You are given an integer n
. We reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true
if and only if we can do this so that the resulting number is a power of two.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: true\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
You are given two integer arrays nums1
and nums2
both of the same length. The advantage of nums1
with respect to nums2
is the number of indices i
for which nums1[i] > nums2[i]
.
Return any permutation of nums1
that maximizes its advantage with respect to nums2
.
\n
Example 1:
\nInput: nums1 = [2,7,11,15], nums2 = [1,10,4,11]\nOutput: [2,11,7,15]\n
Example 2:
\nInput: nums1 = [12,24,8,32], nums2 = [13,25,32,11]\nOutput: [24,32,8,12]\n\n
\n
Constraints:
\n\n1 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 109
A car travels from a starting position to a destination which is target
miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array stations
where stations[i] = [positioni, fueli]
indicates that the ith
gas station is positioni
miles east of the starting position and has fueli
liters of gas.
The car starts with an infinite tank of gas, which initially has startFuel
liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1
.
Note that if the car reaches a gas station with 0
fuel left, the car can still refuel there. If the car reaches the destination with 0
fuel left, it is still considered to have arrived.
\n
Example 1:
\n\n\nInput: target = 1, startFuel = 1, stations = []\nOutput: 0\nExplanation: We can reach the target without refueling.\n\n\n
Example 2:
\n\n\nInput: target = 100, startFuel = 1, stations = [[10,100]]\nOutput: -1\nExplanation: We can not reach the target (or even the first gas station).\n\n\n
Example 3:
\n\n\nInput: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput: 2\nExplanation: We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.\n\n\n
\n
Constraints:
\n\n1 <= target, startFuel <= 109
0 <= stations.length <= 500
1 <= positioni < positioni+1 < target
1 <= fueli < 109
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
\n\nFor example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
\n\nReturn true
if and only if the two given trees with head nodes root1
and root2
are leaf-similar.
\n
Example 1:
\n\nInput: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput: true\n\n\n
Example 2:
\n\nInput: root1 = [1,2,3], root2 = [1,3,2]\nOutput: false\n\n\n
\n
Constraints:
\n\n[1, 200]
.[0, 200]
.A sequence x1, x2, ..., xn
is Fibonacci-like if:
n >= 3
xi + xi+1 == xi+2
for all i + 2 <= n
Given a strictly increasing array arr
of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr
. If one does not exist, return 0
.
A subsequence is derived from another sequence arr
by deleting any number of elements (including none) from arr
, without changing the order of the remaining elements. For example, [3, 5, 8]
is a subsequence of [3, 4, 5, 6, 7, 8]
.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5,6,7,8]\nOutput: 5\nExplanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].\n\n
Example 2:
\n\n\nInput: arr = [1,3,7,11,12,14,18]\nOutput: 3\nExplanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].\n\n
\n
Constraints:
\n\n3 <= arr.length <= 1000
1 <= arr[i] < arr[i + 1] <= 109
iarr[i]
, which can be done in linear time per element."
+ ],
"topicTags": [
{
"name": "Array"
@@ -32919,7 +32937,7 @@
"isPaidOnly": false,
"solution": {
"canSeeDetail": true,
- "content": "[TOC]\n\n## Solution\n---\n### Approach 1: Brute Force with Set\n\n**Intuition**\n\nEvery Fibonacci-like subsequence has each two adjacent terms determine the next expected term. For example, with `2, 5`, we expect that the sequence must continue `7, 12, 19, 31`, etc.\n\nWe can use a `Set` structure to determine quickly whether the next term is in the array `A` or not. Because of the exponential growth of these terms, there are at most 43 terms in any Fibonacci-like subsequence that has maximum value $$\\leq 10^9$$.\n\n**Algorithm**\n\nFor each starting pair `A[i], A[j]`, we maintain the next expected value `y = A[i] + A[j]` and the previously seen largest value `x = A[j]`. If `y` is in the array, then we can then update these values `(x, y) -> (y, x+y)`.\n\nAlso, because subsequences are only fibonacci-like if they have length 3 or more, we must perform the check `ans >= 3 ? ans : 0` at the end.\n\n\n\n**Complexity Analysis**\n\n* Time Complexity: $$O(N^2 \\log M)$$, where $$N$$ is the length of `A`, and $$M$$ is the maximum value of `A`.\n\n* Space Complexity: $$O(N)$$, the space used by the set `S`.\nA robot on an infinite XY-plane starts at point (0, 0)
facing north. The robot receives an array of integers commands
, which represents a sequence of moves that it needs to execute. There are only three possible types of instructions the robot can receive:
-2
: Turn left 90
degrees.-1
: Turn right 90
degrees.1 <= k <= 9
: Move forward k
units, one unit at a time.Some of the grid squares are obstacles
. The ith
obstacle is at grid point obstacles[i] = (xi, yi)
. If the robot runs into an obstacle, it will stay in its current location (on the block adjacent to the obstacle) and move onto the next command.
Return the maximum squared Euclidean distance that the robot reaches at any point in its path (i.e. if the distance is 5
, return 25
).
Note:
\n\n(0, 0)
. If this happens, the robot will ignore the obstacle until it has moved off the origin. However, it will be unable to return to (0, 0)
due to the obstacle.\n
Example 1:
\n\nInput: commands = [4,-1,3], obstacles = []
\n\nOutput: 25
\n\nExplanation:
\n\nThe robot starts at (0, 0)
:
(0, 4)
.(3, 4)
.The furthest point the robot ever gets from the origin is (3, 4)
, which squared is 32 + 42 = 25
units away.
Example 2:
\n\nInput: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
\n\nOutput: 65
\n\nExplanation:
\n\nThe robot starts at (0, 0)
:
(0, 4)
.(2, 4)
, robot is at (1, 4)
.(1, 8)
.The furthest point the robot ever gets from the origin is (1, 8)
, which squared is 12 + 82 = 65
units away.
Example 3:
\n\nInput: commands = [6,-1,-1,6], obstacles = [[0,0]]
\n\nOutput: 36
\n\nExplanation:
\n\nThe robot starts at (0, 0)
:
(0, 6)
.(0,0)
, robot is at (0, 1)
.The furthest point the robot ever gets from the origin is (0, 6)
, which squared is 62 = 36
units away.
\n
Constraints:
\n\n1 <= commands.length <= 104
commands[i]
is either -2
, -1
, or an integer in the range [1, 9]
.0 <= obstacles.length <= 104
-3 * 104 <= xi, yi <= 3 * 104
231
.Koko loves to eat bananas. There are n
piles of bananas, the ith
pile has piles[i]
bananas. The guards have gone and will come back in h
hours.
Koko can decide her bananas-per-hour eating speed of k
. Each hour, she chooses some pile of bananas and eats k
bananas from that pile. If the pile has less than k
bananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
\n\nReturn the minimum integer k
such that she can eat all the bananas within h
hours.
\n
Example 1:
\n\n\nInput: piles = [3,6,7,11], h = 8\nOutput: 4\n\n\n
Example 2:
\n\n\nInput: piles = [30,11,23,4,20], h = 5\nOutput: 30\n\n\n
Example 3:
\n\n\nInput: piles = [30,11,23,4,20], h = 6\nOutput: 23\n\n\n
\n
Constraints:
\n\n1 <= piles.length <= 104
piles.length <= h <= 109
1 <= piles[i] <= 109
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
\n\n\n
Example 1:
\n\nInput: head = [1,2,3,4,5]\nOutput: [3,4,5]\nExplanation: The middle node of the list is node 3.\n\n\n
Example 2:
\n\nInput: head = [1,2,3,4,5,6]\nOutput: [4,5,6]\nExplanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n\n\n
\n
Constraints:
\n\n[1, 100]
.1 <= Node.val <= 100
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]
.
The objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.
\n\nAlice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
\n\nAssuming Alice and Bob play optimally, return true
if Alice wins the game, or false
if Bob wins.
\n
Example 1:
\n\n\nInput: piles = [5,3,4,5]\nOutput: true\nExplanation: \nAlice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.\n\n\n
Example 2:
\n\n\nInput: piles = [3,7,2,3]\nOutput: true\n\n\n
\n
Constraints:
\n\n2 <= piles.length <= 500
piles.length
is even.1 <= piles[i] <= 500
sum(piles[i])
is odd.A positive integer is magical if it is divisible by either a
or b
.
Given the three integers n
, a
, and b
, return the nth
magical number. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 1, a = 2, b = 3\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: n = 4, a = 2, b = 3\nOutput: 6\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
2 <= a, b <= 4 * 104
There is a group of n
members, and a list of various crimes they could commit. The ith
crime generates a profit[i]
and requires group[i]
members to participate in it. If a member participates in one crime, that member can't participate in another crime.
Let's call a profitable scheme any subset of these crimes that generates at least minProfit
profit, and the total number of members participating in that subset of crimes is at most n
.
Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\nOutput: 2\nExplanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes.\n\n
Example 2:
\n\n\nInput: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\nOutput: 7\nExplanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n\n
\n
Constraints:
\n\n1 <= n <= 100
0 <= minProfit <= 100
1 <= group.length <= 100
1 <= group[i] <= 100
profit.length == group.length
0 <= profit[i] <= 100
You are given an encoded string s
. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
d
, the entire current tape is repeatedly written d - 1
more times in total.Given an integer k
, return the kth
letter (1-indexed) in the decoded string.
\n
Example 1:
\n\n\nInput: s = "leet2code3", k = 10\nOutput: "o"\nExplanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode".\nThe 10th letter in the string is "o".\n\n\n
Example 2:
\n\n\nInput: s = "ha22", k = 5\nOutput: "h"\nExplanation: The decoded string is "hahahaha".\nThe 5th letter is "h".\n\n\n
Example 3:
\n\n\nInput: s = "a2345678999999999999999", k = 1\nOutput: "a"\nExplanation: The decoded string is "a" repeated 8301530446056247680 times.\nThe 1st letter is "a".\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 100
s
consists of lowercase English letters and digits 2
through 9
.s
starts with a letter.1 <= k <= 109
k
is less than or equal to the length of the decoded string.263
letters.You are given an array people
where people[i]
is the weight of the ith
person, and an infinite number of boats where each boat can carry a maximum weight of limit
. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit
.
Return the minimum number of boats to carry every given person.
\n\n\n
Example 1:
\n\n\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\n\n\n
Example 2:
\n\n\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\n\n\n
Example 3:
\n\n\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\n\n\n
\n
Constraints:
\n\n1 <= people.length <= 5 * 104
1 <= people[i] <= limit <= 3 * 104
You are given an undirected graph (the "original graph") with n
nodes labeled from 0
to n - 1
. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.
The graph is given as a 2D array of edges
where edges[i] = [ui, vi, cnti]
indicates that there is an edge between nodes ui
and vi
in the original graph, and cnti
is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0
means you will not subdivide the edge.
To subdivide the edge [ui, vi]
, replace it with (cnti + 1)
new edges and cnti
new nodes. The new nodes are x1
, x2
, ..., xcnti
, and the new edges are [ui, x1]
, [x1, x2]
, [x2, x3]
, ..., [xcnti-1, xcnti]
, [xcnti, vi]
.
In this new graph, you want to know how many nodes are reachable from the node 0
, where a node is reachable if the distance is maxMoves
or less.
Given the original graph and maxMoves
, return the number of nodes that are reachable from node 0
in the new graph.
\n
Example 1:
\n\nInput: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\nOutput: 13\nExplanation: The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.\n\n\n
Example 2:
\n\n\nInput: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\nOutput: 23\n\n\n
Example 3:
\n\n\nInput: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\nOutput: 1\nExplanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n\n\n
\n
Constraints:
\n\n0 <= edges.length <= min(n * (n - 1) / 2, 104)
edges[i].length == 3
0 <= ui < vi < n
0 <= cnti <= 104
0 <= maxMoves <= 109
1 <= n <= 3000
You are given an n x n
grid
where we place some 1 x 1 x 1
cubes that are axis-aligned with the x
, y
, and z
axes.
Each value v = grid[i][j]
represents a tower of v
cubes placed on top of the cell (i, j)
.
We view the projection of these cubes onto the xy
, yz
, and zx
planes.
A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
\n\nReturn the total area of all three projections.
\n\n\n
Example 1:
\n\nInput: grid = [[1,2],[3,4]]\nOutput: 17\nExplanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.\n\n\n
Example 2:
\n\n\nInput: grid = [[2]]\nOutput: 5\n\n\n
Example 3:
\n\n\nInput: grid = [[1,0],[0,2]]\nOutput: 8\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
A sentence is a string of single-space separated words where each word consists only of lowercase letters.
\n\nA word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
\n\nGiven two sentences s1
and s2
, return a list of all the uncommon words. You may return the answer in any order.
\n
Example 1:
\n\nInput: s1 = "this apple is sweet", s2 = "this apple is sour"
\n\nOutput: ["sweet","sour"]
\n\nExplanation:
\n\nThe word "sweet"
appears only in s1
, while the word "sour"
appears only in s2
.
Example 2:
\n\nInput: s1 = "apple apple", s2 = "banana"
\n\nOutput: ["banana"]
\n\n
Constraints:
\n\n1 <= s1.length, s2.length <= 200
s1
and s2
consist of lowercase English letters and spaces.s1
and s2
do not have leading or trailing spaces.s1
and s2
are separated by a single space.You start at the cell (rStart, cStart)
of an rows x cols
grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols
spaces of the grid.
Return an array of coordinates representing the positions of the grid in the order you visited them.
\n\n\n
Example 1:
\n\nInput: rows = 1, cols = 4, rStart = 0, cStart = 0\nOutput: [[0,0],[0,1],[0,2],[0,3]]\n\n\n
Example 2:
\n\nInput: rows = 5, cols = 6, rStart = 1, cStart = 4\nOutput: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]\n\n\n
\n
Constraints:
\n\n1 <= rows, cols <= 100
0 <= rStart < rows
0 <= cStart < cols
We want to split a group of n
people (labeled from 1
to n
) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.
Given the integer n
and the array dislikes
where dislikes[i] = [ai, bi]
indicates that the person labeled ai
does not like the person labeled bi
, return true
if it is possible to split everyone into two groups in this way.
\n
Example 1:
\n\n\nInput: n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput: true\nExplanation: The first group has [1,4], and the second group has [2,3].\n\n\n
Example 2:
\n\n\nInput: n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput: false\nExplanation: We need at least 3 groups to divide them. We cannot put them in two groups.\n\n\n
\n
Constraints:
\n\n1 <= n <= 2000
0 <= dislikes.length <= 104
dislikes[i].length == 2
1 <= ai < bi <= n
dislikes
are unique.You are given k
identical eggs and you have access to a building with n
floors labeled from 1
to n
.
You know that there exists a floor f
where 0 <= f <= n
such that any egg dropped at a floor higher than f
will break, and any egg dropped at or below floor f
will not break.
Each move, you may take an unbroken egg and drop it from any floor x
(where 1 <= x <= n
). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f
is.
\n
Example 1:
\n\n\nInput: k = 1, n = 2\nOutput: 2\nExplanation: \nDrop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.\n\n\n
Example 2:
\n\n\nInput: k = 2, n = 6\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: k = 3, n = 14\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= k <= 100
1 <= n <= 104
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes
and bobSizes
where aliceSizes[i]
is the number of candies of the ith
box of candy that Alice has and bobSizes[j]
is the number of candies of the jth
box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
\n\nReturn an integer array answer
where answer[0]
is the number of candies in the box that Alice must exchange, and answer[1]
is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
\n
Example 1:
\n\n\nInput: aliceSizes = [1,1], bobSizes = [2,2]\nOutput: [1,2]\n\n\n
Example 2:
\n\n\nInput: aliceSizes = [1,2], bobSizes = [2,3]\nOutput: [1,2]\n\n\n
Example 3:
\n\n\nInput: aliceSizes = [2], bobSizes = [1,3]\nOutput: [2,3]\n\n\n
\n
Constraints:
\n\n1 <= aliceSizes.length, bobSizes.length <= 104
1 <= aliceSizes[i], bobSizes[j] <= 105
Given two integer arrays, preorder
and postorder
where preorder
is the preorder traversal of a binary tree of distinct values and postorder
is the postorder traversal of the same tree, reconstruct and return the binary tree.
If there exist multiple answers, you can return any of them.
\n\n\n
Example 1:
\n\nInput: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\n\n\n
Example 2:
\n\n\nInput: preorder = [1], postorder = [1]\nOutput: [1]\n\n\n
\n
Constraints:
\n\n1 <= preorder.length <= 30
1 <= preorder[i] <= preorder.length
preorder
are unique.postorder.length == preorder.length
1 <= postorder[i] <= postorder.length
postorder
are unique.preorder
and postorder
are the preorder traversal and postorder traversal of the same binary tree.Given a list of strings words
and a string pattern
, return a list of words[i]
that match pattern
. You may return the answer in any order.
A word matches the pattern if there exists a permutation of letters p
so that after replacing every letter x
in the pattern with p(x)
, we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
\n\n\n
Example 1:
\n\n\nInput: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"\nOutput: ["mee","aqq"]\nExplanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.\n\n\n
Example 2:
\n\n\nInput: words = ["a","b","c"], pattern = "a"\nOutput: ["a","b","c"]\n\n\n
\n
Constraints:
\n\n1 <= pattern.length <= 20
1 <= words.length <= 50
words[i].length == pattern.length
pattern
and words[i]
are lowercase English letters.The width of a sequence is the difference between the maximum and minimum elements in the sequence.
\n\nGiven an array of integers nums
, return the sum of the widths of all the non-empty subsequences of nums
. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7]
is a subsequence of the array [0,3,1,6,2,2,7]
.
\n
Example 1:
\n\n\nInput: nums = [2,1,3]\nOutput: 6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\n\n\n
Example 2:
\n\n\nInput: nums = [2]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
You are given an n x n
grid
where you have placed some 1 x 1 x 1
cubes. Each value v = grid[i][j]
represents a tower of v
cubes placed on top of cell (i, j)
.
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.
\n\nReturn the total surface area of the resulting shapes.
\n\nNote: The bottom face of each shape counts toward its surface area.
\n\n\n
Example 1:
\n\nInput: grid = [[1,2],[3,4]]\nOutput: 34\n\n\n
Example 2:
\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 32\n\n\n
Example 3:
\n\nInput: grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput: 46\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
You are given an array of strings of the same length words
.
In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i]
.
Two strings words[i]
and words[j]
are special-equivalent if after any number of moves, words[i] == words[j]
.
words[i] = "zzxy"
and words[j] = "xyzz"
are special-equivalent because we may make the moves "zzxy" -> "xzzy" -> "xyzz"
.A group of special-equivalent strings from words
is a non-empty subset of words such that:
words[i]
not in the group such that words[i]
is special-equivalent to every string in the group).Return the number of groups of special-equivalent strings from words
.
\n
Example 1:
\n\n\nInput: words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"]\nOutput: 3\nExplanation: \nOne group is ["abcd", "cdab", "cbad"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are ["xyzz", "zzxy"] and ["zzyx"].\nNote that in particular, "zzxy" is not special equivalent to "zzyx".\n\n\n
Example 2:
\n\n\nInput: words = ["abc","acb","bac","bca","cab","cba"]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 20
words[i]
consist of lowercase English letters.Given an integer n
, return a list of all possible full binary trees with n
nodes. Each node of each tree in the answer must have Node.val == 0
.
Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.
\n\nA full binary tree is a binary tree where each node has exactly 0
or 2
children.
\n
Example 1:
\n\nInput: n = 7\nOutput: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: [[0,0,0]]\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
\n\nImplement the FreqStack
class:
FreqStack()
constructs an empty frequency stack.void push(int val)
pushes an integer val
onto the top of the stack.int pop()
removes and returns the most frequent element in the stack.\n\t\n
Example 1:
\n\n\nInput\n["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]\n[[], [5], [7], [5], [7], [4], [5], [], [], [], []]\nOutput\n[null, null, null, null, null, null, null, 5, 7, 5, 4]\n\nExplanation\nFreqStack freqStack = new FreqStack();\nfreqStack.push(5); // The stack is [5]\nfreqStack.push(7); // The stack is [5,7]\nfreqStack.push(5); // The stack is [5,7,5]\nfreqStack.push(7); // The stack is [5,7,5,7]\nfreqStack.push(4); // The stack is [5,7,5,7,4]\nfreqStack.push(5); // The stack is [5,7,5,7,4,5]\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\nfreqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\nfreqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\nfreqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n\n\n
\n
Constraints:
\n\n0 <= val <= 109
2 * 104
calls will be made to push
and pop
.pop
.An array is monotonic if it is either monotone increasing or monotone decreasing.
\n\nAn array nums
is monotone increasing if for all i <= j
, nums[i] <= nums[j]
. An array nums
is monotone decreasing if for all i <= j
, nums[i] >= nums[j]
.
Given an integer array nums
, return true
if the given array is monotonic, or false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [1,2,2,3]\nOutput: true\n\n\n
Example 2:
\n\n\nInput: nums = [6,5,4,4]\nOutput: true\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,2]\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-105 <= nums[i] <= 105
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.
\n
Example 1:
\n\nInput: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n\n\n
Example 2:
\n\nInput: root = [5,1,7]\nOutput: [1,null,5,null,7]\n\n\n
\n
Constraints:
\n\n[1, 100]
.0 <= Node.val <= 1000
Given an integer array arr
, return the number of distinct bitwise ORs of all the non-empty subarrays of arr
.
The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: arr = [0]\nOutput: 1\nExplanation: There is only one possible result: 0.\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,2]\nOutput: 3\nExplanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,4]\nOutput: 6\nExplanation: The possible results are 1, 2, 3, 4, 6, and 7.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 5 * 104
0 <= arr[i] <= 109
You are given a string s
and an integer k
. You can choose one of the first k
letters of s
and append it at the end of the string.
Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.
\n\n\n
Example 1:
\n\n\nInput: s = "cba", k = 1\nOutput: "acb"\nExplanation: \nIn the first move, we move the 1st character 'c' to the end, obtaining the string "bac".\nIn the second move, we move the 1st character 'b' to the end, obtaining the final result "acb".\n\n\n
Example 2:
\n\n\nInput: s = "baaca", k = 3\nOutput: "aaabc"\nExplanation: \nIn the first move, we move the 1st character 'b' to the end, obtaining the string "aacab".\nIn the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc".\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 1000
s
consist of lowercase English letters.We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding
(0-indexed), for all even i
, encoding[i]
tells us the number of times that the non-negative integer value encoding[i + 1]
is repeated in the sequence.
arr = [8,8,8,5,5]
can be encoded to be encoding = [3,8,2,5]
. encoding = [3,8,0,9,2,5]
and encoding = [2,8,1,8,2,5]
are also valid RLE of arr
.Given a run-length encoded array, design an iterator that iterates through it.
\n\nImplement the RLEIterator
class:
RLEIterator(int[] encoded)
Initializes the object with the encoded array encoded
.int next(int n)
Exhausts the next n
elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1
instead.\n
Example 1:
\n\n\nInput\n["RLEIterator", "next", "next", "next", "next"]\n[[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]\nOutput\n[null, 8, 8, 5, -1]\n\nExplanation\nRLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\nrLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\nrLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\nrLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\nbut the second term did not exist. Since the last term exhausted does not exist, we return -1.\n\n\n
\n
Constraints:
\n\n2 <= encoding.length <= 1000
encoding.length
is even.0 <= encoding[i] <= 109
1 <= n <= 109
1000
calls will be made to next
.Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
\n\nThe span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
\n\n[7,2,1,2]
and the price of the stock today is 2
, then the span of today is 4
because starting from today, the price of the stock was less than or equal 2
for 4
consecutive days.[7,34,1,2]
and the price of the stock today is 8
, then the span of today is 3
because starting from today, the price of the stock was less than or equal 8
for 3
consecutive days.Implement the StockSpanner
class:
StockSpanner()
Initializes the object of the class.int next(int price)
Returns the span of the stock's price given that today's price is price
.\n
Example 1:
\n\n\nInput\n["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]\n[[], [100], [80], [60], [70], [60], [75], [85]]\nOutput\n[null, 1, 1, 1, 2, 1, 4, 6]\n\nExplanation\nStockSpanner stockSpanner = new StockSpanner();\nstockSpanner.next(100); // return 1\nstockSpanner.next(80); // return 1\nstockSpanner.next(60); // return 1\nstockSpanner.next(70); // return 2\nstockSpanner.next(60); // return 1\nstockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\nstockSpanner.next(85); // return 6\n\n\n
\n
Constraints:
\n\n1 <= price <= 105
104
calls will be made to next
.Given an array of digits
which is sorted in non-decreasing order. You can write numbers using each digits[i]
as many times as we want. For example, if digits = ['1','3','5']
, we may write numbers such as '13'
, '551'
, and '1351315'
.
Return the number of positive integers that can be generated that are less than or equal to a given integer n
.
\n
Example 1:
\n\n\nInput: digits = ["1","3","5","7"], n = 100\nOutput: 20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n\n\n
Example 2:
\n\n\nInput: digits = ["1","4","9"], n = 1000000000\nOutput: 29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.\n\n\n
Example 3:
\n\n\nInput: digits = ["7"], n = 8\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= digits.length <= 9
digits[i].length == 1
digits[i]
is a digit from '1'
to '9'
.digits
are unique.digits
is sorted in non-decreasing order.1 <= n <= 109
You are given a string s
of length n
where s[i]
is either:
'D'
means decreasing, or'I'
means increasing.A permutation perm
of n + 1
integers of all the integers in the range [0, n]
is called a valid permutation if for all valid i
:
s[i] == 'D'
, then perm[i] > perm[i + 1]
, ands[i] == 'I'
, then perm[i] < perm[i + 1]
.Return the number of valid permutations perm
. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "DID"\nOutput: 5\nExplanation: The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)\n\n\n
Example 2:
\n\n\nInput: s = "D"\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == s.length
1 <= n <= 200
s[i]
is either 'I'
or 'D'
.You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits
where fruits[i]
is the type of fruit the ith
tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
\n\nGiven the integer array fruits
, return the maximum number of fruits you can pick.
\n
Example 1:
\n\n\nInput: fruits = [1,2,1]\nOutput: 3\nExplanation: We can pick from all 3 trees.\n\n\n
Example 2:
\n\n\nInput: fruits = [0,1,2,2]\nOutput: 3\nExplanation: We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].\n\n\n
Example 3:
\n\n\nInput: fruits = [1,2,3,2,2]\nOutput: 4\nExplanation: We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].\n\n\n
\n
Constraints:
\n\n1 <= fruits.length <= 105
0 <= fruits[i] < fruits.length
Given an integer array nums
, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,2,4]\nOutput: [2,4,3,1]\nExplanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n\n\n
Example 2:
\n\n\nInput: nums = [0]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5000
0 <= nums[i] <= 5000
Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.
\n\nGiven two positive integers left
and right
represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]
.
\n
Example 1:
\n\n\nInput: left = "4", right = "1000"\nOutput: 4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n\n\n
Example 2:
\n\n\nInput: left = "1", right = "2"\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= left.length, right.length <= 18
left
and right
consist of only digits.left
and right
cannot have leading zeros.left
and right
represent integers in the range [1, 1018 - 1]
.left
is less than or equal to right
.Given an array of integers arr, find the sum of min(b)
, where b
ranges over every (contiguous) subarray of arr
. Since the answer may be large, return the answer modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.\n\n\n
Example 2:
\n\n\nInput: arr = [11,81,94,43,3]\nOutput: 444\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 3 * 104
1 <= arr[i] <= 3 * 104
You are given an integer array nums
and an integer k
.
In one operation, you can choose any index i
where 0 <= i < nums.length
and change nums[i]
to nums[i] + x
where x
is an integer from the range [-k, k]
. You can apply this operation at most once for each index i
.
The score of nums
is the difference between the maximum and minimum elements in nums
.
Return the minimum score of nums
after applying the mentioned operation at most once for each index in it.
\n
Example 1:
\n\n\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n\n\n
Example 2:
\n\n\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,6], k = 3\nOutput: 0\nExplanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
0 <= nums[i] <= 104
0 <= k <= 104
You are given an n x n
integer matrix board
where the cells are labeled from 1
to n2
in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]
) and alternating direction each row.
You start on square 1
of the board. In each move, starting from square curr
, do the following:
next
with a label in the range [curr + 1, min(curr + 6, n2)]
.\n\n\tnext
has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next
.n2
.A board square on row r
and column c
has a snake or ladder if board[r][c] != -1
. The destination of that snake or ladder is board[r][c]
. Squares 1
and n2
are not the starting points of any snake or ladder.
Note that you only take a snake or ladder at most once per dice roll. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.
\n\n[[-1,4],[-1,3]]
, and on the first move, your destination square is 2
. You follow the ladder to square 3
, but do not follow the subsequent ladder to 4
.Return the least number of dice rolls required to reach the square n2
. If it is not possible to reach the square, return -1
.
\n
Example 1:
\n\nInput: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput: 4\nExplanation: \nIn the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.\n\n\n
Example 2:
\n\n\nInput: board = [[-1,-1],[-1,3]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == board.length == board[i].length
2 <= n <= 20
board[i][j]
is either -1
or in the range [1, n2]
.1
and n2
are not the starting points of any snake or ladder.You are given an integer array nums
and an integer k
.
For each index i
where 0 <= i < nums.length
, change nums[i]
to be either nums[i] + k
or nums[i] - k
.
The score of nums
is the difference between the maximum and minimum elements in nums
.
Return the minimum score of nums
after changing the values at each index.
\n
Example 1:
\n\n\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n\n\n
Example 2:
\n\n\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,6], k = 3\nOutput: 3\nExplanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
0 <= nums[i] <= 104
0 <= k <= 104
You are given two integer arrays persons
and times
. In an election, the ith
vote was cast for persons[i]
at time times[i]
.
For each query at a time t
, find the person that was leading the election at time t
. Votes cast at time t
will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.
Implement the TopVotedCandidate
class:
TopVotedCandidate(int[] persons, int[] times)
Initializes the object with the persons
and times
arrays.int q(int t)
Returns the number of the person that was leading the election at time t
according to the mentioned rules.\n
Example 1:
\n\n\nInput\n["TopVotedCandidate", "q", "q", "q", "q", "q", "q"]\n[[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]\nOutput\n[null, 0, 1, 1, 0, 0, 1]\n\nExplanation\nTopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\ntopVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\ntopVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\ntopVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\ntopVotedCandidate.q(15); // return 0\ntopVotedCandidate.q(24); // return 0\ntopVotedCandidate.q(8); // return 1\n\n\n\n
\n
Constraints:
\n\n1 <= persons.length <= 5000
times.length == persons.length
0 <= persons[i] < persons.length
0 <= times[i] <= 109
times
is sorted in a strictly increasing order.times[0] <= t <= 109
104
calls will be made to q
.Given an array of integers nums
, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n))
time complexity and with the smallest space complexity possible.
\n
Example 1:
\n\n\nInput: nums = [5,2,3,1]\nOutput: [1,2,3,5]\nExplanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).\n\n\n
Example 2:
\n\n\nInput: nums = [5,1,1,2,0,0]\nOutput: [0,0,1,1,2,5]\nExplanation: Note that the values of nums are not necessairly unique.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
-5 * 104 <= nums[i] <= 5 * 104
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.
\n\nThe graph is given as follows: graph[a]
is a list of all nodes b
such that ab
is an edge of the graph.
The mouse starts at node 1
and goes first, the cat starts at node 2
and goes second, and there is a hole at node 0
.
During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1]
.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0
).
Then, the game can end in three ways:
\n\nGiven a graph
, and assuming both players play optimally, return
1
if the mouse wins the game,2
if the cat wins the game, or0
if the game is a draw.\n
Example 1:
\n\nInput: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput: 0\n\n\n
Example 2:
\n\nInput: graph = [[1,3],[0],[3],[0,2]]\nOutput: 1\n\n\n
\n
Constraints:
\n\n3 <= graph.length <= 50
1 <= graph[i].length < graph.length
0 <= graph[i][j] < graph.length
graph[i][j] != i
graph[i]
is unique.You are given an integer array deck
where deck[i]
represents the number written on the ith
card.
Partition the cards into one or more groups such that:
\n\nx
cards where x > 1
, andReturn true
if such partition is possible, or false
otherwise.
\n
Example 1:
\n\n\nInput: deck = [1,2,3,4,4,3,2,1]\nOutput: true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].\n\n\n
Example 2:
\n\n\nInput: deck = [1,1,1,2,2,2,3,3]\nOutput: false\nExplanation: No possible partition.\n\n\n
\n
Constraints:
\n\n1 <= deck.length <= 104
0 <= deck[i] < 104
Given an integer array nums
, partition it into two (contiguous) subarrays left
and right
so that:
left
is less than or equal to every element in right
.left
and right
are non-empty.left
has the smallest possible size.Return the length of left
after such a partitioning.
Test cases are generated such that partitioning exists.
\n\n\n
Example 1:
\n\n\nInput: nums = [5,0,3,8,6]\nOutput: 3\nExplanation: left = [5,0,3], right = [8,6]\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,0,6,12]\nOutput: 4\nExplanation: left = [1,1,1,0], right = [6,12]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
0 <= nums[i] <= 106
You are given two string arrays words1
and words2
.
A string b
is a subset of string a
if every letter in b
occurs in a
including multiplicity.
"wrr"
is a subset of "warrior"
but is not a subset of "world"
.A string a
from words1
is universal if for every string b
in words2
, b
is a subset of a
.
Return an array of all the universal strings in words1
. You may return the answer in any order.
\n
Example 1:
\n\nInput: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["e","o"]
\n\nOutput: ["facebook","google","leetcode"]
\nExample 2:
\n\nInput: words1 = ["amazon","apple","facebook","google","leetcode"], words2 = ["lc","eo"]
\n\nOutput: ["leetcode"]
\nExample 3:
\n\nInput: words1 = ["acaac","cccbb","aacbb","caacc","bcbbb"], words2 = ["c","cc","b"]
\n\nOutput: ["cccbb"]
\n\n
Constraints:
\n\n1 <= words1.length, words2.length <= 104
1 <= words1[i].length, words2[i].length <= 10
words1[i]
and words2[i]
consist only of lowercase English letters.words1
are unique.Given a string s
, reverse the string according to the following rules:
Return s
after reversing it.
\n
Example 1:
\nInput: s = \"ab-cd\"\nOutput: \"dc-ba\"\n
Example 2:
\nInput: s = \"a-bC-dEf-ghIj\"\nOutput: \"j-Ih-gfE-dCba\"\n
Example 3:
\nInput: s = \"Test1ng-Leet=code-Q!\"\nOutput: \"Qedo1ct-eeLg=ntse-T!\"\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of characters with ASCII values in the range [33, 122]
.s
does not contain '\\"'
or '\\\\'
.Given a circular integer array nums
of length n
, return the maximum possible sum of a non-empty subarray of nums
.
A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i]
is nums[(i + 1) % n]
and the previous element of nums[i]
is nums[(i - 1 + n) % n]
.
A subarray may only include each element of the fixed buffer nums
at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j]
, there does not exist i <= k1
, k2 <= j
with k1 % n == k2 % n
.
\n
Example 1:
\n\n\nInput: nums = [1,-2,3,-2]\nOutput: 3\nExplanation: Subarray [3] has maximum sum 3.\n\n\n
Example 2:
\n\n\nInput: nums = [5,-3,5]\nOutput: 10\nExplanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\n\n\n
Example 3:
\n\n\nInput: nums = [-3,-2,-3]\nOutput: -2\nExplanation: Subarray [-2] has maximum sum -2.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 3 * 104
-3 * 104 <= nums[i] <= 3 * 104
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.
\n\nDesign an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.
\n\nImplement the CBTInserter
class:
CBTInserter(TreeNode root)
Initializes the data structure with the root
of the complete binary tree.int insert(int v)
Inserts a TreeNode
into the tree with value Node.val == val
so that the tree remains complete, and returns the value of the parent of the inserted TreeNode
.TreeNode get_root()
Returns the root node of the tree.\n
Example 1:
\n\nInput\n["CBTInserter", "insert", "insert", "get_root"]\n[[[1, 2]], [3], [4], []]\nOutput\n[null, 1, 2, [1, 2, 3, 4]]\n\nExplanation\nCBTInserter cBTInserter = new CBTInserter([1, 2]);\ncBTInserter.insert(3); // return 1\ncBTInserter.insert(4); // return 2\ncBTInserter.get_root(); // return [1, 2, 3, 4]\n\n\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 5000
root
is a complete binary tree.0 <= val <= 5000
104
calls will be made to insert
and get_root
.Your music player contains n
different songs. You want to listen to goal
songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
k
other songs have been played.Given n
, goal
, and k
, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 3, goal = 3, k = 1\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].\n\n\n
Example 2:
\n\n\nInput: n = 2, goal = 3, k = 0\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].\n\n\n
Example 3:
\n\n\nInput: n = 2, goal = 3, k = 1\nOutput: 2\nExplanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].\n\n\n
\n
Constraints:
\n\n0 <= k < n <= goal <= 100
A parentheses string is valid if and only if:
\n\nAB
(A
concatenated with B
), where A
and B
are valid strings, or(A)
, where A
is a valid string.You are given a parentheses string s
. In one move, you can insert a parenthesis at any position of the string.
s = "()))"
, you can insert an opening parenthesis to be "(()))"
or a closing parenthesis to be "())))"
.Return the minimum number of moves required to make s
valid.
\n
Example 1:
\n\n\nInput: s = "())"\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: s = "((("\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either '('
or ')'
.Given an array of integers nums
, half of the integers in nums
are odd, and the other half are even.
Sort the array so that whenever nums[i]
is odd, i
is odd, and whenever nums[i]
is even, i
is even.
Return any answer array that satisfies this condition.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,2,5,7]\nOutput: [4,5,2,7]\nExplanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3]\nOutput: [2,3]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 2 * 104
nums.length
is even.nums
are even.0 <= nums[i] <= 1000
\n
Follow Up: Could you solve it in-place?
\n", - "likes": 2668, - "dislikes": 98, - "stats": "{\"totalAccepted\": \"284.2K\", \"totalSubmission\": \"400.7K\", \"totalAcceptedRaw\": 284240, \"totalSubmissionRaw\": 400737, \"acRate\": \"70.9%\"}", + "likes": 2697, + "dislikes": 101, + "stats": "{\"totalAccepted\": \"299.3K\", \"totalSubmission\": \"421.5K\", \"totalAcceptedRaw\": 299278, \"totalSubmissionRaw\": 421504, \"acRate\": \"71.0%\"}", "similarQuestions": "[{\"title\": \"Sort Array By Parity\", \"titleSlug\": \"sort-array-by-parity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Rearrange Array Elements by Sign\", \"titleSlug\": \"rearrange-array-elements-by-sign\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Even and Odd Indices Independently\", \"titleSlug\": \"sort-even-and-odd-indices-independently\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Largest Number After Digit Swaps by Parity\", \"titleSlug\": \"largest-number-after-digit-swaps-by-parity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find the Number of K-Even Arrays\", \"titleSlug\": \"find-the-number-of-k-even-arrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [], @@ -34798,9 +34819,9 @@ "questionFrontendId": "923", "title": "3Sum With Multiplicity", "content": "Given an integer array arr
, and an integer target
, return the number of tuples i, j, k
such that i < j < k
and arr[i] + arr[j] + arr[k] == target
.
As the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput: 20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,2,2,2,2], target = 5\nOutput: 12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.\n\n\n
Example 3:
\n\n\nInput: arr = [2,1,3], target = 6\nOutput: 1\nExplanation: (1, 2, 3) occured one time in the array so we return 1.\n\n\n
\n
Constraints:
\n\n3 <= arr.length <= 3000
0 <= arr[i] <= 100
0 <= target <= 300
You are given a network of n
nodes represented as an n x n
adjacency matrix graph
, where the ith
node is directly connected to the jth
node if graph[i][j] == 1
.
Some nodes initial
are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial)
is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial
.
Return the node that, if removed, would minimize M(initial)
. If multiple nodes could be removed to minimize M(initial)
, return such a node with the smallest index.
Note that if a node was removed from the initial
list of infected nodes, it might still be infected later due to the malware spread.
\n
Example 1:
\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\n
Example 2:
\nInput: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput: 0\n
Example 3:
\nInput: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput: 1\n\n
\n
Constraints:
\n\nn == graph.length
n == graph[i].length
2 <= n <= 300
graph[i][j]
is 0
or 1
.graph[i][j] == graph[j][i]
graph[i][i] == 1
1 <= initial.length <= n
0 <= initial[i] <= n - 1
initial
are unique.Your friend is typing his name
into a keyboard. Sometimes, when typing a character c
, the key might get long pressed, and the character will be typed 1 or more times.
You examine the typed
characters of the keyboard. Return True
if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
\n
Example 1:
\n\n\nInput: name = "alex", typed = "aaleex"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\n\n\n
Example 2:
\n\n\nInput: name = "saeed", typed = "ssaaedd"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.\n\n\n
\n
Constraints:
\n\n1 <= name.length, typed.length <= 1000
name
and typed
consist of only lowercase English letters.A binary string is monotone increasing if it consists of some number of 0
's (possibly none), followed by some number of 1
's (also possibly none).
You are given a binary string s
. You can flip s[i]
changing it from 0
to 1
or from 1
to 0
.
Return the minimum number of flips to make s
monotone increasing.
\n
Example 1:
\n\n\nInput: s = "00110"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\n\n\n
Example 2:
\n\n\nInput: s = "010110"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\n\n\n
Example 3:
\n\n\nInput: s = "00011000"\nOutput: 2\nExplanation: We flip to get 00000000.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.You are given an array arr
which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.
If it is possible, return any [i, j]
with i + 1 < j
, such that:
arr[0], arr[1], ..., arr[i]
is the first part,arr[i + 1], arr[i + 2], ..., arr[j - 1]
is the second part, andarr[j], arr[j + 1], ..., arr[arr.length - 1]
is the third part.If it is not possible, return [-1, -1]
.
Note that the entire part is used when considering what binary value it represents. For example, [1,1,0]
represents 6
in decimal, not 3
. Also, leading zeros are allowed, so [0,1,1]
and [1,1]
represent the same value.
\n
Example 1:
\nInput: arr = [1,0,1,0,1]\nOutput: [0,3]\n
Example 2:
\nInput: arr = [1,1,0,1,1]\nOutput: [-1,-1]\n
Example 3:
\nInput: arr = [1,1,0,0,1]\nOutput: [0,2]\n\n
\n
Constraints:
\n\n3 <= arr.length <= 3 * 104
arr[i]
is 0
or 1
You are given a network of n
nodes represented as an n x n
adjacency matrix graph
, where the ith
node is directly connected to the jth
node if graph[i][j] == 1
.
Some nodes initial
are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial)
is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove exactly one node from initial
, completely removing it and any connections from this node to any other node.
Return the node that, if removed, would minimize M(initial)
. If multiple nodes could be removed to minimize M(initial)
, return such a node with the smallest index.
\n
Example 1:
\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\n
Example 2:
\nInput: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput: 1\n
Example 3:
\nInput: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput: 1\n\n
\n
Constraints:
\n\nn == graph.length
n == graph[i].length
2 <= n <= 300
graph[i][j]
is 0
or 1
.graph[i][j] == graph[j][i]
graph[i][i] == 1
1 <= initial.length < n
0 <= initial[i] <= n - 1
initial
are unique.Every valid email consists of a local name and a domain name, separated by the '@'
sign. Besides lowercase letters, the email may contain one or more '.'
or '+'
.
"alice@leetcode.com"
, "alice"
is the local name, and "leetcode.com"
is the domain name.If you add periods '.'
between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.
"alice.z@leetcode.com"
and "alicez@leetcode.com"
forward to the same email address.If you add a plus '+'
in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.
"m.y+name@email.com"
will be forwarded to "my@email.com"
.It is possible to use both of these rules at the same time.
\n\nGiven an array of strings emails
where we send one email to each emails[i]
, return the number of different addresses that actually receive mails.
\n
Example 1:
\n\n\nInput: emails = ["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]\nOutput: 2\nExplanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails.\n\n\n
Example 2:
\n\n\nInput: emails = ["a@leetcode.com","b@leetcode.com","c@leetcode.com"]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= emails.length <= 100
1 <= emails[i].length <= 100
emails[i]
consist of lowercase English letters, '+'
, '.'
and '@'
.emails[i]
contains exactly one '@'
character.'+'
character.".com"
suffix.".com"
suffix.Given a binary array nums
and an integer goal
, return the number of non-empty subarrays with a sum goal
.
A subarray is a contiguous part of the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,0,1,0,1], goal = 2\nOutput: 4\nExplanation: The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,0,0,0], goal = 0\nOutput: 15\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
nums[i]
is either 0
or 1
.0 <= goal <= nums.length
Given an n x n
array of integers matrix
, return the minimum sum of any falling path through matrix
.
A falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col)
will be (row + 1, col - 1)
, (row + 1, col)
, or (row + 1, col + 1)
.
\n
Example 1:
\n\nInput: matrix = [[2,1,3],[6,5,4],[7,8,9]]\nOutput: 13\nExplanation: There are two falling paths with a minimum sum as shown.\n\n\n
Example 2:
\n\nInput: matrix = [[-19,57],[-40,-5]]\nOutput: -59\nExplanation: The falling path with a minimum sum is shown.\n\n\n
\n
Constraints:
\n\nn == matrix.length == matrix[i].length
1 <= n <= 100
-100 <= matrix[i][j] <= 100
An array nums
of length n
is beautiful if:
nums
is a permutation of the integers in the range [1, n]
.0 <= i < j < n
, there is no index k
with i < k < j
where 2 * nums[k] == nums[i] + nums[j]
.Given the integer n
, return any beautiful array nums
of length n
. There will be at least one valid answer for the given n
.
\n
Example 1:
\nInput: n = 4\nOutput: [2,1,4,3]\n
Example 2:
\nInput: n = 5\nOutput: [3,1,2,5,4]\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You have a RecentCounter
class which counts the number of recent requests within a certain time frame.
Implement the RecentCounter
class:
RecentCounter()
Initializes the counter with zero recent requests.int ping(int t)
Adds a new request at time t
, where t
represents some time in milliseconds, and returns the number of requests that has happened in the past 3000
milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t]
.It is guaranteed that every call to ping
uses a strictly larger value of t
than the previous call.
\n
Example 1:
\n\n\nInput\n["RecentCounter", "ping", "ping", "ping", "ping"]\n[[], [1], [100], [3001], [3002]]\nOutput\n[null, 1, 2, 3, 3]\n\nExplanation\nRecentCounter recentCounter = new RecentCounter();\nrecentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\nrecentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2\nrecentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3\nrecentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3\n\n\n
\n
Constraints:
\n\n1 <= t <= 109
ping
with strictly increasing values of t
.104
calls will be made to ping
.You are given an n x n
binary matrix grid
where 1
represents land and 0
represents water.
An island is a 4-directionally connected group of 1
's not connected to any other 1
's. There are exactly two islands in grid
.
You may change 0
's to 1
's to connect the two islands to form one island.
Return the smallest number of 0
's you must flip to connect the two islands.
\n
Example 1:
\n\n\nInput: grid = [[0,1],[1,0]]\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
2 <= n <= 100
grid[i][j]
is either 0
or 1
.grid
.The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:
\n\nA chess knight can move as indicated in the chess diagram below:
\nWe have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).
\nGiven an integer n
, return how many distinct phone numbers of length n
we can dial.
You are allowed to place the knight on any numeric cell initially and then you should perform n - 1
jumps to dial a number of length n
. All jumps should be valid knight jumps.
As the answer may be very large, return the answer modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 10\nExplanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 20\nExplanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\n\n\n
Example 3:
\n\n\nInput: n = 3131\nOutput: 136006598\nExplanation: Please take care of the mod.\n\n\n
\n
Constraints:
\n\n1 <= n <= 5000
You are given two strings stamp
and target
. Initially, there is a string s
of length target.length
with all s[i] == '?'
.
In one turn, you can place stamp
over s
and replace every letter in the s
with the corresponding letter from stamp
.
stamp = "abc"
and target = "abcba"
, then s
is "?????"
initially. In one turn you can:\n\n\tstamp
at index 0
of s
to obtain "abc??"
,stamp
at index 1
of s
to obtain "?abc?"
, orstamp
at index 2
of s
to obtain "??abc"
.stamp
must be fully contained in the boundaries of s
in order to stamp (i.e., you cannot place stamp
at index 3
of s
).We want to convert s
to target
using at most 10 * target.length
turns.
Return an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target
from s
within 10 * target.length
turns, return an empty array.
\n
Example 1:
\n\n\nInput: stamp = "abc", target = "ababc"\nOutput: [0,2]\nExplanation: Initially s = "?????".\n- Place stamp at index 0 to get "abc??".\n- Place stamp at index 2 to get "ababc".\n[1,0,2] would also be accepted as an answer, as well as some other answers.\n\n\n
Example 2:
\n\n\nInput: stamp = "abca", target = "aabcaca"\nOutput: [3,0,1]\nExplanation: Initially s = "???????".\n- Place stamp at index 3 to get "???abca".\n- Place stamp at index 0 to get "abcabca".\n- Place stamp at index 1 to get "aabcaca".\n\n\n
\n
Constraints:
\n\n1 <= stamp.length <= target.length <= 1000
stamp
and target
consist of lowercase English letters.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:
\n\nReorder these logs so that:
\n\nReturn the final order of the logs.
\n\n\n
Example 1:
\n\n\nInput: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]\nOutput: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]\nExplanation:\nThe letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".\nThe digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".\n\n\n
Example 2:
\n\n\nInput: logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]\nOutput: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]\n\n\n
\n
Constraints:
\n\n1 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i]
are separated by a single space.logs[i]
is guaranteed to have an identifier and at least one word after the identifier.Given the root
node of a binary search tree and two integers low
and high
, return the sum of values of all nodes with a value in the inclusive range [low, high]
.
\n
Example 1:
\n\nInput: root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n\n\n
Example 2:
\n\nInput: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n\n\n
\n
Constraints:
\n\n[1, 2 * 104]
.1 <= Node.val <= 105
1 <= low <= high <= 105
Node.val
are unique.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
.
\n
Example 1:
\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput: 4\n\n\n
Example 2:
\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 500
points[i].length == 2
0 <= xi, yi <= 4 * 104
Given a string s, return the number of distinct non-empty subsequences of s
. Since the answer may be very large, return it modulo 109 + 7
.
"ace"
is a subsequence of "abcde"
while "aec"
is not.\n\n
Example 1:
\n\n\nInput: s = "abc"\nOutput: 7\nExplanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".\n\n\n
Example 2:
\n\n\nInput: s = "aba"\nOutput: 6\nExplanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba".\n\n\n
Example 3:
\n\n\nInput: s = "aaa"\nOutput: 3\nExplanation: The 3 distinct subsequences are "a", "aa" and "aaa".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2000
s
consists of lowercase English letters.Given an array of integers arr
, return true
if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
\n\narr.length >= 3
i
with 0 < i < arr.length - 1
such that:\n\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
\n
Example 1:
\nInput: arr = [2,1]\nOutput: false\n
Example 2:
\nInput: arr = [3,5,5]\nOutput: false\n
Example 3:
\nInput: arr = [0,3,2,1]\nOutput: true\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
0 <= arr[i] <= 104
A permutation perm
of n + 1
integers of all the integers in the range [0, n]
can be represented as a string s
of length n
where:
s[i] == 'I'
if perm[i] < perm[i + 1]
, ands[i] == 'D'
if perm[i] > perm[i + 1]
.Given a string s
, reconstruct the permutation perm
and return it. If there are multiple valid permutations perm, return any of them.
\n
Example 1:
\nInput: s = \"IDID\"\nOutput: [0,4,1,3,2]\n
Example 2:
\nInput: s = \"III\"\nOutput: [0,1,2,3]\n
Example 3:
\nInput: s = \"DDI\"\nOutput: [3,2,0,1]\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either 'I'
or 'D'
.Given an array of strings words
, return the smallest string that contains each string in words
as a substring. If there are multiple valid strings of the smallest length, return any of them.
You may assume that no string in words
is a substring of another string in words
.
\n
Example 1:
\n\n\nInput: words = ["alex","loves","leetcode"]\nOutput: "alexlovesleetcode"\nExplanation: All permutations of "alex","loves","leetcode" would also be accepted.\n\n\n
Example 2:
\n\n\nInput: words = ["catg","ctaagt","gcta","ttca","atgcatc"]\nOutput: "gctaagttcatgcatc"\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 12
1 <= words[i].length <= 20
words[i]
consists of lowercase English letters.words
are unique.You are given an array of n
strings strs
, all of the same length.
The strings can be arranged such that there is one on each line, making a grid.
\n\nstrs = ["abc", "bce", "cae"]
can be arranged as follows:\nabc\nbce\ncae\n\n\n
You want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a'
, 'b'
, 'c'
) and 2 ('c'
, 'e'
, 'e'
) are sorted, while column 1 ('b'
, 'c'
, 'a'
) is not, so you would delete column 1.
Return the number of columns that you will delete.
\n\n\n
Example 1:
\n\n\nInput: strs = ["cba","daf","ghi"]\nOutput: 1\nExplanation: The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.\n\n\n
Example 2:
\n\n\nInput: strs = ["a","b"]\nOutput: 0\nExplanation: The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.\n\n\n
Example 3:
\n\n\nInput: strs = ["zyx","wvu","tsr"]\nOutput: 3\nExplanation: The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.\n\n\n
\n
Constraints:
\n\nn == strs.length
1 <= n <= 100
1 <= strs[i].length <= 1000
strs[i]
consists of lowercase English letters.You are given an integer array nums
. In one move, you can pick an index i
where 0 <= i < nums.length
and increment nums[i]
by 1
.
Return the minimum number of moves to make every value in nums
unique.
The test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,2]\nOutput: 1\nExplanation: After 1 move, the array could be [1, 2, 3].\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,1,2,1,7]\nOutput: 6\nExplanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown that it is impossible for the array to have all unique values with 5 or less moves.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
Given two integer arrays pushed
and popped
each with distinct values, return true
if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false
otherwise.
\n
Example 1:
\n\n\nInput: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput: true\nExplanation: We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n\n\n
Example 2:
\n\n\nInput: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput: false\nExplanation: 1 cannot be popped before 2.\n\n\n
\n
Constraints:
\n\n1 <= pushed.length <= 1000
0 <= pushed[i] <= 1000
pushed
are unique.popped.length == pushed.length
popped
is a permutation of pushed
.On a 2D plane, we place n
stones at some integer coordinate points. Each coordinate point may have at most one stone.
A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.
\n\nGiven an array stones
of length n
where stones[i] = [xi, yi]
represents the location of the ith
stone, return the largest possible number of stones that can be removed.
\n
Example 1:
\n\n\nInput: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput: 5\nExplanation: One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.\n\n\n
Example 2:
\n\n\nInput: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput: 3\nExplanation: One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.\n\n\n
Example 3:
\n\n\nInput: stones = [[0,0]]\nOutput: 0\nExplanation: [0,0] is the only stone on the plane, so you cannot remove it.\n\n\n
\n
Constraints:
\n\n1 <= stones.length <= 1000
0 <= xi, yi <= 104
You start with an initial power of power
, an initial score of 0
, and a bag of tokens given as an integer array tokens
, where each tokens[i]
denotes the value of tokeni.
Your goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):
\n\ntokens[i]
, you may play tokeni, losing tokens[i]
power and gaining 1
score.1
, you may play tokeni, gaining tokens[i]
power and losing 1
score.Return the maximum possible score you can achieve after playing any number of tokens.
\n\n\n
Example 1:
\n\nInput: tokens = [100], power = 50
\n\nOutput: 0
\n\nExplanation: Since your score is 0
initially, you cannot play the token face-down. You also cannot play it face-up since your power (50
) is less than tokens[0]
(100
).
Example 2:
\n\nInput: tokens = [200,100], power = 150
\n\nOutput: 1
\n\nExplanation: Play token1 (100
) face-up, reducing your power to 50
and increasing your score to 1
.
There is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1
.
Example 3:
\n\nInput: tokens = [100,200,300,400], power = 200
\n\nOutput: 2
\n\nExplanation: Play the tokens in this order to get a score of 2
:
100
) face-up, reducing power to 100
and increasing score to 1
.400
) face-down, increasing power to 500
and reducing score to 0
.200
) face-up, reducing power to 300
and increasing score to 1
.300
) face-up, reducing power to 0
and increasing score to 2
.The maximum score achievable is 2
.
\n
Constraints:
\n\n0 <= tokens.length <= 1000
0 <= tokens[i], power < 104
Given an array arr
of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.
24-hour times are formatted as "HH:MM"
, where HH
is between 00
and 23
, and MM
is between 00
and 59
. The earliest 24-hour time is 00:00
, and the latest is 23:59
.
Return the latest 24-hour time in "HH:MM"
format. If no valid time can be made, return an empty string.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4]\nOutput: "23:41"\nExplanation: The valid 24-hour times are "12:34", "12:43", "13:24", "13:42", "14:23", "14:32", "21:34", "21:43", "23:14", and "23:41". Of these times, "23:41" is the latest.\n\n\n
Example 2:
\n\n\nInput: arr = [5,5,5,5]\nOutput: ""\nExplanation: There are no valid 24-hour times as "55:55" is not valid.\n\n\n
\n
Constraints:
\n\narr.length == 4
0 <= arr[i] <= 9
You are given an integer array deck
. There is a deck of cards where every card has a unique integer. The integer on the ith
card is deck[i]
.
You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.
\n\nYou will do the following steps repeatedly until all cards are revealed:
\n\nReturn an ordering of the deck that would reveal the cards in increasing order.
\n\nNote that the first entry in the answer is considered to be the top of the deck.
\n\n\n
Example 1:
\n\n\nInput: deck = [17,13,11,2,3,5,7]\nOutput: [2,13,3,11,5,17,7]\nExplanation: \nWe get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.\n\n\n
Example 2:
\n\n\nInput: deck = [1,1000]\nOutput: [1,1000]\n\n\n
\n
Constraints:
\n\n1 <= deck.length <= 1000
1 <= deck[i] <= 106
deck
are unique.For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
\n\nA binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
\n\nGiven the roots of two binary trees root1
and root2
, return true
if the two trees are flip equivalent or false
otherwise.
\n
Example 1:
\n\nInput: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput: true\nExplanation: We flipped at nodes with values 1, 3, and 5.\n\n\n
Example 2:
\n\n\nInput: root1 = [], root2 = []\nOutput: true\n\n\n
Example 3:
\n\n\nInput: root1 = [], root2 = [1]\nOutput: false\n\n\n
\n
Constraints:
\n\n[0, 100]
.[0, 99]
.You are given an integer array of unique positive integers nums
. Consider the following graph:
nums.length
nodes, labeled nums[0]
to nums[nums.length - 1]
,nums[i]
and nums[j]
if nums[i]
and nums[j]
share a common factor greater than 1
.Return the size of the largest connected component in the graph.
\n\n\n
Example 1:
\n\nInput: nums = [4,6,15,35]\nOutput: 4\n\n\n
Example 2:
\n\nInput: nums = [20,50,9,63]\nOutput: 2\n\n\n
Example 3:
\n\nInput: nums = [2,3,6,7,4,12,21,39]\nOutput: 8\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= nums[i] <= 105
nums
are unique.In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order
. The order
of the alphabet is some permutation of lowercase letters.
Given a sequence of words
written in the alien language, and the order
of the alphabet, return true
if and only if the given words
are sorted lexicographically in this alien language.
\n
Example 1:
\n\n\nInput: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"\nOutput: true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.\n\n\n
Example 2:
\n\n\nInput: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"\nOutput: false\nExplanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.\n\n\n
Example 3:
\n\n\nInput: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"\nOutput: false\nExplanation: The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" > "app", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character (More info).\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
words[i]
and order
are English lowercase letters.Given an integer array of even length arr
, return true
if it is possible to reorder arr
such that arr[2 * i + 1] = 2 * arr[2 * i]
for every 0 <= i < len(arr) / 2
, or false
otherwise.
\n
Example 1:
\n\n\nInput: arr = [3,1,3,6]\nOutput: false\n\n\n
Example 2:
\n\n\nInput: arr = [2,1,2,6]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: arr = [4,-2,2,-4]\nOutput: true\nExplanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 3 * 104
arr.length
is even.-105 <= arr[i] <= 105
You are given an array of n
strings strs
, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
\n\nFor example, if we have strs = ["abcdef","uvwxyz"]
and deletion indices {0, 2, 3}
, then the final array after deletions is ["bef", "vyz"]
.
Suppose we chose a set of deletion indices answer
such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]
). Return the minimum possible value of answer.length
.
\n
Example 1:
\n\n\nInput: strs = ["ca","bb","ac"]\nOutput: 1\nExplanation: \nAfter deleting the first column, strs = ["a", "b", "c"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.\n\n\n
Example 2:
\n\n\nInput: strs = ["xc","yb","za"]\nOutput: 0\nExplanation: \nstrs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)\n\n\n
Example 3:
\n\n\nInput: strs = ["zyx","wvu","tsr"]\nOutput: 3\nExplanation: We have to delete every column.\n\n\n
\n
Constraints:
\n\nn == strs.length
1 <= n <= 100
1 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
\n\nYou are given a collection of rods
that can be welded together. For example, if you have rods of lengths 1
, 2
, and 3
, you can weld them together to make a support of length 6
.
Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0
.
\n
Example 1:
\n\n\nInput: rods = [1,2,3,6]\nOutput: 6\nExplanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n\n\n
Example 2:
\n\n\nInput: rods = [1,2,3,4,5,6]\nOutput: 10\nExplanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n\n\n
Example 3:
\n\n\nInput: rods = [1,2]\nOutput: 0\nExplanation: The billboard cannot be supported, so we return 0.\n\n\n
\n
Constraints:
\n\n1 <= rods.length <= 20
1 <= rods[i] <= 1000
sum(rods[i]) <= 5000
There are 8
prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
\n\nNote that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
\n\nYou are given an integer array cells
where cells[i] == 1
if the ith
cell is occupied and cells[i] == 0
if the ith
cell is vacant, and you are given an integer n
.
Return the state of the prison after n
days (i.e., n
such changes described above).
\n
Example 1:
\n\n\nInput: cells = [0,1,0,1,1,0,0,1], n = 7\nOutput: [0,0,1,1,0,0,0,0]\nExplanation: The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]\n\n\n
Example 2:
\n\n\nInput: cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput: [0,0,1,1,1,1,1,0]\n\n\n
\n
Constraints:
\n\ncells.length == 8
cells[i]
is either 0
or 1
.1 <= n <= 109
Given the root
of a binary tree, determine if it is a complete binary tree.
In a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1
and 2h
nodes inclusive at the last level h
.
\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6]\nOutput: true\nExplanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\n\n\n
Example 2:
\n\nInput: root = [1,2,3,4,5,null,7]\nOutput: false\nExplanation: The node with value 7 isn't as far left as possible.\n\n\n
\n
Constraints:
\n\n[1, 100]
.1 <= Node.val <= 1000
An n x n
grid is composed of 1 x 1
squares where each 1 x 1
square consists of a '/'
, '\\'
, or blank space ' '
. These characters divide the square into contiguous regions.
Given the grid grid
represented as a string array, return the number of regions.
Note that backslash characters are escaped, so a '\\'
is represented as '\\\\'
.
\n
Example 1:
\n\nInput: grid = [" /","/ "]\nOutput: 2\n\n\n
Example 2:
\n\nInput: grid = [" /"," "]\nOutput: 1\n\n\n
Example 3:
\n\nInput: grid = ["/\\\\","\\\\/"]\nOutput: 5\nExplanation: Recall that because \\ characters are escaped, "\\\\/" refers to \\/, and "/\\\\" refers to /\\.\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
1 <= n <= 30
grid[i][j]
is either '/'
, '\\'
, or ' '
.You are given an array of n
strings strs
, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
\n\nFor example, if we have strs = ["abcdef","uvwxyz"]
and deletion indices {0, 2, 3}
, then the final array after deletions is ["bef", "vyz"]
.
Suppose we chose a set of deletion indices answer
such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])
, and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])
, and so on). Return the minimum possible value of answer.length
.
\n
Example 1:
\n\n\nInput: strs = ["babca","bbazb"]\nOutput: 3\nExplanation: After deleting columns 0, 1, and 4, the final array is strs = ["bc", "az"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\n\n
Example 2:
\n\n\nInput: strs = ["edcba"]\nOutput: 4\nExplanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\n\n\n
Example 3:
\n\n\nInput: strs = ["ghi","def","abc"]\nOutput: 0\nExplanation: All rows are already lexicographically sorted.\n\n\n
\n
Constraints:
\n\nn == strs.length
1 <= n <= 100
1 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.You are given an integer array nums
with the following properties:
nums.length == 2 * n
.nums
contains n + 1
unique elements.nums
is repeated n
times.Return the element that is repeated n
times.
\n
Example 1:
\nInput: nums = [1,2,3,3]\nOutput: 3\n
Example 2:
\nInput: nums = [2,1,2,5,3,2]\nOutput: 2\n
Example 3:
\nInput: nums = [5,1,5,2,5,3,5,4]\nOutput: 5\n\n
\n
Constraints:
\n\n2 <= n <= 5000
nums.length == 2 * n
0 <= nums[i] <= 104
nums
contains n + 1
unique elements and one of them is repeated exactly n
times.A ramp in an integer array nums
is a pair (i, j)
for which i < j
and nums[i] <= nums[j]
. The width of such a ramp is j - i
.
Given an integer array nums
, return the maximum width of a ramp in nums
. If there is no ramp in nums
, return 0
.
\n
Example 1:
\n\n\nInput: nums = [6,0,8,2,1,5]\nOutput: 4\nExplanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [9,8,1,0,1,9,4,0,4,1]\nOutput: 7\nExplanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 5 * 104
0 <= nums[i] <= 5 * 104
You are given an array of points in the X-Y plane points
where points[i] = [xi, yi]
.
Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0
.
Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\nInput: points = [[1,2],[2,1],[1,0],[0,1]]\nOutput: 2.00000\nExplanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.\n\n\n
Example 2:
\n\nInput: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput: 1.00000\nExplanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.\n\n\n
Example 3:
\n\nInput: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput: 0\nExplanation: There is no possible rectangle to form from these points.\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 50
points[i].length == 2
0 <= xi, yi <= 4 * 104
Given a single positive integer x
, we will write an expression of the form x (op1) x (op2) x (op3) x ...
where each operator op1
, op2
, etc. is either addition, subtraction, multiplication, or division (+
, -
, *
, or /)
. For example, with x = 3
, we might write 3 * 3 / 3 + 3 - 3
which is a value of 3.
When writing such an expression, we adhere to the following conventions:
\n\n/
) returns rational numbers.-
). For example, "x - x
" is a valid expression as it only uses subtraction, but "-x + x
" is not because it uses negation.We would like to write an expression with the least number of operators such that the expression equals the given target
. Return the least number of operators used.
\n
Example 1:
\n\n\nInput: x = 3, target = 19\nOutput: 5\nExplanation: 3 * 3 + 3 * 3 + 3 / 3.\nThe expression contains 5 operations.\n\n\n
Example 2:
\n\n\nInput: x = 5, target = 501\nOutput: 8\nExplanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\nThe expression contains 8 operations.\n\n\n
Example 3:
\n\n\nInput: x = 100, target = 100000000\nOutput: 3\nExplanation: 100 * 100 * 100 * 100.\nThe expression contains 3 operations.\n\n\n
\n
Constraints:
\n\n2 <= x <= 100
1 <= target <= 2 * 108
A binary tree is uni-valued if every node in the tree has the same value.
\n\nGiven the root
of a binary tree, return true
if the given tree is uni-valued, or false
otherwise.
\n
Example 1:
\n\nInput: root = [1,1,1,1,1,null,1]\nOutput: true\n\n\n
Example 2:
\n\nInput: root = [2,2,2,5,2]\nOutput: false\n\n\n
\n
Constraints:
\n\n[1, 100]
.0 <= Node.val < 100
Given a wordlist
, we want to implement a spellchecker that converts a query word into a correct word.
For a given query
word, the spell checker handles two categories of spelling mistakes:
wordlist = ["yellow"]
, query = "YellOw"
: correct = "yellow"
wordlist = ["Yellow"]
, query = "yellow"
: correct = "Yellow"
wordlist = ["yellow"]
, query = "yellow"
: correct = "yellow"
('a', 'e', 'i', 'o', 'u')
of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.\n\twordlist = ["YellOw"]
, query = "yollow"
: correct = "YellOw"
wordlist = ["YellOw"]
, query = "yeellow"
: correct = ""
(no match)wordlist = ["YellOw"]
, query = "yllw"
: correct = ""
(no match)In addition, the spell checker operates under the following precedence rules:
\n\nGiven some queries
, return a list of words answer
, where answer[i]
is the correct word for query = queries[i]
.
\n
Example 1:
\nInput: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\n
Example 2:
\nInput: wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput: [\"yellow\"]\n\n
\n
Constraints:
\n\n1 <= wordlist.length, queries.length <= 5000
1 <= wordlist[i].length, queries[i].length <= 7
wordlist[i]
and queries[i]
consist only of only English letters.Given two integers n and k, return an array of all the integers of length n
where the difference between every two consecutive digits is k
. You may return the answer in any order.
Note that the integers should not have leading zeros. Integers as 02
and 043
are not allowed.
\n
Example 1:
\n\n\nInput: n = 3, k = 7\nOutput: [181,292,707,818,929]\nExplanation: Note that 070 is not a valid number, because it has leading zeroes.\n\n\n
Example 2:
\n\n\nInput: n = 2, k = 1\nOutput: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n\n\n
\n
Constraints:
\n\n2 <= n <= 9
0 <= k <= 9
You are given the root
of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return the minimum number of cameras needed to monitor all nodes of the tree.
\n\n\n
Example 1:
\n\nInput: root = [0,0,null,0,0]\nOutput: 1\nExplanation: One camera is enough to monitor all nodes if placed as shown.\n\n\n
Example 2:
\n\nInput: root = [0,0,null,0,null,0,null,null,0]\nOutput: 2\nExplanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.\n\n\n
\n
Constraints:
\n\n[1, 1000]
.Node.val == 0
Given an array of integers arr
, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
\n\nk
where 1 <= k <= arr.length
.arr[0...k-1]
(0-indexed).For example, if arr = [3,2,1,4]
and we performed a pancake flip choosing k = 3
, we reverse the sub-array [3,2,1]
, so arr = [1,2,3,4]
after the pancake flip at k = 3
.
Return an array of the k
-values corresponding to a sequence of pancake flips that sort arr
. Any valid answer that sorts the array within 10 * arr.length
flips will be judged as correct.
\n
Example 1:
\n\n\nInput: arr = [3,2,4,1]\nOutput: [4,2,4,3]\nExplanation: \nWe perform 4 pancake flips, with k values 4, 2, 4, and 3.\nStarting state: arr = [3, 2, 4, 1]\nAfter 1st flip (k = 4): arr = [1, 4, 2, 3]\nAfter 2nd flip (k = 2): arr = [4, 1, 2, 3]\nAfter 3rd flip (k = 4): arr = [3, 2, 1, 4]\nAfter 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,3]\nOutput: []\nExplanation: The input is already sorted, so there is no need to flip anything.\nNote that other answers, such as [3, 3], would also be accepted.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 100
1 <= arr[i] <= arr.length
arr
are unique (i.e. arr
is a permutation of the integers from 1
to arr.length
).Given three integers x
, y
, and bound
, return a list of all the powerful integers that have a value less than or equal to bound
.
An integer is powerful if it can be represented as xi + yj
for some integers i >= 0
and j >= 0
.
You may return the answer in any order. In your answer, each value should occur at most once.
\n\n\n
Example 1:
\n\n\nInput: x = 2, y = 3, bound = 10\nOutput: [2,3,4,5,7,9,10]\nExplanation:\n2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32\n\n\n
Example 2:
\n\n\nInput: x = 3, y = 5, bound = 15\nOutput: [2,4,6,8,10,14]\n\n\n
\n
Constraints:
\n\n1 <= x, y <= 100
0 <= bound <= 106
You are given the root
of a binary tree with n
nodes, where each node is uniquely assigned a value from 1
to n
. You are also given a sequence of n
values voyage
, which is the desired pre-order traversal of the binary tree.
Any node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
\nFlip the smallest number of nodes so that the pre-order traversal of the tree matches voyage
.
Return a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage
, return the list [-1]
.
\n
Example 1:
\n\nInput: root = [1,2], voyage = [2,1]\nOutput: [-1]\nExplanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\n\n\n
Example 2:
\n\nInput: root = [1,2,3], voyage = [1,3,2]\nOutput: [1]\nExplanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\n\n
Example 3:
\n\nInput: root = [1,2,3], voyage = [1,2,3]\nOutput: []\nExplanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n\n\n
\n
Constraints:
\n\nn
.n == voyage.length
1 <= n <= 100
1 <= Node.val, voyage[i] <= n
voyage
are unique.Given two strings s
and t
, each of which represents a non-negative rational number, return true
if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A rational number can be represented using up to three parts: <IntegerPart>
, <NonRepeatingPart>
, and a <RepeatingPart>
. The number will be represented in one of the following three ways:
<IntegerPart>
\n\n\t12
, 0
, and 123
.<IntegerPart><.><NonRepeatingPart>
\n\t0.5
, 1.
, 2.12
, and 123.0001
.<IntegerPart><.><NonRepeatingPart><(><RepeatingPart><)>
\n\t0.1(6)
, 1.(9)
, 123.00(1212)
.The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
\n\n1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)
.\n
Example 1:
\n\n\nInput: s = "0.(52)", t = "0.5(25)"\nOutput: true\nExplanation: Because "0.(52)" represents 0.52525252..., and "0.5(25)" represents 0.52525252525..... , the strings represent the same number.\n\n\n
Example 2:
\n\n\nInput: s = "0.1666(6)", t = "0.166(66)"\nOutput: true\n\n\n
Example 3:
\n\n\nInput: s = "0.9(9)", t = "1."\nOutput: true\nExplanation: "0.9(9)" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n"1." represents the number 1, which is formed correctly: (IntegerPart) = "1" and (NonRepeatingPart) = "".\n\n\n
\n
Constraints:
\n\n<IntegerPart>
does not have leading zeros (except for the zero itself).1 <= <IntegerPart>.length <= 4
0 <= <NonRepeatingPart>.length <= 4
1 <= <RepeatingPart>.length <= 4
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane and an integer k
, return the k
closest points to the origin (0, 0)
.
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2
).
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
\n\n\n
Example 1:
\n\nInput: points = [[1,3],[-2,2]], k = 1\nOutput: [[-2,2]]\nExplanation:\nThe distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].\n\n\n
Example 2:
\n\n\nInput: points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput: [[3,3],[-2,4]]\nExplanation: The answer [[-2,4],[3,3]] would also be accepted.\n\n\n
\n
Constraints:
\n\n1 <= k <= points.length <= 104
-104 <= xi, yi <= 104
Given an integer array nums
and an integer k
, return the number of non-empty subarrays that have a sum divisible by k
.
A subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,5,0,-2,-3,1], k = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n\n\n
Example 2:
\n\n\nInput: nums = [5], k = 9\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
You are given an integer array arr
. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.
You may jump forward from index i
to index j
(with i < j
) in the following way:
j
such that arr[i] <= arr[j]
and arr[j]
is the smallest possible value. If there are multiple such indices j
, you can only jump to the smallest such index j
.j
such that arr[i] >= arr[j]
and arr[j]
is the largest possible value. If there are multiple such indices j
, you can only jump to the smallest such index j
.i
, there are no legal jumps.A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1
) by jumping some number of times (possibly 0 or more than once).
Return the number of good starting indices.
\n\n\n
Example 1:
\n\n\nInput: arr = [10,13,12,14,15]\nOutput: 2\nExplanation: \nFrom starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.\n\n\n
Example 2:
\n\n\nInput: arr = [2,3,1,1,4]\nOutput: 3\nExplanation: \nFrom starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.\n\n\n
Example 3:
\n\n\nInput: arr = [5,1,3,4,2]\nOutput: 3\nExplanation: We can reach the end from starting indices 1, 2, and 4.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 2 * 104
0 <= arr[i] < 105
Given an integer array nums
, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0
.
\n
Example 1:
\n\n\nInput: nums = [2,1,2]\nOutput: 5\nExplanation: You can form a triangle with three side lengths: 1, 2, and 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,10]\nOutput: 0\nExplanation: \nYou cannot use the side lengths 1, 1, and 2 to form a triangle.\nYou cannot use the side lengths 1, 1, and 10 to form a triangle.\nYou cannot use the side lengths 1, 2, and 10 to form a triangle.\nAs we cannot use any three side lengths to form a triangle of non-zero area, we return 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 104
1 <= nums[i] <= 106
Given an integer array nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
\n
Example 1:
\n\n\nInput: nums = [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\nExplanation: After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].\n\n\n
Example 2:
\n\n\nInput: nums = [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums
is sorted in non-decreasing order.\nFollow up: Squaring each element and sorting the new array is very trivial, could you find an
O(n)
solution using a different approach?",
- "likes": 9555,
- "dislikes": 249,
- "stats": "{\"totalAccepted\": \"2.1M\", \"totalSubmission\": \"2.9M\", \"totalAcceptedRaw\": 2098336, \"totalSubmissionRaw\": 2872365, \"acRate\": \"73.1%\"}",
+ "likes": 9696,
+ "dislikes": 254,
+ "stats": "{\"totalAccepted\": \"2.2M\", \"totalSubmission\": \"3.1M\", \"totalAcceptedRaw\": 2235956, \"totalSubmissionRaw\": 3053965, \"acRate\": \"73.2%\"}",
"similarQuestions": "[{\"title\": \"Merge Sorted Array\", \"titleSlug\": \"merge-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sort Transformed Array\", \"titleSlug\": \"sort-transformed-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [],
@@ -36892,9 +36916,9 @@
"questionFrontendId": "978",
"title": "Longest Turbulent Subarray",
"content": "Given an integer array arr
, return the length of a maximum size turbulent subarray of arr
.
A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
\n\nMore formally, a subarray [arr[i], arr[i + 1], ..., arr[j]]
of arr
is said to be turbulent if and only if:
i <= k < j
:\n\n\tarr[k] > arr[k + 1]
when k
is odd, andarr[k] < arr[k + 1]
when k
is even.i <= k < j
:\n\tarr[k] > arr[k + 1]
when k
is even, andarr[k] < arr[k + 1]
when k
is odd.\n
Example 1:
\n\n\nInput: arr = [9,4,2,10,7,8,8,1,9]\nOutput: 5\nExplanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]\n\n\n
Example 2:
\n\n\nInput: arr = [4,8,12,16]\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: arr = [100]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 4 * 104
0 <= arr[i] <= 109
You are given the root
of a binary tree with n
nodes where each node
in the tree has node.val
coins. There are n
coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
\n\nReturn the minimum number of moves required to make every node have exactly one coin.
\n\n\n
Example 1:
\n\nInput: root = [3,0,0]\nOutput: 2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.\n\n\n
Example 2:
\n\nInput: root = [0,3,0]\nOutput: 3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.\n\n\n
\n
Constraints:
\n\nn
.1 <= n <= 100
0 <= Node.val <= n
Node.val
is n
.You are given an m x n
integer array grid
where grid[i][j]
could be:
1
representing the starting square. There is exactly one starting square.2
representing the ending square. There is exactly one ending square.0
representing empty squares we can walk over.-1
representing obstacles that we cannot walk over.Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
\n\n\n
Example 1:
\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput: 2\nExplanation: We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n\n\n
Example 2:
\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput: 4\nExplanation: We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n\n\n
Example 3:
\n\nInput: grid = [[0,1],[2,0]]\nOutput: 0\nExplanation: There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 20
1 <= m * n <= 20
-1 <= grid[i][j] <= 2
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
\n\nImplement the TimeMap
class:
TimeMap()
Initializes the object of the data structure.void set(String key, String value, int timestamp)
Stores the key key
with the value value
at the given time timestamp
.String get(String key, int timestamp)
Returns a value such that set
was called previously, with timestamp_prev <= timestamp
. If there are multiple such values, it returns the value associated with the largest timestamp_prev
. If there are no values, it returns ""
.\n
Example 1:
\n\n\nInput\n["TimeMap", "set", "get", "get", "set", "get", "get"]\n[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]\nOutput\n[null, null, "bar", "bar", null, "bar2", "bar2"]\n\nExplanation\nTimeMap timeMap = new TimeMap();\ntimeMap.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1.\ntimeMap.get("foo", 1); // return "bar"\ntimeMap.get("foo", 3); // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".\ntimeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.\ntimeMap.get("foo", 4); // return "bar2"\ntimeMap.get("foo", 5); // return "bar2"\n\n\n
\n
Constraints:
\n\n1 <= key.length, value.length <= 100
key
and value
consist of lowercase English letters and digits.1 <= timestamp <= 107
timestamp
of set
are strictly increasing.2 * 105
calls will be made to set
and get
.Given an integer array nums, return the number of AND triples.
\n\nAn AND triple is a triple of indices (i, j, k)
such that:
0 <= i < nums.length
0 <= j < nums.length
0 <= k < nums.length
nums[i] & nums[j] & nums[k] == 0
, where &
represents the bitwise-AND operator.\n
Example 1:
\n\n\nInput: nums = [2,1,3]\nOutput: 12\nExplanation: We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,0]\nOutput: 27\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] < 216
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days
. Each day is an integer from 1
to 365
.
Train tickets are sold in three different ways:
\n\ncosts[0]
dollars,costs[1]
dollars, andcosts[2]
dollars.The passes allow that many days of consecutive travel.
\n\n2
, then we can travel for 7
days: 2
, 3
, 4
, 5
, 6
, 7
, and 8
.Return the minimum number of dollars you need to travel every day in the given list of days.
\n\n\n
Example 1:
\n\n\nInput: days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput: 11\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.\n\n\n
Example 2:
\n\n\nInput: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput: 17\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.\n\n\n
\n
Constraints:
\n\n1 <= days.length <= 365
1 <= days[i] <= 365
days
is in strictly increasing order.costs.length == 3
1 <= costs[i] <= 1000
Given two integers a
and b
, return any string s
such that:
s
has length a + b
and contains exactly a
'a'
letters, and exactly b
'b'
letters,'aaa'
does not occur in s
, and'bbb'
does not occur in s
.\n
Example 1:
\n\n\nInput: a = 1, b = 2\nOutput: "abb"\nExplanation: "abb", "bab" and "bba" are all correct answers.\n\n\n
Example 2:
\n\n\nInput: a = 4, b = 1\nOutput: "aabaa"\n\n\n
\n
Constraints:
\n\n0 <= a, b <= 100
s
exists for the given a
and b
.You are given an integer array nums
and an array queries
where queries[i] = [vali, indexi]
.
For each query i
, first, apply nums[indexi] = nums[indexi] + vali
, then print the sum of the even values of nums
.
Return an integer array answer
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput: [8,6,2,4]\nExplanation: At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n\n\n
Example 2:
\n\n\nInput: nums = [1], queries = [[4,0]]\nOutput: [0]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-104 <= nums[i] <= 104
1 <= queries.length <= 104
-104 <= vali <= 104
0 <= indexi < nums.length
You are given two lists of closed intervals, firstList
and secondList
, where firstList[i] = [starti, endi]
and secondList[j] = [startj, endj]
. Each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
\n\nA closed interval [a, b]
(with a <= b
) denotes the set of real numbers x
with a <= x <= b
.
The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3]
and [2, 4]
is [2, 3]
.
\n
Example 1:
\n\nInput: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\n\n\n
Example 2:
\n\n\nInput: firstList = [[1,3],[5,9]], secondList = []\nOutput: []\n\n\n
\n
Constraints:
\n\n0 <= firstList.length, secondList.length <= 1000
firstList.length + secondList.length >= 1
0 <= starti < endi <= 109
endi < starti+1
0 <= startj < endj <= 109
endj < startj+1
Given the root
of a binary tree, calculate the vertical order traversal of the binary tree.
For each node at position (row, col)
, its left and right children will be at positions (row + 1, col - 1)
and (row + 1, col + 1)
respectively. The root of the tree is at (0, 0)
.
The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.
\n\nReturn the vertical order traversal of the binary tree.
\n\n\n
Example 1:
\n\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[9],[3,15],[20],[7]]\nExplanation:\nColumn -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.\n\n
Example 2:
\n\nInput: root = [1,2,3,4,5,6,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nColumn -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.\n\n\n
Example 3:
\n\nInput: root = [1,2,3,4,6,5,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nThis case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.\n\n\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 1000
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.
\n\nAs a reminder, any shorter prefix of a string is lexicographically smaller.
\n\n"ab"
is lexicographically smaller than "aba"
.A leaf of a node is a node that has no children.
\n\n\n
Example 1:
\n\nInput: root = [0,1,2,3,4,3,4]\nOutput: "dba"\n\n\n
Example 2:
\n\nInput: root = [25,1,3,1,3,0,2]\nOutput: "adz"\n\n\n
Example 3:
\n\nInput: root = [2,2,1,null,1,0,null,0]\nOutput: "abc"\n\n\n
\n
Constraints:
\n\n[1, 8500]
.0 <= Node.val <= 25
The array-form of an integer num
is an array representing its digits in left to right order.
num = 1321
, the array form is [1,3,2,1]
.Given num
, the array-form of an integer, and an integer k
, return the array-form of the integer num + k
.
\n
Example 1:
\n\n\nInput: num = [1,2,0,0], k = 34\nOutput: [1,2,3,4]\nExplanation: 1200 + 34 = 1234\n\n\n
Example 2:
\n\n\nInput: num = [2,7,4], k = 181\nOutput: [4,5,5]\nExplanation: 274 + 181 = 455\n\n\n
Example 3:
\n\n\nInput: num = [2,1,5], k = 806\nOutput: [1,0,2,1]\nExplanation: 215 + 806 = 1021\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 104
0 <= num[i] <= 9
num
does not contain any leading zeros except for the zero itself.1 <= k <= 104
You are given an array of strings equations
that represent relationships between variables where each string equations[i]
is of length 4
and takes one of two different forms: "xi==yi"
or "xi!=yi"
.Here, xi
and yi
are lowercase letters (not necessarily different) that represent one-letter variable names.
Return true
if it is possible to assign integers to variable names so as to satisfy all the given equations, or false
otherwise.
\n
Example 1:
\n\n\nInput: equations = ["a==b","b!=a"]\nOutput: false\nExplanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.\n\n\n
Example 2:
\n\n\nInput: equations = ["b==a","a==b"]\nOutput: true\nExplanation: We could assign a = 1 and b = 1 to satisfy both equations.\n\n\n
\n
Constraints:
\n\n1 <= equations.length <= 500
equations[i].length == 4
equations[i][0]
is a lowercase letter.equations[i][1]
is either '='
or '!'
.equations[i][2]
is '='
.equations[i][3]
is a lowercase letter.There is a broken calculator that has the integer startValue
on its display initially. In one operation, you can:
2
, or1
from the number on display.Given two integers startValue
and target
, return the minimum number of operations needed to display target
on the calculator.
\n
Example 1:
\n\n\nInput: startValue = 2, target = 3\nOutput: 2\nExplanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n\n\n
Example 2:
\n\n\nInput: startValue = 5, target = 8\nOutput: 2\nExplanation: Use decrement and then double {5 -> 4 -> 8}.\n\n\n
Example 3:
\n\n\nInput: startValue = 3, target = 10\nOutput: 3\nExplanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n\n\n
\n
Constraints:
\n\n1 <= startValue, target <= 109
Given an integer array nums
and an integer k
, return the number of good subarrays of nums
.
A good array is an array where the number of different integers in that array is exactly k
.
[1,2,3,1,2]
has 3
different integers: 1
, 2
, and 3
.A subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,2,3], k = 2\nOutput: 7\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,3,4], k = 3\nOutput: 3\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= nums[i], k <= nums.length
Given the root
of a binary tree with unique values and the values of two different nodes of the tree x
and y
, return true
if the nodes corresponding to the values x
and y
in the tree are cousins, or false
otherwise.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
\n\nNote that in a binary tree, the root node is at the depth 0
, and children of each depth k
node are at the depth k + 1
.
\n
Example 1:
\n\nInput: root = [1,2,3,4], x = 4, y = 3\nOutput: false\n\n\n
Example 2:
\n\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput: true\n\n\n
Example 3:
\n\nInput: root = [1,2,3,null,4], x = 2, y = 3\nOutput: false\n\n\n
\n
Constraints:
\n\n[2, 100]
.1 <= Node.val <= 100
x != y
x
and y
are exist in the tree.You are given an m x n
grid
where each cell can have one of three values:
0
representing an empty cell,1
representing a fresh orange, or2
representing a rotten orange.Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.
\n\nReturn the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1
.
\n
Example 1:
\n\nInput: grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput: 4\n\n\n
Example 2:
\n\n\nInput: grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput: -1\nExplanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.\n\n\n
Example 3:
\n\n\nInput: grid = [[0,2]]\nOutput: 0\nExplanation: Since there are already no fresh oranges at minute 0, the answer is just 0.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 10
grid[i][j]
is 0
, 1
, or 2
.You are given a binary array nums
and an integer k
.
A k-bit flip is choosing a subarray of length k
from nums
and simultaneously changing every 0
in the subarray to 1
, and every 1
in the subarray to 0
.
Return the minimum number of k-bit flips required so that there is no 0
in the array. If it is not possible, return -1
.
A subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,1,0], k = 1\nOutput: 2\nExplanation: Flip nums[0], then flip nums[2].\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,0], k = 2\nOutput: -1\nExplanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].\n\n\n
Example 3:
\n\n\nInput: nums = [0,0,0,1,0,1,1,0], k = 3\nOutput: 3\nExplanation: \nFlip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= k <= nums.length
An array is squareful if the sum of every pair of adjacent elements is a perfect square.
\n\nGiven an integer array nums, return the number of permutations of nums
that are squareful.
Two permutations perm1
and perm2
are different if there is some index i
such that perm1[i] != perm2[i]
.
\n
Example 1:
\n\n\nInput: nums = [1,17,8]\nOutput: 2\nExplanation: [1,8,17] and [17,8,1] are the valid permutations.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 12
0 <= nums[i] <= 109
In a town, there are n
people labeled from 1
to n
. There is a rumor that one of these people is secretly the town judge.
If the town judge exists, then:
\n\nYou are given an array trust
where trust[i] = [ai, bi]
representing that the person labeled ai
trusts the person labeled bi
. If a trust relationship does not exist in trust
array, then such a trust relationship does not exist.
Return the label of the town judge if the town judge exists and can be identified, or return -1
otherwise.
\n
Example 1:
\n\n\nInput: n = 2, trust = [[1,2]]\nOutput: 2\n\n\n
Example 2:
\n\n\nInput: n = 3, trust = [[1,3],[2,3]]\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: n = 3, trust = [[1,3],[2,3],[3,1]]\nOutput: -1\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
0 <= trust.length <= 104
trust[i].length == 2
trust
are unique.ai != bi
1 <= ai, bi <= n
A maximum tree is a tree where every node has a value greater than any other value in its subtree.
\n\nYou are given the root
of a maximum binary tree and an integer val
.
Just as in the previous problem, the given tree was constructed from a list a
(root = Construct(a)
) recursively with the following Construct(a)
routine:
a
is empty, return null
.a[i]
be the largest element of a
. Create a root
node with the value a[i]
.root
will be Construct([a[0], a[1], ..., a[i - 1]])
.root
will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])
.root
.Note that we were not given a
directly, only a root node root = Construct(a)
.
Suppose b
is a copy of a
with the value val
appended to it. It is guaranteed that b
has unique values.
Return Construct(b)
.
\n
Example 1:
\n\nInput: root = [4,1,3,null,null,2], val = 5\nOutput: [5,4,null,1,3,null,null,2]\nExplanation: a = [1,4,2,3], b = [1,4,2,3,5]\n\n\n
Example 2:
\n\nInput: root = [5,2,4,null,1], val = 3\nOutput: [5,2,4,null,1,null,3]\nExplanation: a = [2,1,5,4], b = [2,1,5,4,3]\n\n\n
Example 3:
\n\nInput: root = [5,2,3,null,1], val = 4\nOutput: [5,2,4,null,1,3]\nExplanation: a = [2,1,5,3], b = [2,1,5,3,4]\n\n\n
\n
Constraints:
\n\n[1, 100]
.1 <= Node.val <= 100
1 <= val <= 100
You are given an 8 x 8
matrix representing a chessboard. There is exactly one white rook represented by 'R'
, some number of white bishops 'B'
, and some number of black pawns 'p'
. Empty squares are represented by '.'
.
A rook can move any number of squares horizontally or vertically (up, down, left, right) until it reaches another piece or the edge of the board. A rook is attacking a pawn if it can move to the pawn's square in one move.
\n\nNote: A rook cannot move through other pieces, such as bishops or pawns. This means a rook cannot attack a pawn if there is another piece blocking the path.
\n\nReturn the number of pawns the white rook is attacking.
\n\n\n
Example 1:
\nInput: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
\n\nOutput: 3
\n\nExplanation:
\n\nIn this example, the rook is attacking all the pawns.
\nExample 2:
\nInput: board = [[".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
\n\nOutput: 0
\n\nExplanation:
\n\nThe bishops are blocking the rook from attacking any of the pawns.
\nExample 3:
\nInput: board = [[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
\n\nOutput: 3
\n\nExplanation:
\n\nThe rook is attacking the pawns at positions b5, d6, and f5.
\n\n
Constraints:
\n\nboard.length == 8
board[i].length == 8
board[i][j]
is either 'R'
, '.'
, 'B'
, or 'p'
board[i][j] == 'R'
There are n
piles of stones
arranged in a row. The ith
pile has stones[i]
stones.
A move consists of merging exactly k
consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k
piles.
Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1
.
\n
Example 1:
\n\n\nInput: stones = [3,2,4,1], k = 2\nOutput: 20\nExplanation: We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible.\n\n\n
Example 2:
\n\n\nInput: stones = [3,2,4,1], k = 3\nOutput: -1\nExplanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\n\n\n
Example 3:
\n\n\nInput: stones = [3,5,1,2,6], k = 3\nOutput: 25\nExplanation: We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible.\n\n\n
\n
Constraints:
\n\nn == stones.length
1 <= n <= 30
1 <= stones[i] <= 100
2 <= k <= 30
There is a 2D grid
of size n x n
where each cell of this grid has a lamp that is initially turned off.
You are given a 2D array of lamp positions lamps
, where lamps[i] = [rowi, coli]
indicates that the lamp at grid[rowi][coli]
is turned on. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.
\n\nYou are also given another 2D array queries
, where queries[j] = [rowj, colj]
. For the jth
query, determine whether grid[rowj][colj]
is illuminated or not. After answering the jth
query, turn off the lamp at grid[rowj][colj]
and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj]
.
Return an array of integers ans
, where ans[j]
should be 1
if the cell in the jth
query was illuminated, or 0
if the lamp was not.
\n
Example 1:
\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput: [1,0]\nExplanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n\n\n\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n
\n
Example 2:
\n\n\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput: [1,1]\n\n\n
Example 3:
\n\n\nInput: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput: [1,1,0]\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
0 <= lamps.length <= 20000
0 <= queries.length <= 20000
lamps[i].length == 2
0 <= rowi, coli < n
queries[j].length == 2
0 <= rowj, colj < n
Given a string array words
, return an array of all characters that show up in all strings within the words
(including duplicates). You may return the answer in any order.
\n
Example 1:
\nInput: words = [\"bella\",\"label\",\"roller\"]\nOutput: [\"e\",\"l\",\"l\"]\n
Example 2:
\nInput: words = [\"cool\",\"lock\",\"cook\"]\nOutput: [\"c\",\"o\"]\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.Given a string s
, determine if it is valid.
A string s
is valid if, starting with an empty string t = ""
, you can transform t
into s
after performing the following operation any number of times:
"abc"
into any position in t
. More formally, t
becomes tleft + "abc" + tright
, where t == tleft + tright
. Note that tleft
and tright
may be empty.Return true
if s
is a valid string, otherwise, return false
.
\n
Example 1:
\n\n\nInput: s = "aabcbc"\nOutput: true\nExplanation:\n"" -> "abc" -> "aabcbc"\nThus, "aabcbc" is valid.\n\n
Example 2:
\n\n\nInput: s = "abcabcababcc"\nOutput: true\nExplanation:\n"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"\nThus, "abcabcababcc" is valid.\n\n\n
Example 3:
\n\n\nInput: s = "abccba"\nOutput: false\nExplanation: It is impossible to get "abccba" using the operation.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2 * 104
s
consists of letters 'a'
, 'b'
, and 'c'
Given a binary array nums
and an integer k
, return the maximum number of consecutive 1
's in the array if you can flip at most k
0
's.
\n
Example 1:
\n\n\nInput: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput: 6\nExplanation: [1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\n
Example 2:
\n\n\nInput: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput: 10\nExplanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.0 <= k <= nums.length
Given an integer array nums
and an integer k
, modify the array in the following way:
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 in this way.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,2,3], k = 1\nOutput: 5\nExplanation: Choose index 1 and nums becomes [4,-2,3].\n\n\n
Example 2:
\n\n\nInput: nums = [3,-1,0,2], k = 3\nOutput: 6\nExplanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\n\n\n
Example 3:
\n\n\nInput: nums = [2,-3,-1,5,-4], k = 2\nOutput: 13\nExplanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
-100 <= nums[i] <= 100
1 <= k <= 104
The factorial of a positive integer n
is the product of all positive integers less than or equal to n
.
factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
.We make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*'
, divide '/'
, add '+'
, and subtract '-'
in this order.
clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
.However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
\n\nAdditionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11
.
Given an integer n
, return the clumsy factorial of n
.
\n
Example 1:
\n\n\nInput: n = 4\nOutput: 7\nExplanation: 7 = 4 * 3 / 2 + 1\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: 12\nExplanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
In a row of dominoes, tops[i]
and bottoms[i]
represent the top and bottom halves of the ith
domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the ith
domino, so that tops[i]
and bottoms[i]
swap values.
Return the minimum number of rotations so that all the values in tops
are the same, or all the values in bottoms
are the same.
If it cannot be done, return -1
.
\n
Example 1:
\n\nInput: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput: 2\nExplanation: \nThe first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\n\n\n
Example 2:
\n\n\nInput: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput: -1\nExplanation: \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n\n\n
\n
Constraints:
\n\n2 <= tops.length <= 2 * 104
bottoms.length == tops.length
1 <= tops[i], bottoms[i] <= 6
Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.
\n\nIt is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.
\n\nA binary search tree is a binary tree where for every node, any descendant of Node.left
has a value strictly less than Node.val
, and any descendant of Node.right
has a value strictly greater than Node.val
.
A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left
, then traverses Node.right
.
\n
Example 1:
\n\nInput: preorder = [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\n\n\n
Example 2:
\n\n\nInput: preorder = [1,3]\nOutput: [1,null,3]\n\n\n
\n
Constraints:
\n\n1 <= preorder.length <= 100
1 <= preorder[i] <= 1000
preorder
are unique.The complement of an integer is the integer you get when you flip all the 0
's to 1
's and all the 1
's to 0
's in its binary representation.
5
is "101"
in binary and its complement is "010"
which is the integer 2
.Given an integer n
, return its complement.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: 2\nExplanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.\n\n\n
Example 2:
\n\n\nInput: n = 7\nOutput: 0\nExplanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.\n\n\n
Example 3:
\n\n\nInput: n = 10\nOutput: 5\nExplanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.\n\n\n
\n
Constraints:
\n\n0 <= n < 109
\n
Note: This question is the same as 476: https://leetcode.com/problems/number-complement/
\n", - "likes": 2499, - "dislikes": 118, - "stats": "{\"totalAccepted\": \"282K\", \"totalSubmission\": \"464K\", \"totalAcceptedRaw\": 281952, \"totalSubmissionRaw\": 464018, \"acRate\": \"60.8%\"}", + "likes": 2531, + "dislikes": 121, + "stats": "{\"totalAccepted\": \"293.6K\", \"totalSubmission\": \"483.7K\", \"totalAcceptedRaw\": 293639, \"totalSubmissionRaw\": 483655, \"acRate\": \"60.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -38087,9 +38111,9 @@ "questionFrontendId": "1010", "title": "Pairs of Songs With Total Durations Divisible by 60", "content": "You are given a list of songs where the ith
song has a duration of time[i]
seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60
. Formally, we want the number of indices i
, j
such that i < j
with (time[i] + time[j]) % 60 == 0
.
\n
Example 1:
\n\n\nInput: time = [30,20,150,100,40]\nOutput: 3\nExplanation: Three pairs have a total duration divisible by 60:\n(time[0] = 30, time[2] = 150): total duration 180\n(time[1] = 20, time[3] = 100): total duration 120\n(time[1] = 20, time[4] = 40): total duration 60\n\n\n
Example 2:
\n\n\nInput: time = [60,60,60]\nOutput: 3\nExplanation: All three pairs have a total duration of 120, which is divisible by 60.\n\n\n
\n
Constraints:
\n\n1 <= time.length <= 6 * 104
1 <= time[i] <= 500
A conveyor belt has packages that must be shipped from one port to another within days
days.
The ith
package on the conveyor belt has a weight of weights[i]
. Each day, we load the ship with packages on the conveyor belt (in the order given by weights
). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days
days.
\n
Example 1:
\n\n\nInput: weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput: 15\nExplanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.\n\n\n
Example 2:
\n\n\nInput: weights = [3,2,2,4,1,4], days = 3\nOutput: 6\nExplanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4\n\n\n
Example 3:
\n\n\nInput: weights = [1,2,3,1,1], days = 4\nOutput: 3\nExplanation:\n1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1\n\n\n
\n
Constraints:
\n\n1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
Given an integer n
, return the number of positive integers in the range [1, n]
that have at least one repeated digit.
\n
Example 1:
\n\n\nInput: n = 20\nOutput: 1\nExplanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\n\n\n
Example 2:
\n\n\nInput: n = 100\nOutput: 10\nExplanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\n\n\n
Example 3:
\n\n\nInput: n = 1000\nOutput: 262\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
Given an array of integers arr
, return true
if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i + 1 < j
with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])
\n
Example 1:
\n\n\nInput: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput: true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n\n\n
Example 2:
\n\n\nInput: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput: true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n\n\n
\n
Constraints:
\n\n3 <= arr.length <= 5 * 104
-104 <= arr[i] <= 104
You are given an integer array values
where values[i] represents the value of the ith
sightseeing spot. Two sightseeing spots i
and j
have a distance j - i
between them.
The score of a pair (i < j
) of sightseeing spots is values[i] + values[j] + i - j
: the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.
\n\n\n
Example 1:
\n\n\nInput: values = [8,1,5,2,6]\nOutput: 11\nExplanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11\n\n\n
Example 2:
\n\n\nInput: values = [1,2]\nOutput: 2\n\n\n
\n
Constraints:
\n\n2 <= values.length <= 5 * 104
1 <= values[i] <= 1000
Given a positive integer k
, you need to find the length of the smallest positive integer n
such that n
is divisible by k
, and n
only contains the digit 1
.
Return the length of n
. If there is no such n
, return -1.
Note: n
may not fit in a 64-bit signed integer.
\n
Example 1:
\n\n\nInput: k = 1\nOutput: 1\nExplanation: The smallest answer is n = 1, which has length 1.\n\n\n
Example 2:
\n\n\nInput: k = 2\nOutput: -1\nExplanation: There is no such positive integer n divisible by 2.\n\n\n
Example 3:
\n\n\nInput: k = 3\nOutput: 3\nExplanation: The smallest answer is n = 111, which has length 3.\n\n\n
\n
Constraints:
\n\n1 <= k <= 105
Given a binary string s
and a positive integer n
, return true
if the binary representation of all the integers in the range [1, n]
are substrings of s
, or false
otherwise.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\nInput: s = \"0110\", n = 3\nOutput: true\n
Example 2:
\nInput: s = \"0110\", n = 4\nOutput: false\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either '0'
or '1'
.1 <= n <= 109
Given an integer n
, return a binary string representing its representation in base -2
.
Note that the returned string should not have leading zeros unless the string is "0"
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: "110"\nExplantion: (-2)2 + (-2)1 = 2\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: "111"\nExplantion: (-2)2 + (-2)1 + (-2)0 = 3\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: "100"\nExplantion: (-2)2 = 4\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
You are given a binary array nums
(0-indexed).
We define xi
as the number whose binary representation is the subarray nums[0..i]
(from most-significant-bit to least-significant-bit).
nums = [1,0,1]
, then x0 = 1
, x1 = 2
, and x2 = 5
.Return an array of booleans answer
where answer[i]
is true
if xi
is divisible by 5
.
\n
Example 1:
\n\n\nInput: nums = [0,1,1]\nOutput: [true,false,false]\nExplanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.\nOnly the first number is divisible by 5, so answer[0] is true.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1]\nOutput: [false,false,false]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.You are given the head
of a linked list with n
nodes.
For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.
\n\nReturn an integer array answer
where answer[i]
is the value of the next greater node of the ith
node (1-indexed). If the ith
node does not have a next greater node, set answer[i] = 0
.
\n
Example 1:
\n\nInput: head = [2,1,5]\nOutput: [5,5,0]\n\n\n
Example 2:
\n\nInput: head = [2,7,4,3,5]\nOutput: [7,0,5,5,0]\n\n\n
\n
Constraints:
\n\nn
.1 <= n <= 104
1 <= Node.val <= 109
You are given an m x n
binary matrix grid
, where 0
represents a sea cell and 1
represents a land cell.
A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid
.
Return the number of land cells in grid
for which we cannot walk off the boundary of the grid in any number of moves.
\n
Example 1:
\n\nInput: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\nOutput: 3\nExplanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.\n\n\n
Example 2:
\n\nInput: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\nOutput: 0\nExplanation: All 1s are either on the boundary or can reach the boundary.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 500
grid[i][j]
is either 0
or 1
.A valid parentheses string is either empty ""
, "(" + A + ")"
, or A + B
, where A
and B
are valid parentheses strings, and +
represents string concatenation.
""
, "()"
, "(())()"
, and "(()(()))"
are all valid parentheses strings.A valid parentheses string s
is primitive if it is nonempty, and there does not exist a way to split it into s = A + B
, with A
and B
nonempty valid parentheses strings.
Given a valid parentheses string s
, consider its primitive decomposition: s = P1 + P2 + ... + Pk
, where Pi
are primitive valid parentheses strings.
Return s
after removing the outermost parentheses of every primitive string in the primitive decomposition of s
.
\n
Example 1:
\n\n\nInput: s = "(()())(())"\nOutput: "()()()"\nExplanation: \nThe input string is "(()())(())", with primitive decomposition "(()())" + "(())".\nAfter removing outer parentheses of each part, this is "()()" + "()" = "()()()".\n\n\n
Example 2:
\n\n\nInput: s = "(()())(())(()(()))"\nOutput: "()()()()(())"\nExplanation: \nThe input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".\nAfter removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".\n\n\n
Example 3:
\n\n\nInput: s = "()()"\nOutput: ""\nExplanation: \nThe input string is "()()", with primitive decomposition "()" + "()".\nAfter removing outer parentheses of each part, this is "" + "" = "".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '('
or ')'
.s
is a valid parentheses string.You are given the root
of a binary tree where each node has a value 0
or 1
. Each root-to-leaf path represents a binary number starting with the most significant bit.
0 -> 1 -> 1 -> 0 -> 1
, then this could represent 01101
in binary, which is 13
.For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.
\n\nThe test cases are generated so that the answer fits in a 32-bits integer.
\n\n\n
Example 1:
\n\nInput: root = [1,0,1,0,1,0,1]\nOutput: 22\nExplanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22\n\n\n
Example 2:
\n\n\nInput: root = [0]\nOutput: 0\n\n\n
\n
Constraints:
\n\n[1, 1000]
.Node.val
is 0
or 1
.Given an array of strings queries
and a string pattern
, return a boolean array answer
where answer[i]
is true
if queries[i]
matches pattern
, and false
otherwise.
A query word queries[i]
matches pattern
if you can insert lowercase English letters into the pattern so that it equals the query. You may insert a character at any position in pattern or you may choose not to insert any characters at all.
\n
Example 1:
\n\n\nInput: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"\nOutput: [true,false,true,true,false]\nExplanation: "FooBar" can be generated like this "F" + "oo" + "B" + "ar".\n"FootBall" can be generated like this "F" + "oot" + "B" + "all".\n"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".\n\n\n
Example 2:
\n\n\nInput: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"\nOutput: [true,false,true,false,false]\nExplanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".\n"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".\n\n\n
Example 3:
\n\n\nInput: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"\nOutput: [false,true,false,false,false]\nExplanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".\n\n\n
\n
Constraints:
\n\n1 <= pattern.length, queries.length <= 100
1 <= queries[i].length <= 100
queries[i]
and pattern
consist of English letters.You are given a series of video clips from a sporting event that lasted time
seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array clips
where clips[i] = [starti, endi]
indicates that the ith clip started at starti
and ended at endi
.
We can cut these clips into segments freely.
\n\n[0, 7]
can be cut into segments [0, 1] + [1, 3] + [3, 7]
.Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]
. If the task is impossible, return -1
.
\n
Example 1:
\n\n\nInput: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput: 3\nExplanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\n\n\n
Example 2:
\n\n\nInput: clips = [[0,1],[1,2]], time = 5\nOutput: -1\nExplanation: We cannot cover [0,5] with only [0,1] and [1,2].\n\n\n
Example 3:
\n\n\nInput: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput: 3\nExplanation: We can take clips [0,4], [4,7], and [6,9].\n\n\n
\n
Constraints:
\n\n1 <= clips.length <= 100
0 <= starti <= endi <= 100
1 <= time <= 100
Alice and Bob take turns playing a game, with Alice starting first.
\n\nInitially, there is a number n
on the chalkboard. On each player's turn, that player makes a move consisting of:
x
with 0 < x < n
and n % x == 0
.n
on the chalkboard with n - x
.Also, if a player cannot make a move, they lose the game.
\n\nReturn true
if and only if Alice wins the game, assuming both players play optimally.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: true\nExplanation: Alice chooses 1, and Bob has no more moves.\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: false\nExplanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
Given the root
of a binary tree, find the maximum value v
for which there exist different nodes a
and b
where v = |a.val - b.val|
and a
is an ancestor of b
.
A node a
is an ancestor of b
if either: any child of a
is equal to b
or any child of a
is an ancestor of b
.
\n
Example 1:
\n\nInput: root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput: 7\nExplanation: We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\n\n
Example 2:
\n\nInput: root = [1,null,2,null,0,3]\nOutput: 3\n\n\n
\n
Constraints:
\n\n[2, 5000]
.0 <= Node.val <= 105
Given an array nums
of integers, return the length of the longest arithmetic subsequence in nums
.
Note that:
\n\nseq
is arithmetic if seq[i + 1] - seq[i]
are all the same value (for 0 <= i < seq.length - 1
).\n
Example 1:
\n\n\nInput: nums = [3,6,9,12]\nOutput: 4\nExplanation: The whole array is an arithmetic sequence with steps of length = 3.\n\n\n
Example 2:
\n\n\nInput: nums = [9,4,7,2,10]\nOutput: 3\nExplanation: The longest arithmetic subsequence is [4,7,10].\n\n\n
Example 3:
\n\n\nInput: nums = [20,1,15,3,10,5,8]\nOutput: 4\nExplanation: The longest arithmetic subsequence is [20,15,10,5].\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 1000
0 <= nums[i] <= 500
We run a preorder depth-first search (DFS) on the root
of a binary tree.
At each node in this traversal, we output D
dashes (where D
is the depth of this node), then we output the value of this node. If the depth of a node is D
, the depth of its immediate child is D + 1
. The depth of the root
node is 0
.
If a node has only one child, that child is guaranteed to be the left child.
\n\nGiven the output traversal
of this traversal, recover the tree and return its root
.
\n
Example 1:
\n\nInput: traversal = "1-2--3--4-5--6--7"\nOutput: [1,2,5,3,4,6,7]\n\n\n
Example 2:
\n\nInput: traversal = "1-2--3---4-5--6---7"\nOutput: [1,2,5,3,null,6,null,4,null,7]\n\n\n
Example 3:
\n\nInput: traversal = "1-401--349---90--88"\nOutput: [1,401,null,349,88,90]\n\n\n
\n
Constraints:
\n\n[1, 1000]
.1 <= Node.val <= 109
A company is planning to interview 2n
people. Given the array costs
where costs[i] = [aCosti, bCosti]
, the cost of flying the ith
person to city a
is aCosti
, and the cost of flying the ith
person to city b
is bCosti
.
Return the minimum cost to fly every person to a city such that exactly n
people arrive in each city.
\n
Example 1:
\n\n\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n\n\n
Example 2:
\n\n\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\n\n\n
Example 3:
\n\n\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n\n\n
\n
Constraints:
\n\n2 * n == costs.length
2 <= costs.length <= 100
costs.length
is even.1 <= aCosti, bCosti <= 1000
You are given four integers row
, cols
, rCenter
, and cCenter
. There is a rows x cols
matrix and you are on the cell with the coordinates (rCenter, cCenter)
.
Return the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter)
from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.
The distance between two cells (r1, c1)
and (r2, c2)
is |r1 - r2| + |c1 - c2|
.
\n
Example 1:
\n\n\nInput: rows = 1, cols = 2, rCenter = 0, cCenter = 0\nOutput: [[0,0],[0,1]]\nExplanation: The distances from (0, 0) to other cells are: [0,1]\n\n\n
Example 2:
\n\n\nInput: rows = 2, cols = 2, rCenter = 0, cCenter = 1\nOutput: [[0,1],[0,0],[1,1],[1,0]]\nExplanation: The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\n\n\n
Example 3:
\n\n\nInput: rows = 2, cols = 3, rCenter = 1, cCenter = 2\nOutput: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\nExplanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].\n\n\n
\n
Constraints:
\n\n1 <= rows, cols <= 100
0 <= rCenter < rows
0 <= cCenter < cols
Given an integer array nums
and two integers firstLen
and secondLen
, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen
and secondLen
.
The array with length firstLen
could occur before or after the array with length secondLen
, but they have to be non-overlapping.
A subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput: 20\nExplanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\n\n\n
Example 2:
\n\n\nInput: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput: 29\nExplanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\n\n\n
Example 3:
\n\n\nInput: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput: 31\nExplanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n\n\n
\n
Constraints:
\n\n1 <= firstLen, secondLen <= 1000
2 <= firstLen + secondLen <= 1000
firstLen + secondLen <= nums.length <= 1000
0 <= nums[i] <= 1000
Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words
.
For example, if words = ["abc", "xyz"]
and the stream added the four characters (one by one) 'a'
, 'x'
, 'y'
, and 'z'
, your algorithm should detect that the suffix "xyz"
of the characters "axyz"
matches "xyz"
from words
.
Implement the StreamChecker
class:
StreamChecker(String[] words)
Initializes the object with the strings array words
.boolean query(char letter)
Accepts a new character from the stream and returns true
if any non-empty suffix from the stream forms a word that is in words
.\n
Example 1:
\n\n\nInput\n["StreamChecker", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query", "query"]\n[[["cd", "f", "kl"]], ["a"], ["b"], ["c"], ["d"], ["e"], ["f"], ["g"], ["h"], ["i"], ["j"], ["k"], ["l"]]\nOutput\n[null, false, false, false, true, false, true, false, false, false, false, false, true]\n\nExplanation\nStreamChecker streamChecker = new StreamChecker(["cd", "f", "kl"]);\nstreamChecker.query("a"); // return False\nstreamChecker.query("b"); // return False\nstreamChecker.query("c"); // return False\nstreamChecker.query("d"); // return True, because 'cd' is in the wordlist\nstreamChecker.query("e"); // return False\nstreamChecker.query("f"); // return True, because 'f' is in the wordlist\nstreamChecker.query("g"); // return False\nstreamChecker.query("h"); // return False\nstreamChecker.query("i"); // return False\nstreamChecker.query("j"); // return False\nstreamChecker.query("k"); // return False\nstreamChecker.query("l"); // return True, because 'kl' is in the wordlist\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 2000
1 <= words[i].length <= 200
words[i]
consists of lowercase English letters.letter
is a lowercase English letter.4 * 104
calls will be made to query.There are three stones in different positions on the X-axis. You are given three integers a
, b
, and c
, the positions of the stones.
In one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x
, y
, and z
with x < y < z
. You pick up the stone at either position x
or position z
, and move that stone to an integer position k
, with x < k < z
and k != y
.
The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).
\n\nReturn an integer array answer
of length 2
where:
answer[0]
is the minimum number of moves you can play, andanswer[1]
is the maximum number of moves you can play.\n
Example 1:
\n\n\nInput: a = 1, b = 2, c = 5\nOutput: [1,2]\nExplanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.\n\n\n
Example 2:
\n\n\nInput: a = 4, b = 3, c = 2\nOutput: [0,0]\nExplanation: We cannot make any moves.\n\n\n
Example 3:
\n\n\nInput: a = 3, b = 5, c = 1\nOutput: [1,2]\nExplanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.\n\n\n
\n
Constraints:
\n\n1 <= a, b, c <= 100
a
, b
, and c
have different values.You are given an m x n
integer matrix grid
, and three integers row
, col
, and color
. Each value in the grid represents the color of the grid square at that location.
Two squares are called adjacent if they are next to each other in any of the 4 directions.
\n\nTwo squares belong to the same connected component if they have the same color and they are adjacent.
\n\nThe border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).
\n\nYou should color the border of the connected component that contains the square grid[row][col]
with color
.
Return the final grid.
\n\n\n
Example 1:
\nInput: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput: [[3,3],[3,2]]\n
Example 2:
\nInput: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput: [[1,3,3],[2,3,3]]\n
Example 3:
\nInput: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput: [[2,2,2],[2,1,2],[2,2,2]]\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j], color <= 1000
0 <= row < m
0 <= col < n
You are given two integer arrays nums1
and nums2
. We write the integers of nums1
and nums2
(in the order they are given) on two separate horizontal lines.
We may draw connecting lines: a straight line connecting two numbers nums1[i]
and nums2[j]
such that:
nums1[i] == nums2[j]
, andNote that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).
\n\nReturn the maximum number of connecting lines we can draw in this way.
\n\n\n
Example 1:
\n\nInput: nums1 = [1,4,2], nums2 = [1,2,4]\nOutput: 2\nExplanation: We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 500
1 <= nums1[i], nums2[j] <= 2000
There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y)
.
We start at the source = [sx, sy]
square and want to reach the target = [tx, ty]
square. There is also an array of blocked
squares, where each blocked[i] = [xi, yi]
represents a blocked square with coordinates (xi, yi)
.
Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked
squares. We are also not allowed to walk outside of the grid.
Return true
if and only if it is possible to reach the target
square from the source
square through a sequence of valid moves.
\n
Example 1:
\n\n\nInput: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\nOutput: false\nExplanation: The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.\n\n\n
Example 2:
\n\n\nInput: blocked = [], source = [0,0], target = [999999,999999]\nOutput: true\nExplanation: Because there are no blocked cells, it is possible to reach the target square.\n\n\n
\n
Constraints:
\n\n0 <= blocked.length <= 200
blocked[i].length == 2
0 <= xi, yi < 106
source.length == target.length == 2
0 <= sx, sy, tx, ty < 106
source != target
source
and target
are not blocked.Given an array points
where points[i] = [xi, yi]
represents a point on the X-Y plane, return true
if these points are a boomerang.
A boomerang is a set of three points that are all distinct and not in a straight line.
\n\n\n
Example 1:
\nInput: points = [[1,1],[2,3],[3,2]]\nOutput: true\n
Example 2:
\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: false\n\n
\n
Constraints:
\n\npoints.length == 3
points[i].length == 2
0 <= xi, yi <= 100
Given the root
of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
\n\n\n
Example 1:
\n\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n\n\n
Example 2:
\n\n\nInput: root = [0,null,1]\nOutput: [1,null,1]\n\n\n
\n
Constraints:
\n\n[1, 100]
.0 <= Node.val <= 100
\n
Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/
\n", - "likes": 4386, - "dislikes": 167, - "stats": "{\"totalAccepted\": \"305.2K\", \"totalSubmission\": \"345.6K\", \"totalAcceptedRaw\": 305187, \"totalSubmissionRaw\": 345564, \"acRate\": \"88.3%\"}", + "likes": 4436, + "dislikes": 169, + "stats": "{\"totalAccepted\": \"315.9K\", \"totalSubmission\": \"357.9K\", \"totalAcceptedRaw\": 315942, \"totalSubmissionRaw\": 357934, \"acRate\": \"88.3%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -39178,9 +39214,9 @@ "questionFrontendId": "1039", "title": "Minimum Score Triangulation of Polygon", "content": "You have a convex n
-sided polygon where each vertex has an integer value. You are given an integer array values
where values[i]
is the value of the ith
vertex in clockwise order.
Polygon triangulation is a process where you divide a polygon into a set of triangles and the vertices of each triangle must also be vertices of the original polygon. Note that no other shapes other than triangles are allowed in the division. This process will result in n - 2
triangles.
You will triangulate the polygon. For each triangle, the weight of that triangle is the product of the values at its vertices. The total score of the triangulation is the sum of these weights over all n - 2
triangles.
Return the minimum possible score that you can achieve with some triangulation of the polygon.
\n\n\n\n
Example 1:
\n\nInput: values = [1,2,3]
\n\nOutput: 6
\n\nExplanation: The polygon is already triangulated, and the score of the only triangle is 6.
\nExample 2:
\n\nInput: values = [3,7,4,5]
\n\nOutput: 144
\n\nExplanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.
\nThe minimum score is 144.
Example 3:
\n\nInput: values = [1,3,1,4,1,5]
\n\nOutput: 13
\n\nExplanation: The minimum score triangulation is 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
\n\n
Constraints:
\n\nn == values.length
3 <= n <= 50
1 <= values[i] <= 100
There are some stones in different positions on the X-axis. You are given an integer array stones
, the positions of the stones.
Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.
\n\nstones = [1,2,5]
, you cannot move the endpoint stone at position 5
, since moving it to any position (such as 0
, or 3
) will still keep that stone as an endpoint stone.The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).
\n\nReturn an integer array answer
of length 2
where:
answer[0]
is the minimum number of moves you can play, andanswer[1]
is the maximum number of moves you can play.\n
Example 1:
\n\n\nInput: stones = [7,4,9]\nOutput: [1,2]\nExplanation: We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.\n\n\n
Example 2:
\n\n\nInput: stones = [6,5,4,3,10]\nOutput: [2,3]\nExplanation: We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.\n\n\n
\n
Constraints:
\n\n3 <= stones.length <= 104
1 <= stones[i] <= 109
stones
are unique.On an infinite plane, a robot initially stands at (0, 0)
and faces north. Note that:
The robot can receive one of three instructions:
\n\n"G"
: go straight 1 unit."L"
: turn 90 degrees to the left (i.e., anti-clockwise direction)."R"
: turn 90 degrees to the right (i.e., clockwise direction).The robot performs the instructions
given in order, and repeats them forever.
Return true
if and only if there exists a circle in the plane such that the robot never leaves the circle.
\n
Example 1:
\n\n\nInput: instructions = "GGLLGG"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n"G": move one step. Position: (0, 1). Direction: North.\n"G": move one step. Position: (0, 2). Direction: North.\n"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n"L": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n"G": move one step. Position: (0, 1). Direction: South.\n"G": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.\n\n\n
Example 2:
\n\n\nInput: instructions = "GG"\nOutput: false\nExplanation: The robot is initially at (0, 0) facing the north direction.\n"G": move one step. Position: (0, 1). Direction: North.\n"G": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.\n\n\n
Example 3:
\n\n\nInput: instructions = "GL"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n"G": move one step. Position: (0, 1). Direction: North.\n"L": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n"G": move one step. Position: (-1, 1). Direction: West.\n"L": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n"G": move one step. Position: (-1, 0). Direction: South.\n"L": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n"G": move one step. Position: (0, 0). Direction: East.\n"L": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.\n\n\n
\n
Constraints:
\n\n1 <= instructions.length <= 100
instructions[i]
is 'G'
, 'L'
or, 'R'
.You have n
gardens, labeled from 1
to n
, and an array paths
where paths[i] = [xi, yi]
describes a bidirectional path between garden xi
to garden yi
. In each garden, you want to plant one of 4 types of flowers.
All gardens have at most 3 paths coming into or leaving it.
\n\nYour task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.
\n\nReturn any such a choice as an array answer
, where answer[i]
is the type of flower planted in the (i+1)th
garden. The flower types are denoted 1
, 2
, 3
, or 4
. It is guaranteed an answer exists.
\n
Example 1:
\n\n\nInput: n = 3, paths = [[1,2],[2,3],[3,1]]\nOutput: [1,2,3]\nExplanation:\nGardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].\n\n\n
Example 2:
\n\n\nInput: n = 4, paths = [[1,2],[3,4]]\nOutput: [1,2,1,2]\n\n\n
Example 3:
\n\n\nInput: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\nOutput: [1,2,3,4]\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
0 <= paths.length <= 2 * 104
paths[i].length == 2
1 <= xi, yi <= n
xi != yi
Given an integer array arr
, partition the array into (contiguous) subarrays of length at most k
. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\n\n\n
Example 2:
\n\n\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\n\n\n
Example 3:
\n\n\nInput: arr = [1], k = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 500
0 <= arr[i] <= 109
1 <= k <= arr.length
Given a string s
, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s
does not have a duplicated substring, the answer is ""
.
\n
Example 1:
\nInput: s = \"banana\"\nOutput: \"ana\"\n
Example 2:
\nInput: s = \"abcd\"\nOutput: \"\"\n\n
\n
Constraints:
\n\n2 <= s.length <= 3 * 104
s
consists of lowercase English letters.Table: Customer
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| customer_id | int |\n| product_key | int |\n+-------------+---------+\nThis table may contain duplicates rows. \n\n\ncustomer_id
is not NULL.
\nproduct_key is a foreign key (reference column) toProduct
table.\n
\n\n
Table: Product
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| product_key | int |\n+-------------+---------+\nproduct_key is the primary key (column with unique values) for this table.\n\n\n
\n\n
Write a solution to report the customer ids from the Customer
table that bought all the products in the Product
table.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCustomer table:\n+-------------+-------------+\n| customer_id | product_key |\n+-------------+-------------+\n| 1 | 5 |\n| 2 | 6 |\n| 3 | 5 |\n| 3 | 6 |\n| 1 | 6 |\n+-------------+-------------+\nProduct table:\n+-------------+\n| product_key |\n+-------------+\n| 5 |\n| 6 |\n+-------------+\nOutput: \n+-------------+\n| customer_id |\n+-------------+\n| 1 |\n| 3 |\n+-------------+\nExplanation: \nThe customers who bought all the products (5 and 6) are customers with IDs 1 and 3.\n\n", - "likes": 853, - "dislikes": 78, - "stats": "{\"totalAccepted\": \"284.3K\", \"totalSubmission\": \"453.1K\", \"totalAcceptedRaw\": 284323, \"totalSubmissionRaw\": 453081, \"acRate\": \"62.8%\"}", + "likes": 922, + "dislikes": 84, + "stats": "{\"totalAccepted\": \"340.9K\", \"totalSubmission\": \"540.3K\", \"totalAcceptedRaw\": 340931, \"totalSubmissionRaw\": 540297, \"acRate\": \"63.1%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -39443,9 +39479,9 @@ "questionFrontendId": "1046", "title": "Last Stone Weight", "content": "
You are given an array of integers stones
where stones[i]
is the weight of the ith
stone.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x
and y
with x <= y
. The result of this smash is:
x == y
, both stones are destroyed, andx != y
, the stone of weight x
is destroyed, and the stone of weight y
has new weight y - x
.At the end of the game, there is at most one stone left.
\n\nReturn the weight of the last remaining stone. If there are no stones left, return 0
.
\n
Example 1:
\n\n\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\n\n\n
Example 2:
\n\n\nInput: stones = [1]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= stones.length <= 30
1 <= stones[i] <= 1000
You are given a string s
consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
\n\n\n
Example 1:
\n\n\nInput: s = "abbaca"\nOutput: "ca"\nExplanation: \nFor example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".\n\n\n
Example 2:
\n\n\nInput: s = "azxxzy"\nOutput: "ay"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.You are given an array of words
where each word consists of lowercase English letters.
wordA
is a predecessor of wordB
if and only if we can insert exactly one letter anywhere in wordA
without changing the order of the other characters to make it equal to wordB
.
"abc"
is a predecessor of "abac"
, while "cba"
is not a predecessor of "bcad"
.A word chain is a sequence of words [word1, word2, ..., wordk]
with k >= 1
, where word1
is a predecessor of word2
, word2
is a predecessor of word3
, and so on. A single word is trivially a word chain with k == 1
.
Return the length of the longest possible word chain with words chosen from the given list of words
.
\n
Example 1:
\n\n\nInput: words = ["a","b","ba","bca","bda","bdca"]\nOutput: 4\nExplanation: One of the longest word chains is ["a","ba","bda","bdca"].\n\n\n
Example 2:
\n\n\nInput: words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]\nOutput: 5\nExplanation: All the words can be put in a word chain ["xb", "xbc", "cxbc", "pcxbc", "pcxbcf"].\n\n\n
Example 3:
\n\n\nInput: words = ["abcd","dbqca"]\nOutput: 1\nExplanation: The trivial word chain ["abcd"] is one of the longest word chains.\n["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 16
words[i]
only consists of lowercase English letters.You are given an array of integers stones
where stones[i]
is the weight of the ith
stone.
We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x
and y
with x <= y
. The result of this smash is:
x == y
, both stones are destroyed, andx != y
, the stone of weight x
is destroyed, and the stone of weight y
has new weight y - x
.At the end of the game, there is at most one stone left.
\n\nReturn the smallest possible weight of the left stone. If there are no stones left, return 0
.
\n
Example 1:
\n\n\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation:\nWe can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\nwe can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\nwe can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\nwe can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.\n\n\n
Example 2:
\n\n\nInput: stones = [31,26,33,21,40]\nOutput: 5\n\n\n
\n
Constraints:
\n\n1 <= stones.length <= 30
1 <= stones[i] <= 100
Table: ActorDirector
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| actor_id | int |\n| director_id | int |\n| timestamp | int |\n+-------------+---------+\ntimestamp is the primary key (column with unique values) for this table.\n\n\n
\n\n
Write a solution to find all the pairs (actor_id, director_id)
where the actor has cooperated with the director at least three times.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActorDirector table:\n+-------------+-------------+-------------+\n| actor_id | director_id | timestamp |\n+-------------+-------------+-------------+\n| 1 | 1 | 0 |\n| 1 | 1 | 1 |\n| 1 | 1 | 2 |\n| 1 | 2 | 3 |\n| 1 | 2 | 4 |\n| 2 | 1 | 5 |\n| 2 | 1 | 6 |\n+-------------+-------------+-------------+\nOutput: \n+-------------+-------------+\n| actor_id | director_id |\n+-------------+-------------+\n| 1 | 1 |\n+-------------+-------------+\nExplanation: The only pair is (1, 1) where they cooperated exactly 3 times.\n\n", - "likes": 695, + "likes": 721, "dislikes": 52, - "stats": "{\"totalAccepted\": \"218K\", \"totalSubmission\": \"309.5K\", \"totalAcceptedRaw\": 217995, \"totalSubmissionRaw\": 309491, \"acRate\": \"70.4%\"}", + "stats": "{\"totalAccepted\": \"241.3K\", \"totalSubmission\": \"341.4K\", \"totalAcceptedRaw\": 241280, \"totalSubmissionRaw\": 341391, \"acRate\": \"70.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -39629,9 +39665,9 @@ "questionFrontendId": "1051", "title": "Height Checker", "content": "
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected
where expected[i]
is the expected height of the ith
student in line.
You are given an integer array heights
representing the current order that the students are standing in. Each heights[i]
is the height of the ith
student in line (0-indexed).
Return the number of indices where heights[i] != expected[i]
.
\n
Example 1:
\n\n\nInput: heights = [1,1,4,2,1,3]\nOutput: 3\nExplanation: \nheights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.\n\n\n
Example 2:
\n\n\nInput: heights = [5,1,2,3,4]\nOutput: 5\nExplanation:\nheights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.\n\n\n
Example 3:
\n\n\nInput: heights = [1,2,3,4,5]\nOutput: 0\nExplanation:\nheights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.\n\n\n
\n
Constraints:
\n\n1 <= heights.length <= 100
1 <= heights[i] <= 100
There is a bookstore owner that has a store open for n
minutes. You are given an integer array customers
of length n
where customers[i]
is the number of the customers that enter the store at the start of the ith
minute and all those customers leave after the end of that minute.
During certain minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i]
is 1
if the bookstore owner is grumpy during the ith
minute, and is 0
otherwise.
When the bookstore owner is grumpy, the customers entering during that minute are not satisfied. Otherwise, they are satisfied.
\n\nThe bookstore owner knows a secret technique to remain not grumpy for minutes
consecutive minutes, but this technique can only be used once.
Return the maximum number of customers that can be satisfied throughout the day.
\n\n\n
Example 1:
\n\nInput: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3
\n\nOutput: 16
\n\nExplanation:
\n\nThe bookstore owner keeps themselves not grumpy for the last 3 minutes.
\n\nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.
\nExample 2:
\n\nInput: customers = [1], grumpy = [0], minutes = 1
\n\nOutput: 1
\n\n
Constraints:
\n\nn == customers.length == grumpy.length
1 <= minutes <= n <= 2 * 104
0 <= customers[i] <= 1000
grumpy[i]
is either 0
or 1
.Given an array of positive integers arr
(not necessarily distinct), return the lexicographically largest permutation that is smaller than arr
, that can be made with exactly one swap. If it cannot be done, then return the same array.
Note that a swap exchanges the positions of two numbers arr[i]
and arr[j]
\n
Example 1:
\n\n\nInput: arr = [3,2,1]\nOutput: [3,1,2]\nExplanation: Swapping 2 and 1.\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,5]\nOutput: [1,1,5]\nExplanation: This is already the smallest permutation.\n\n\n
Example 3:
\n\n\nInput: arr = [1,9,4,6,7]\nOutput: [1,7,4,6,9]\nExplanation: Swapping 9 and 7.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
1 <= arr[i] <= 104
In a warehouse, there is a row of barcodes, where the ith
barcode is barcodes[i]
.
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
\n\n\n
Example 1:
\nInput: barcodes = [1,1,1,2,2,2]\nOutput: [2,1,2,1,2,1]\n
Example 2:
\nInput: barcodes = [1,1,1,1,2,2,3,3]\nOutput: [1,3,1,3,1,2,1,2]\n\n
\n
Constraints:
\n\n1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
You are given two strings of the same length s1
and s2
and a string baseStr
.
We say s1[i]
and s2[i]
are equivalent characters.
s1 = "abc"
and s2 = "cde"
, then we have 'a' == 'c'
, 'b' == 'd'
, and 'c' == 'e'
.Equivalent characters follow the usual rules of any equivalence relation:
\n\n'a' == 'a'
.'a' == 'b'
implies 'b' == 'a'
.'a' == 'b'
and 'b' == 'c'
implies 'a' == 'c'
.For example, given the equivalency information from s1 = "abc"
and s2 = "cde"
, "acd"
and "aab"
are equivalent strings of baseStr = "eed"
, and "aab"
is the lexicographically smallest equivalent string of baseStr
.
Return the lexicographically smallest equivalent string of baseStr
by using the equivalency information from s1
and s2
.
\n
Example 1:
\n\n\nInput: s1 = "parker", s2 = "morris", baseStr = "parser"\nOutput: "makkek"\nExplanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].\nThe characters in each group are equivalent and sorted in lexicographical order.\nSo the answer is "makkek".\n\n\n
Example 2:
\n\n\nInput: s1 = "hello", s2 = "world", baseStr = "hold"\nOutput: "hdld"\nExplanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].\nSo only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld".\n\n\n
Example 3:
\n\n\nInput: s1 = "leetcode", s2 = "programs", baseStr = "sourcecode"\nOutput: "aauaaaaada"\nExplanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada".\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length, baseStr <= 1000
s1.length == s2.length
s1
, s2
, and baseStr
consist of lowercase English letters.Table: Sales
\n+-------------+-------+\n| Column Name | Type |\n+-------------+-------+\n| sale_id | int |\n| product_id | int |\n| year | int |\n| quantity | int |\n| price | int |\n+-------------+-------+\n(sale_id, year) is the primary key (combination of columns with unique values) of this table.\nproduct_id is a foreign key (reference column) to Product
table.\nEach row of this table shows a sale on the product product_id in a certain year.\nNote that the price is per unit.\n
\n\n\n\n
Table: Product
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| product_id | int |\n| product_name | varchar |\n+--------------+---------+\nproduct_id is the primary key (column with unique values) of this table.\nEach row of this table indicates the product name of each product.\n\n\n
\n\n
Write a solution to report the product_name
, year
, and price
for each sale_id
in the Sales
table.
Return the resulting table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSales table:\n+---------+------------+------+----------+-------+\n| sale_id | product_id | year | quantity | price |\n+---------+------------+------+----------+-------+ \n| 1 | 100 | 2008 | 10 | 5000 |\n| 2 | 100 | 2009 | 12 | 5000 |\n| 7 | 200 | 2011 | 15 | 9000 |\n+---------+------------+------+----------+-------+\nProduct table:\n+------------+--------------+\n| product_id | product_name |\n+------------+--------------+\n| 100 | Nokia |\n| 200 | Apple |\n| 300 | Samsung |\n+------------+--------------+\nOutput: \n+--------------+-------+-------+\n| product_name | year | price |\n+--------------+-------+-------+\n| Nokia | 2008 | 5000 |\n| Nokia | 2009 | 5000 |\n| Apple | 2011 | 9000 |\n+--------------+-------+-------+\nExplanation: \nFrom sale_id = 1, we can conclude that Nokia was sold for 5000 in the year 2008.\nFrom sale_id = 2, we can conclude that Nokia was sold for 5000 in the year 2009.\nFrom sale_id = 7, we can conclude that Apple was sold for 9000 in the year 2011.\n\n", - "likes": 1098, - "dislikes": 231, - "stats": "{\"totalAccepted\": \"819.1K\", \"totalSubmission\": \"968.3K\", \"totalAcceptedRaw\": 819147, \"totalSubmissionRaw\": 968308, \"acRate\": \"84.6%\"}", + "likes": 1220, + "dislikes": 240, + "stats": "{\"totalAccepted\": \"984.4K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 984370, \"totalSubmissionRaw\": 1164078, \"acRate\": \"84.6%\"}", "similarQuestions": "[{\"title\": \"Product Sales Analysis II\", \"titleSlug\": \"product-sales-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis IV\", \"titleSlug\": \"product-sales-analysis-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis V\", \"titleSlug\": \"product-sales-analysis-v\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40334,9 +40370,9 @@ "questionFrontendId": "1069", "title": "Product Sales Analysis II", "content": null, - "likes": 83, + "likes": 84, "dislikes": 182, - "stats": "{\"totalAccepted\": \"57.3K\", \"totalSubmission\": \"69.8K\", \"totalAcceptedRaw\": 57292, \"totalSubmissionRaw\": 69768, \"acRate\": \"82.1%\"}", + "stats": "{\"totalAccepted\": \"59K\", \"totalSubmission\": \"71.8K\", \"totalAcceptedRaw\": 59050, \"totalSubmissionRaw\": 71756, \"acRate\": \"82.3%\"}", "similarQuestions": "[{\"title\": \"Product Sales Analysis I\", \"titleSlug\": \"product-sales-analysis-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis III\", \"titleSlug\": \"product-sales-analysis-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis IV\", \"titleSlug\": \"product-sales-analysis-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis V\", \"titleSlug\": \"product-sales-analysis-v\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40364,10 +40400,10 @@ "questionId": "1155", "questionFrontendId": "1070", "title": "Product Sales Analysis III", - "content": "
Table: Sales
\n+-------------+-------+\n| Column Name | Type |\n+-------------+-------+\n| sale_id | int |\n| product_id | int |\n| year | int |\n| quantity | int |\n| price | int |\n+-------------+-------+\n(sale_id, year) is the primary key (combination of columns with unique values) of this table.\nproduct_id is a foreign key (reference column) to Product
table.\nEach row of this table shows a sale on the product product_id in a certain year.\nNote that the price is per unit.\n
\n\n\n\n
Table: Product
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| product_id | int |\n| product_name | varchar |\n+--------------+---------+\nproduct_id is the primary key (column with unique values) of this table.\nEach row of this table indicates the product name of each product.\n\n\n
\n\n
Write a solution to select the product id, year, quantity, and price for the first year of every product sold.
\n\nReturn the resulting table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSales table:\n+---------+------------+------+----------+-------+\n| sale_id | product_id | year | quantity | price |\n+---------+------------+------+----------+-------+ \n| 1 | 100 | 2008 | 10 | 5000 |\n| 2 | 100 | 2009 | 12 | 5000 |\n| 7 | 200 | 2011 | 15 | 9000 |\n+---------+------------+------+----------+-------+\nProduct table:\n+------------+--------------+\n| product_id | product_name |\n+------------+--------------+\n| 100 | Nokia |\n| 200 | Apple |\n| 300 | Samsung |\n+------------+--------------+\nOutput: \n+------------+------------+----------+-------+\n| product_id | first_year | quantity | price |\n+------------+------------+----------+-------+ \n| 100 | 2008 | 10 | 5000 |\n| 200 | 2011 | 15 | 9000 |\n+------------+------------+----------+-------+\n\n", - "likes": 530, - "dislikes": 1018, - "stats": "{\"totalAccepted\": \"258.8K\", \"totalSubmission\": \"585.4K\", \"totalAcceptedRaw\": 258795, \"totalSubmissionRaw\": 585363, \"acRate\": \"44.2%\"}", + "content": "
Table: Sales
\n+-------------+-------+\n| Column Name | Type |\n+-------------+-------+\n| sale_id | int |\n| product_id | int |\n| year | int |\n| quantity | int |\n| price | int |\n+-------------+-------+\n(sale_id, year) is the primary key (combination of columns with unique values) of this table.\nproduct_id is a foreign key (reference column) to Product
table.\nEach row records a sale of a product in a given year.\nA product may have multiple sales entries in the same year.\nNote that the per-unit price.\n\n
\n\nWrite a solution to find all sales that occurred in the first year each product was sold.
\n\nFor each product_id
, identify the earliest year
it appears in the Sales
table.
Return all sales entries for that product in that year.
\n\tReturn a table with the following columns: product_id, first_year, quantity, and price.
\nReturn the result in any order.
\n
Example 1:
\n\n\nInput: \nSales table:\n+---------+------------+------+----------+-------+\n| sale_id | product_id | year | quantity | price |\n+---------+------------+------+----------+-------+ \n| 1 | 100 | 2008 | 10 | 5000 |\n| 2 | 100 | 2009 | 12 | 5000 |\n| 7 | 200 | 2011 | 15 | 9000 |\n+---------+------------+------+----------+-------+\n\nOutput: \n+------------+------------+----------+-------+\n| product_id | first_year | quantity | price |\n+------------+------------+----------+-------+ \n| 100 | 2008 | 10 | 5000 |\n| 200 | 2011 | 15 | 9000 |\n+------------+------------+----------+-------+\n\n", + "likes": 607, + "dislikes": 1065, + "stats": "{\"totalAccepted\": \"314.2K\", \"totalSubmission\": \"704.4K\", \"totalAcceptedRaw\": 314211, \"totalSubmissionRaw\": 704419, \"acRate\": \"44.6%\"}", "similarQuestions": "[{\"title\": \"Product Sales Analysis II\", \"titleSlug\": \"product-sales-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis IV\", \"titleSlug\": \"product-sales-analysis-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Product Sales Analysis V\", \"titleSlug\": \"product-sales-analysis-v\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40396,9 +40432,9 @@ "questionFrontendId": "1071", "title": "Greatest Common Divisor of Strings", "content": "
For two strings s
and t
, we say "t
divides s
" if and only if s = t + t + t + ... + t + t
(i.e., t
is concatenated with itself one or more times).
Given two strings str1
and str2
, return the largest string x
such that x
divides both str1
and str2
.
\n
Example 1:
\n\n\nInput: str1 = "ABCABC", str2 = "ABC"\nOutput: "ABC"\n\n\n
Example 2:
\n\n\nInput: str1 = "ABABAB", str2 = "ABAB"\nOutput: "AB"\n\n\n
Example 3:
\n\n\nInput: str1 = "LEET", str2 = "CODE"\nOutput: ""\n\n\n
\n
Constraints:
\n\n1 <= str1.length, str2.length <= 1000
str1
and str2
consist of English uppercase letters.You are given an m x n
binary matrix matrix
.
You can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0
to 1
or vice versa).
Return the maximum number of rows that have all values equal after some number of flips.
\n\n\n
Example 1:
\n\n\nInput: matrix = [[0,1],[1,1]]\nOutput: 1\nExplanation: After flipping no values, 1 row has all values equal.\n\n\n
Example 2:
\n\n\nInput: matrix = [[0,1],[1,0]]\nOutput: 2\nExplanation: After flipping values in the first column, both rows have equal values.\n\n\n
Example 3:
\n\n\nInput: matrix = [[0,0,0],[0,0,1],[1,1,0]]\nOutput: 2\nExplanation: After flipping values in the first two columns, the last two rows have equal values.\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j]
is either 0
or 1
.Given two numbers arr1
and arr2
in base -2, return the result of adding them together.
Each number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1]
represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3
. A number arr
in array, format is also guaranteed to have no leading zeros: either arr == [0]
or arr[0] == 1
.
Return the result of adding arr1
and arr2
in the same format: as an array of 0s and 1s with no leading zeros.
\n
Example 1:
\n\n\nInput: arr1 = [1,1,1,1,1], arr2 = [1,0,1]\nOutput: [1,0,0,0,0]\nExplanation: arr1 represents 11, arr2 represents 5, the output represents 16.\n\n\n
Example 2:
\n\n\nInput: arr1 = [0], arr2 = [0]\nOutput: [0]\n\n\n
Example 3:
\n\n\nInput: arr1 = [0], arr2 = [1]\nOutput: [1]\n\n\n
\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 1000
arr1[i]
and arr2[i]
are 0
or 1
arr1
and arr2
have no leading zerosGiven a matrix
and a target
, return the number of non-empty submatrices that sum to target.
A submatrix x1, y1, x2, y2
is the set of all cells matrix[x][y]
with x1 <= x <= x2
and y1 <= y <= y2
.
Two submatrices (x1, y1, x2, y2)
and (x1', y1', x2', y2')
are different if they have some coordinate that is different: for example, if x1 != x1'
.
\n
Example 1:
\n\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\n\n\n
Example 2:
\n\n\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n\n\n
Example 3:
\n\n\nInput: matrix = [[904]], target = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= matrix.length <= 100
1 <= matrix[0].length <= 100
-1000 <= matrix[i][j] <= 1000
-10^8 <= target <= 10^8
Table: Project
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| project_id | int |\n| employee_id | int |\n+-------------+---------+\n(project_id, employee_id) is the primary key of this table.\nemployee_id is a foreign key to Employee
table.\nEach row of this table indicates that the employee with employee_id is working on the project with project_id.\n
\n\n\n\n
Table: Employee
\n+------------------+---------+\n| Column Name | Type |\n+------------------+---------+\n| employee_id | int |\n| name | varchar |\n| experience_years | int |\n+------------------+---------+\nemployee_id is the primary key of this table. It's guaranteed that experience_years is not NULL.\nEach row of this table contains information about one employee.\n\n\n
\n\n
Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.
\n\nReturn the result table in any order.
\n\nThe query result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProject table:\n+-------------+-------------+\n| project_id | employee_id |\n+-------------+-------------+\n| 1 | 1 |\n| 1 | 2 |\n| 1 | 3 |\n| 2 | 1 |\n| 2 | 4 |\n+-------------+-------------+\nEmployee table:\n+-------------+--------+------------------+\n| employee_id | name | experience_years |\n+-------------+--------+------------------+\n| 1 | Khaled | 3 |\n| 2 | Ali | 2 |\n| 3 | John | 1 |\n| 4 | Doe | 2 |\n+-------------+--------+------------------+\nOutput: \n+-------------+---------------+\n| project_id | average_years |\n+-------------+---------------+\n| 1 | 2.00 |\n| 2 | 2.50 |\n+-------------+---------------+\nExplanation: The average experience years for the first project is (3 + 2 + 1) / 3 = 2.00 and for the second project is (3 + 2) / 2 = 2.50\n\n", - "likes": 744, - "dislikes": 184, - "stats": "{\"totalAccepted\": \"403.8K\", \"totalSubmission\": \"623.5K\", \"totalAcceptedRaw\": 403833, \"totalSubmissionRaw\": 623529, \"acRate\": \"64.8%\"}", + "likes": 823, + "dislikes": 193, + "stats": "{\"totalAccepted\": \"487.3K\", \"totalSubmission\": \"742.9K\", \"totalAcceptedRaw\": 487267, \"totalSubmissionRaw\": 742940, \"acRate\": \"65.6%\"}", "similarQuestions": "[{\"title\": \"Project Employees II\", \"titleSlug\": \"project-employees-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40579,7 +40615,7 @@ "content": null, "likes": 204, "dislikes": 63, - "stats": "{\"totalAccepted\": \"61.4K\", \"totalSubmission\": \"122.4K\", \"totalAcceptedRaw\": 61394, \"totalSubmissionRaw\": 122379, \"acRate\": \"50.2%\"}", + "stats": "{\"totalAccepted\": \"63.3K\", \"totalSubmission\": \"125.9K\", \"totalAcceptedRaw\": 63289, \"totalSubmissionRaw\": 125889, \"acRate\": \"50.3%\"}", "similarQuestions": "[{\"title\": \"Project Employees I\", \"titleSlug\": \"project-employees-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Project Employees III\", \"titleSlug\": \"project-employees-iii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40605,9 +40641,9 @@ "questionFrontendId": "1077", "title": "Project Employees III", "content": null, - "likes": 275, + "likes": 276, "dislikes": 9, - "stats": "{\"totalAccepted\": \"63.8K\", \"totalSubmission\": \"83K\", \"totalAcceptedRaw\": 63827, \"totalSubmissionRaw\": 83031, \"acRate\": \"76.9%\"}", + "stats": "{\"totalAccepted\": \"67.4K\", \"totalSubmission\": \"87.3K\", \"totalAcceptedRaw\": 67355, \"totalSubmissionRaw\": 87322, \"acRate\": \"77.1%\"}", "similarQuestions": "[{\"title\": \"Project Employees II\", \"titleSlug\": \"project-employees-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40636,9 +40672,9 @@ "questionFrontendId": "1078", "title": "Occurrences After Bigram", "content": "
Given two strings first
and second
, consider occurrences in some text of the form "first second third"
, where second
comes immediately after first
, and third
comes immediately after second
.
Return an array of all the words third
for each occurrence of "first second third"
.
\n
Example 1:
\nInput: text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\nOutput: [\"girl\",\"student\"]\n
Example 2:
\nInput: text = \"we will we will rock you\", first = \"we\", second = \"will\"\nOutput: [\"we\",\"rock\"]\n\n
\n
Constraints:
\n\n1 <= text.length <= 1000
text
consists of lowercase English letters and spaces.text
are separated by a single space.1 <= first.length, second.length <= 10
first
and second
consist of lowercase English letters.text
will not have any leading or trailing spaces.You have n
tiles
, where each tile has one letter tiles[i]
printed on it.
Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles
.
\n
Example 1:
\n\n\nInput: tiles = "AAB"\nOutput: 8\nExplanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".\n\n\n
Example 2:
\n\n\nInput: tiles = "AAABBC"\nOutput: 188\n\n\n
Example 3:
\n\n\nInput: tiles = "V"\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= tiles.length <= 7
tiles
consists of uppercase English letters.Given the root
of a binary tree and an integer limit
, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.
A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit
.
A leaf is a node with no children.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\n\n\n
Example 2:
\n\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\n\n\n
Example 3:
\n\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\nOutput: [1,null,-3,4]\n\n\n
\n
Constraints:
\n\n[1, 5000]
.-105 <= Node.val <= 105
-109 <= limit <= 109
Given a string s
, return the lexicographically smallest subsequence of s
that contains all the distinct characters of s
exactly once.
\n
Example 1:
\n\n\nInput: s = "bcabc"\nOutput: "abc"\n\n\n
Example 2:
\n\n\nInput: s = "cbacdcbc"\nOutput: "acdb"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of lowercase English letters.\nNote: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/", - "likes": 2646, - "dislikes": 198, - "stats": "{\"totalAccepted\": \"78K\", \"totalSubmission\": \"126.5K\", \"totalAcceptedRaw\": 77978, \"totalSubmissionRaw\": 126509, \"acRate\": \"61.6%\"}", + "likes": 2676, + "dislikes": 199, + "stats": "{\"totalAccepted\": \"82.4K\", \"totalSubmission\": \"133K\", \"totalAcceptedRaw\": 82394, \"totalSubmissionRaw\": 133023, \"acRate\": \"61.9%\"}", "similarQuestions": "[{\"title\": \"Find the Most Competitive Subsequence\", \"titleSlug\": \"find-the-most-competitive-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -40783,9 +40819,9 @@ "questionFrontendId": "1082", "title": "Sales Analysis I", "content": null, - "likes": 198, - "dislikes": 79, - "stats": "{\"totalAccepted\": \"62.8K\", \"totalSubmission\": \"84.1K\", \"totalAcceptedRaw\": 62758, \"totalSubmissionRaw\": 84059, \"acRate\": \"74.7%\"}", + "likes": 201, + "dislikes": 80, + "stats": "{\"totalAccepted\": \"64.6K\", \"totalSubmission\": \"86.4K\", \"totalAcceptedRaw\": 64571, \"totalSubmissionRaw\": 86391, \"acRate\": \"74.7%\"}", "similarQuestions": "[{\"title\": \"Sales Analysis II\", \"titleSlug\": \"sales-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40814,9 +40850,9 @@ "questionFrontendId": "1083", "title": "Sales Analysis II", "content": null, - "likes": 274, + "likes": 277, "dislikes": 47, - "stats": "{\"totalAccepted\": \"62K\", \"totalSubmission\": \"124.3K\", \"totalAcceptedRaw\": 61974, \"totalSubmissionRaw\": 124316, \"acRate\": \"49.9%\"}", + "stats": "{\"totalAccepted\": \"63.6K\", \"totalSubmission\": \"127.5K\", \"totalAcceptedRaw\": 63636, \"totalSubmissionRaw\": 127479, \"acRate\": \"49.9%\"}", "similarQuestions": "[{\"title\": \"Sales Analysis I\", \"titleSlug\": \"sales-analysis-i\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Sales Analysis III\", \"titleSlug\": \"sales-analysis-iii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40845,9 +40881,9 @@ "questionFrontendId": "1084", "title": "Sales Analysis III", "content": "
Table: Product
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| product_id | int |\n| product_name | varchar |\n| unit_price | int |\n+--------------+---------+\nproduct_id is the primary key (column with unique values) of this table.\nEach row of this table indicates the name and the price of each product.\n\n\n
Table: Sales
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| seller_id | int |\n| product_id | int |\n| buyer_id | int |\n| sale_date | date |\n| quantity | int |\n| price | int |\n+-------------+---------+\nThis table can have duplicate rows.\nproduct_id is a foreign key (reference column) to the Product table.\nEach row of this table contains some information about one sale.\n\n\n
\n\n
Write a solution to report the products that were only sold in the first quarter of 2019
. That is, between 2019-01-01
and 2019-03-31
inclusive.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProduct table:\n+------------+--------------+------------+\n| product_id | product_name | unit_price |\n+------------+--------------+------------+\n| 1 | S8 | 1000 |\n| 2 | G4 | 800 |\n| 3 | iPhone | 1400 |\n+------------+--------------+------------+\nSales table:\n+-----------+------------+----------+------------+----------+-------+\n| seller_id | product_id | buyer_id | sale_date | quantity | price |\n+-----------+------------+----------+------------+----------+-------+\n| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |\n| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |\n| 2 | 2 | 3 | 2019-06-02 | 1 | 800 |\n| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 |\n+-----------+------------+----------+------------+----------+-------+\nOutput: \n+-------------+--------------+\n| product_id | product_name |\n+-------------+--------------+\n| 1 | S8 |\n+-------------+--------------+\nExplanation: \nThe product with id 1 was only sold in the spring of 2019.\nThe product with id 2 was sold in the spring of 2019 but was also sold after the spring of 2019.\nThe product with id 3 was sold after spring 2019.\nWe return only product 1 as it is the product that was only sold in the spring of 2019.\n\n", - "likes": 753, - "dislikes": 157, - "stats": "{\"totalAccepted\": \"160K\", \"totalSubmission\": \"342.3K\", \"totalAcceptedRaw\": 160021, \"totalSubmissionRaw\": 342323, \"acRate\": \"46.7%\"}", + "likes": 782, + "dislikes": 162, + "stats": "{\"totalAccepted\": \"175.3K\", \"totalSubmission\": \"374.9K\", \"totalAcceptedRaw\": 175286, \"totalSubmissionRaw\": 374860, \"acRate\": \"46.8%\"}", "similarQuestions": "[{\"title\": \"Sales Analysis II\", \"titleSlug\": \"sales-analysis-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -40878,7 +40914,7 @@ "content": null, "likes": 120, "dislikes": 151, - "stats": "{\"totalAccepted\": \"25K\", \"totalSubmission\": \"32.7K\", \"totalAcceptedRaw\": 25034, \"totalSubmissionRaw\": 32691, \"acRate\": \"76.6%\"}", + "stats": "{\"totalAccepted\": \"25.4K\", \"totalSubmission\": \"33.1K\", \"totalAcceptedRaw\": 25388, \"totalSubmissionRaw\": 33139, \"acRate\": \"76.6%\"}", "similarQuestions": "[{\"title\": \"Add Digits\", \"titleSlug\": \"add-digits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -40912,9 +40948,9 @@ "questionFrontendId": "1086", "title": "High Five", "content": null, - "likes": 812, - "dislikes": 128, - "stats": "{\"totalAccepted\": \"112.1K\", \"totalSubmission\": \"150.6K\", \"totalAcceptedRaw\": 112072, \"totalSubmissionRaw\": 150608, \"acRate\": \"74.4%\"}", + "likes": 820, + "dislikes": 130, + "stats": "{\"totalAccepted\": \"117.1K\", \"totalSubmission\": \"157.5K\", \"totalAcceptedRaw\": 117098, \"totalSubmissionRaw\": 157500, \"acRate\": \"74.3%\"}", "similarQuestions": "[{\"title\": \"Determine the Winner of a Bowling Game\", \"titleSlug\": \"determine-the-winner-of-a-bowling-game\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -40956,9 +40992,9 @@ "questionFrontendId": "1087", "title": "Brace Expansion", "content": null, - "likes": 648, - "dislikes": 55, - "stats": "{\"totalAccepted\": \"56.4K\", \"totalSubmission\": \"84.7K\", \"totalAcceptedRaw\": 56416, \"totalSubmissionRaw\": 84681, \"acRate\": \"66.6%\"}", + "likes": 652, + "dislikes": 57, + "stats": "{\"totalAccepted\": \"59.3K\", \"totalSubmission\": \"88.8K\", \"totalAcceptedRaw\": 59271, \"totalSubmissionRaw\": 88840, \"acRate\": \"66.7%\"}", "similarQuestions": "[{\"title\": \"Decode String\", \"titleSlug\": \"decode-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Letter Case Permutation\", \"titleSlug\": \"letter-case-permutation\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Brace Expansion II\", \"titleSlug\": \"brace-expansion-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -40998,7 +41034,7 @@ "content": null, "likes": 494, "dislikes": 144, - "stats": "{\"totalAccepted\": \"38.1K\", \"totalSubmission\": \"80.8K\", \"totalAcceptedRaw\": 38054, \"totalSubmissionRaw\": 80850, \"acRate\": \"47.1%\"}", + "stats": "{\"totalAccepted\": \"38.5K\", \"totalSubmission\": \"81.8K\", \"totalAcceptedRaw\": 38519, \"totalSubmissionRaw\": 81818, \"acRate\": \"47.1%\"}", "similarQuestions": "[{\"title\": \"Confusing Number\", \"titleSlug\": \"confusing-number\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -41030,9 +41066,9 @@ "questionFrontendId": "1089", "title": "Duplicate Zeros", "content": "
Given a fixed-length integer array arr
, duplicate each occurrence of zero, shifting the remaining elements to the right.
Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,0,2,3,0,4,5,0]\nOutput: [1,0,0,2,3,0,0,4]\nExplanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,3]\nOutput: [1,2,3]\nExplanation: After calling your function, the input array is modified to: [1,2,3]\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
0 <= arr[i] <= 9
You are given n
item's value and label as two integer arrays values
and labels
. You are also given two integers numWanted
and useLimit
.
Your task is to find a subset of items with the maximum sum of their values such that:
\n\nnumWanted
.useLimit
.Return the maximum sum.
\n\n\n
Example 1:
\n\nInput: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1
\n\nOutput: 9
\n\nExplanation:
\n\nThe subset chosen is the first, third, and fifth items with the sum of values 5 + 3 + 1.
\nExample 2:
\n\nInput: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2
\n\nOutput: 12
\n\nExplanation:
\n\nThe subset chosen is the first, second, and third items with the sum of values 5 + 4 + 3.
\nExample 3:
\n\nInput: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1
\n\nOutput: 16
\n\nExplanation:
\n\nThe subset chosen is the first and fourth items with the sum of values 9 + 7.
\n\n
Constraints:
\n\nn == values.length == labels.length
1 <= n <= 2 * 104
0 <= values[i], labels[i] <= 2 * 104
1 <= numWanted, useLimit <= n
Given an n x n
binary matrix grid
, return the length of the shortest clear path in the matrix. If there is no clear path, return -1
.
A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)
) to the bottom-right cell (i.e., (n - 1, n - 1)
) such that:
0
.The length of a clear path is the number of visited cells of this path.
\n\n\n
Example 1:
\n\nInput: grid = [[0,1],[1,0]]\nOutput: 2\n\n\n
Example 2:
\n\nInput: grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput: 4\n\n\n
Example 3:
\n\n\nInput: grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput: -1\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j] is 0 or 1
Given two strings str1
and str2
, return the shortest string that has both str1
and str2
as subsequences. If there are multiple valid strings, return any of them.
A string s
is a subsequence of string t
if deleting some number of characters from t
(possibly 0
) results in the string s
.
\n
Example 1:
\n\n\nInput: str1 = "abac", str2 = "cab"\nOutput: "cabac"\nExplanation: \nstr1 = "abac" is a subsequence of "cabac" because we can delete the first "c".\nstr2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".\nThe answer provided is the shortest such string that satisfies these properties.\n\n\n
Example 2:
\n\n\nInput: str1 = "aaaaaaaa", str2 = "aaaaaaaa"\nOutput: "aaaaaaaa"\n\n\n
\n
Constraints:
\n\n1 <= str1.length, str2.length <= 1000
str1
and str2
consist of lowercase English letters.You are given a large sample of integers in the range [0, 255]
. Since the sample is so large, it is represented by an array count
where count[k]
is the number of times that k
appears in the sample.
Calculate the following statistics:
\n\nminimum
: The minimum element in the sample.maximum
: The maximum element in the sample.mean
: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.median
:\n\tmedian
is the middle element once the sample is sorted.median
is the average of the two middle elements once the sample is sorted.mode
: The number that appears the most in the sample. It is guaranteed to be unique.Return the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]
. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation: The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.\n\n\n
Example 2:
\n\n\nInput: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.\n\n\n
\n
Constraints:
\n\ncount.length == 256
0 <= count[i] <= 109
1 <= sum(count) <= 109
count
represents is unique.There is a car with capacity
empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer capacity
and an array trips
where trips[i] = [numPassengersi, fromi, toi]
indicates that the ith
trip has numPassengersi
passengers and the locations to pick them up and drop them off are fromi
and toi
respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return true
if it is possible to pick up and drop off all passengers for all the given trips, or false
otherwise.
\n
Example 1:
\n\n\nInput: trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput: false\n\n\n
Example 2:
\n\n\nInput: trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= trips.length <= 1000
trips[i].length == 3
1 <= numPassengersi <= 100
0 <= fromi < toi <= 1000
1 <= capacity <= 105
(This problem is an interactive problem.)
\n\nYou may recall that an array arr
is a mountain array if and only if:
arr.length >= 3
i
with 0 < i < arr.length - 1
such that:\n\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array mountainArr
, return the minimum index
such that mountainArr.get(index) == target
. If such an index
does not exist, return -1
.
You cannot access the mountain array directly. You may only access the array using a MountainArray
interface:
MountainArray.get(k)
returns the element of the array at index k
(0-indexed).MountainArray.length()
returns the length of the array.Submissions making more than 100
calls to MountainArray.get
will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
\n
Example 1:
\n\n\nInput: mountainArr = [1,2,3,4,5,3,1], target = 3\nOutput: 2\nExplanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\n\n
Example 2:
\n\n\nInput: mountainArr = [0,1,2,4,2,1], target = 3\nOutput: -1\nExplanation: 3 does not exist in the array,
so we return -1.\n
\n\n\n
Constraints:
\n\n3 <= mountainArr.length() <= 104
0 <= target <= 109
0 <= mountainArr.get(index) <= 109
Under the grammar given below, strings can represent a set of lowercase words. Let R(expr)
denote the set of words the expression represents.
The grammar can best be understood through simple examples:
\n\nR("a") = {"a"}
R("w") = {"w"}
R("{a,b,c}") = {"a","b","c"}
R("{{a,b},{b,c}}") = {"a","b","c"}
(notice the final set only contains each word at most once)R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}
Formally, the three rules for our grammar:
\n\nx
, we have R(x) = {x}
.e1, e2, ... , ek
with k >= 2
, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...
e1
and e2
, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}
, where +
denotes concatenation, and ×
denotes the cartesian product.Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.
\n\n\n
Example 1:
\n\n\nInput: expression = "{a,b}{c,{d,e}}"\nOutput: ["ac","ad","ae","bc","bd","be"]\n\n\n
Example 2:
\n\n\nInput: expression = "{{a,z},a{b,c},{ab,z}}"\nOutput: ["a","ab","ac","z"]\nExplanation: Each distinct word is written only once in the final answer.\n\n\n
\n
Constraints:
\n\n1 <= expression.length <= 60
expression[i]
consists of '{'
, '}'
, ','
or lowercase English letters.expression
represents a set of words based on the grammar given in the description.We distribute some number of candies
, to a row of n = num_people
people in the following way:
We then give 1 candy to the first person, 2 candies to the second person, and so on until we give n
candies to the last person.
Then, we go back to the start of the row, giving n + 1
candies to the first person, n + 2
candies to the second person, and so on until we give 2 * n
candies to the last person.
This process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).
\n\nReturn an array (of length num_people
and sum candies
) that represents the final distribution of candies.
\n
Example 1:
\n\n\nInput: candies = 7, num_people = 4\nOutput: [1,2,3,1]\nExplanation:\nOn the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\n\n\n
Example 2:
\n\n\nInput: candies = 10, num_people = 3\nOutput: [5,2,3]\nExplanation: \nOn the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n\n\n
\n
Constraints:
\n\nIn an infinite binary tree where every node has two children, the nodes are labelled in row order.
\n\nIn the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.
\n\nGiven the label
of a node in this tree, return the labels in the path from the root of the tree to the node with that label
.
\n
Example 1:
\n\n\nInput: label = 14\nOutput: [1,3,4,14]\n\n\n
Example 2:
\n\n\nInput: label = 26\nOutput: [1,2,6,10,26]\n\n\n
\n
Constraints:
\n\n1 <= label <= 10^6
You are given an array books
where books[i] = [thicknessi, heighti]
indicates the thickness and height of the ith
book. You are also given an integer shelfWidth
.
We want to place these books in order onto bookcase shelves that have a total width shelfWidth
.
We choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth
, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.
Note that at each step of the above process, the order of the books we place is the same order as the given sequence of books.
\n\n5
books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.
\n\n\n
Example 1:
\n\nInput: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4\nOutput: 6\nExplanation:\nThe sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.\n\n\n
Example 2:
\n\n\nInput: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= books.length <= 1000
1 <= thicknessi <= shelfWidth <= 1000
1 <= heighti <= 1000
A boolean expression is an expression that evaluates to either true
or false
. It can be in one of the following shapes:
't'
that evaluates to true
.'f'
that evaluates to false
.'!(subExpr)'
that evaluates to the logical NOT of the inner expression subExpr
.'&(subExpr1, subExpr2, ..., subExprn)'
that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn
where n >= 1
.'|(subExpr1, subExpr2, ..., subExprn)'
that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn
where n >= 1
.Given a string expression
that represents a boolean expression, return the evaluation of that expression.
It is guaranteed that the given expression is valid and follows the given rules.
\n\n\n
Example 1:
\n\n\nInput: expression = "&(|(f))"\nOutput: false\nExplanation: \nFirst, evaluate |(f) --> f. The expression is now "&(f)".\nThen, evaluate &(f) --> f. The expression is now "f".\nFinally, return false.\n\n\n
Example 2:
\n\n\nInput: expression = "|(f,f,f,t)"\nOutput: true\nExplanation: The evaluation of (false OR false OR false OR true) is true.\n\n\n
Example 3:
\n\n\nInput: expression = "!(&(f,t))"\nOutput: true\nExplanation: \nFirst, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)".\nThen, evaluate !(f) --> NOT false --> true. We return true.\n\n\n
\n
Constraints:
\n\n1 <= expression.length <= 2 * 104
'('
, ')'
, '&'
, '|'
, '!'
, 't'
, 'f'
, and ','
.Given a valid (IPv4) IP address
, return a defanged version of that IP address.
A defanged IP address replaces every period "."
with "[.]"
.
\r\n
Example 1:
\r\nInput: address = \"1.1.1.1\"\r\nOutput: \"1[.]1[.]1[.]1\"\r\n
Example 2:
\r\nInput: address = \"255.100.50.0\"\r\nOutput: \"255[.]100[.]50[.]0\"\r\n\r\n
\r\n
Constraints:
\r\n\r\naddress
is a valid IPv4 address.There are n
flights that are labeled from 1
to n
.
You are given an array of flight bookings bookings
, where bookings[i] = [firsti, lasti, seatsi]
represents a booking for flights firsti
through lasti
(inclusive) with seatsi
seats reserved for each flight in the range.
Return an array answer
of length n
, where answer[i]
is the total number of seats reserved for flight i
.
\n
Example 1:
\n\n\nInput: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput: [10,55,45,25,25]\nExplanation:\nFlight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]\n\n\n
Example 2:
\n\n\nInput: bookings = [[1,2,10],[2,2,15]], n = 2\nOutput: [10,25]\nExplanation:\nFlight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]\n\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 104
1 <= bookings.length <= 2 * 104
bookings[i].length == 3
1 <= firsti <= lasti <= n
1 <= seatsi <= 104
Given the root
of a binary tree, each node in the tree has a distinct value.
After deleting all nodes with a value in to_delete
, we are left with a forest (a disjoint union of trees).
Return the roots of the trees in the remaining forest. You may return the result in any order.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\n\n\n
Example 2:
\n\n\nInput: root = [1,2,4,null,3], to_delete = [3]\nOutput: [[1,2,4]]\n\n\n
\n
Constraints:
\n\n1000
.1
and 1000
.to_delete.length <= 1000
to_delete
contains distinct values between 1
and 1000
.A string is a valid parentheses string (denoted VPS) if and only if it consists of "("
and ")"
characters only, and:
AB
(A
concatenated with B
), where A
and B
are VPS's, or(A)
, where A
is a VPS.We can similarly define the nesting depth depth(S)
of any VPS S
as follows:
depth("") = 0
depth(A + B) = max(depth(A), depth(B))
, where A
and B
are VPS'sdepth("(" + A + ")") = 1 + depth(A)
, where A
is a VPS.For example, ""
, "()()"
, and "()(()())"
are VPS's (with nesting depths 0, 1, and 2), and ")("
and "(()"
are not VPS's.
\r\n\r\n
Given a VPS seq, split it into two disjoint subsequences A
and B
, such that A
and B
are VPS's (and A.length + B.length = seq.length
).
Now choose any such A
and B
such that max(depth(A), depth(B))
is the minimum possible value.
Return an answer
array (of length seq.length
) that encodes such a choice of A
and B
: answer[i] = 0
if seq[i]
is part of A
, else answer[i] = 1
. Note that even though multiple answers may exist, you may return any of them.
\n
Example 1:
\n\n\nInput: seq = "(()())"\nOutput: [0,1,1,1,1,0]\n\n\n
Example 2:
\n\n\nInput: seq = "()(())()"\nOutput: [0,0,0,1,1,0,1,1]\n\n\n
\n
Constraints:
\n\n1 <= seq.size <= 10000
Suppose we have a class:
\n\n\npublic class Foo {\n public void first() { print("first"); }\n public void second() { print("second"); }\n public void third() { print("third"); }\n}\n\n\n
The same instance of Foo
will be passed to three different threads. Thread A will call first()
, thread B will call second()
, and thread C will call third()
. Design a mechanism and modify the program to ensure that second()
is executed after first()
, and third()
is executed after second()
.
Note:
\n\nWe do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: "firstsecondthird"\nExplanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,2]\nOutput: "firstsecondthird"\nExplanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.\n\n\n
\n
Constraints:
\n\nnums
is a permutation of [1, 2, 3]
.Suppose you are given the following code:
\n\n\nclass FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print("foo");\n }\n }\n\n public void bar() {\n for (int i = 0; i < n; i++) {\n print("bar");\n }\n }\n}\n\n\n
The same instance of FooBar
will be passed to two different threads:
A
will call foo()
, whileB
will call bar()
.Modify the given program to output "foobar"
n
times.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: "foobar"\nExplanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n"foobar" is being output 1 time.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: "foobarfoobar"\nExplanation: "foobar" is being output 2 times.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You have a function printNumber
that can be called with an integer parameter and prints it to the console.
printNumber(7)
prints 7
to the console.You are given an instance of the class ZeroEvenOdd
that has three functions: zero
, even
, and odd
. The same instance of ZeroEvenOdd
will be passed to three different threads:
zero()
that should only output 0
's.even()
that should only output even numbers.odd()
that should only output odd numbers.Modify the given class to output the series "010203040506..."
where the length of the series must be 2n
.
Implement the ZeroEvenOdd
class:
ZeroEvenOdd(int n)
Initializes the object with the number n
that represents the numbers that should be printed.void zero(printNumber)
Calls printNumber
to output one zero.void even(printNumber)
Calls printNumber
to output one even number.void odd(printNumber)
Calls printNumber
to output one odd number.\n
Example 1:
\n\n\nInput: n = 2\nOutput: "0102"\nExplanation: There are three threads being fired asynchronously.\nOne of them calls zero(), the other calls even(), and the last one calls odd().\n"0102" is the correct output.\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: "0102030405"\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
There are two kinds of threads: oxygen
and hydrogen
. Your goal is to group these threads to form water molecules.
There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen
and releaseOxygen
methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.
In other words:
\n\nWe do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.
\n\nWrite synchronization code for oxygen and hydrogen molecules that enforces these constraints.
\n\n\n
Example 1:
\n\n\nInput: water = "HOH"\nOutput: "HHO"\nExplanation: "HOH" and "OHH" are also valid answers.\n\n\n
Example 2:
\n\n\nInput: water = "OOHHHH"\nOutput: "HHOHHO"\nExplanation: "HOHHHO", "OHHHHO", "HHOHOH", "HOHHOH", "OHHHOH", "HHOOHH", "HOHOHH" and "OHHOHH" are also valid answers.\n\n\n
\n
Constraints:
\n\n3 * n == water.length
1 <= n <= 20
water[i]
is either 'H'
or 'O'
.2 * n
'H'
in water
.n
'O'
in water
.Given two arrays arr1
and arr2
, the elements of arr2
are distinct, and all elements in arr2
are also in arr1
.
Sort the elements of arr1
such that the relative ordering of items in arr1
are the same as in arr2
. Elements that do not appear in arr2
should be placed at the end of arr1
in ascending order.
\n
Example 1:
\n\n\nInput: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\nOutput: [2,2,2,1,4,3,3,9,6,7,19]\n\n\n
Example 2:
\n\n\nInput: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\nOutput: [22,28,8,6,17,44]\n\n\n
\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
arr2
are distinct.arr2[i]
is in arr1
.Given the root
of a binary tree, return the lowest common ancestor of its deepest leaves.
Recall that:
\n\n0
. if the depth of a node is d
, the depth of each of its children is d + 1
.S
of nodes, is the node A
with the largest depth such that every node in S
is in the subtree with root A
.\n
Example 1:
\n\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\n\n
Example 2:
\n\n\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree, and it's the lca of itself.\n\n\n
Example 3:
\n\n\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n\n\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 1000
\n
Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
\n", - "likes": 2008, - "dislikes": 852, - "stats": "{\"totalAccepted\": \"123.6K\", \"totalSubmission\": \"169.3K\", \"totalAcceptedRaw\": 123633, \"totalSubmissionRaw\": 169297, \"acRate\": \"73.0%\"}", + "likes": 2547, + "dislikes": 941, + "stats": "{\"totalAccepted\": \"228.3K\", \"totalSubmission\": \"289.4K\", \"totalAcceptedRaw\": 228343, \"totalSubmissionRaw\": 289418, \"acRate\": \"78.9%\"}", "similarQuestions": "[{\"title\": \"Lowest Common Ancestor of a Binary Tree IV\", \"titleSlug\": \"lowest-common-ancestor-of-a-binary-tree-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -42287,8 +42326,11 @@ "companyTags": null, "difficulty": "Medium", "isPaidOnly": false, - "solution": null, - "hasSolution": false, + "solution": { + "canSeeDetail": true, + "content": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Recursion\n\n#### Intuition\n\nThe problem gives a binary tree and requires returning the lowest common ancestor of its deepest leaf node. The depth of the tree's root node is $0$. We note that all nodes with the maximum depth are leaf nodes. For convenience, we refer to the lowest common ancestor of the deepest leaf nodes as the $\\textit{lca}$ node.\n\nWe use a recursive method to perform a depth-first search, recursively traversing each node in the tree and returning the maximum depth $d$ of the current subtree and the $\\textit{lca}$ node. If the current node is null, we return depth $0$ and an null node. In each search, we recursively search the left and right subtrees, and then compare the depths of the left and right subtrees:\n\n- If the left subtree is deeper, the deepest leaf node is in the left subtree, we return \\{left subtree depth + $1$, the $\\textit{lca}$ node of the left subtree\\}\n- If the right subtree is deeper, the deepest leaf node is in the right subtree, we return \\{right subtree depth + $1$, the $\\textit{lca}$ node of the right subtree\\}\n- If both left and right subtrees have the same depth and both have the deepest leaf nodes, we return \\{left subtree depth + $1$, current node\\}.\n\nFinally, we return the root node's $\\textit{lca}$ node.\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the number of tree nodes.\n\n- Time complexity: $O(n)$\n\n We only need to traverse all the nodes in the tree once.\n\n- Space complexity: $O(n)$\n\n The space complexity is mainly the recursive space, with the worst case being $O(n)$.\n\n---" + }, + "hasSolution": true, "hasVideoSolution": false, "url": "https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/" } @@ -42301,9 +42343,9 @@ "questionFrontendId": "1124", "title": "Longest Well-Performing Interval", "content": "We are given hours
, a list of the number of hours worked per day for a given employee.
A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8
.
A well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.
\n\nReturn the length of the longest well-performing interval.
\n\n\n
Example 1:
\n\n\nInput: hours = [9,9,6,0,6,6,9]\nOutput: 3\nExplanation: The longest well-performing interval is [9,9,6].\n\n\n
Example 2:
\n\n\nInput: hours = [6,6,6]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= hours.length <= 104
0 <= hours[i] <= 16
In a project, you have a list of required skills req_skills
, and a list of people. The ith
person people[i]
contains a list of skills that the person has.
Consider a sufficient team: a set of people such that for every required skill in req_skills
, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.
team = [0, 1, 3]
represents the people with skills people[0]
, people[1]
, and people[3]
.Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.
\n\nIt is guaranteed an answer exists.
\n\n\n
Example 1:
\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\n
Example 2:
\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n\n
\n
Constraints:
\n\n1 <= req_skills.length <= 16
1 <= req_skills[i].length <= 16
req_skills[i]
consists of lowercase English letters.req_skills
are unique.1 <= people.length <= 60
0 <= people[i].length <= 16
1 <= people[i][j].length <= 16
people[i][j]
consists of lowercase English letters.people[i]
are unique.people[i]
is a skill in req_skills
.Given a list of dominoes
, dominoes[i] = [a, b]
is equivalent to dominoes[j] = [c, d]
if and only if either (a == c
and b == d
), or (a == d
and b == c
) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j)
for which 0 <= i < j < dominoes.length
, and dominoes[i]
is equivalent to dominoes[j]
.
\n
Example 1:
\n\n\nInput: dominoes = [[1,2],[2,1],[3,4],[5,6]]\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= dominoes.length <= 4 * 104
dominoes[i].length == 2
1 <= dominoes[i][j] <= 9
You are given an integer n
, the number of nodes in a directed graph where the nodes are labeled from 0
to n - 1
. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
You are given two arrays redEdges
and blueEdges
where:
redEdges[i] = [ai, bi]
indicates that there is a directed red edge from node ai
to node bi
in the graph, andblueEdges[j] = [uj, vj]
indicates that there is a directed blue edge from node uj
to node vj
in the graph.Return an array answer
of length n
, where each answer[x]
is the length of the shortest path from node 0
to node x
such that the edge colors alternate along the path, or -1
if such a path does not exist.
\n
Example 1:
\n\n\nInput: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []\nOutput: [0,1,-1]\n\n\n
Example 2:
\n\n\nInput: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]\nOutput: [0,1,-1]\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
0 <= redEdges.length, blueEdges.length <= 400
redEdges[i].length == blueEdges[j].length == 2
0 <= ai, bi, uj, vj < n
Given an array arr
of positive integers, consider all binary trees such that:
0
or 2
children;arr
correspond to the values of each leaf in an in-order traversal of the tree.Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
\n\nA node is a leaf if and only if it has zero children.
\n\n\n
Example 1:
\n\nInput: arr = [6,2,4]\nOutput: 32\nExplanation: There are two possible trees shown.\nThe first has a non-leaf node sum 36, and the second has non-leaf node sum 32.\n\n\n
Example 2:
\n\nInput: arr = [4,11]\nOutput: 44\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 40
1 <= arr[i] <= 15
Given two arrays of integers with equal lengths, return the maximum value of:
\r\n\r\n|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
where the maximum is taken over all 0 <= i, j < arr1.length
.
\n
Example 1:
\n\n\nInput: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput: 13\n\n\n
Example 2:
\n\n\nInput: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput: 20\n\n\n
\n
Constraints:
\n\n2 <= arr1.length == arr2.length <= 40000
-10^6 <= arr1[i], arr2[i] <= 10^6
The Tribonacci sequence Tn is defined as follows:
\n\nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
\n\nGiven n
, return the value of Tn.
\n
Example 1:
\n\n\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\n\n\n
Example 2:
\n\n\nInput: n = 25\nOutput: 1389537\n\n\n
\n
Constraints:
\n\n0 <= n <= 37
answer <= 2^31 - 1
.On an alphabet board, we start at position (0, 0)
, corresponding to character board[0][0]
.
Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"]
, as shown in the diagram below.
We may make the following moves:
\r\n\r\n'U'
moves our position up one row, if the position exists on the board;'D'
moves our position down one row, if the position exists on the board;'L'
moves our position left one column, if the position exists on the board;'R'
moves our position right one column, if the position exists on the board;'!'
adds the character board[r][c]
at our current position (r, c)
to the answer.(Here, the only positions that exist on the board are positions with letters on them.)
\r\n\r\nReturn a sequence of moves that makes our answer equal to target
in the minimum number of moves. You may return any path that does so.
\r\n
Example 1:
\r\nInput: target = \"leet\"\r\nOutput: \"DDR!UURRR!!DDD!\"\r\n
Example 2:
\r\nInput: target = \"code\"\r\nOutput: \"RR!DDRR!UUL!R!\"\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= target.length <= 100
target
consists only of English lowercase letters.Given a 2D grid
of 0
s and 1
s, return the number of elements in the largest square subgrid that has all 1
s on its border, or 0
if such a subgrid doesn't exist in the grid
.
\r\n
Example 1:
\r\n\r\n\r\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\r\nOutput: 9\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: grid = [[1,1,0,0]]\r\nOutput: 1\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is 0
or 1
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]
. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first.
\n\nOn each player's turn, that player can take all the stones in the first X
remaining piles, where 1 <= X <= 2M
. Then, we set M = max(M, X)
. Initially, M = 1.
The game continues until all the stones have been taken.
\n\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
\n\n\n
Example 1:
\n\nInput: piles = [2,7,9,4,4]
\n\nOutput: 10
\n\nExplanation:
\n\n2 + 4 + 4 = 10
stones in total.2 + 7 = 9
stones in total.So we return 10 since it's larger.
\nExample 2:
\n\nInput: piles = [1,2,3,4,5,100]
\n\nOutput: 104
\n\n
Constraints:
\n\n1 <= piles.length <= 100
1 <= piles[i] <= 104
Table: Activity
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| user_id | int |\n| session_id | int |\n| activity_date | date |\n| activity_type | enum |\n+---------------+---------+\nThis table may have duplicate rows.\nThe activity_type column is an ENUM (category) of type ('open_session', 'end_session', 'scroll_down', 'send_message').\nThe table shows the user activities for a social media website. \nNote that each session belongs to exactly one user.\n\n\n
\n\n
Write a solution to find the daily active user count for a period of 30
days ending 2019-07-27
inclusively. A user was active on someday if they made at least one activity on that day.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivity table:\n+---------+------------+---------------+---------------+\n| user_id | session_id | activity_date | activity_type |\n+---------+------------+---------------+---------------+\n| 1 | 1 | 2019-07-20 | open_session |\n| 1 | 1 | 2019-07-20 | scroll_down |\n| 1 | 1 | 2019-07-20 | end_session |\n| 2 | 4 | 2019-07-20 | open_session |\n| 2 | 4 | 2019-07-21 | send_message |\n| 2 | 4 | 2019-07-21 | end_session |\n| 3 | 2 | 2019-07-21 | open_session |\n| 3 | 2 | 2019-07-21 | send_message |\n| 3 | 2 | 2019-07-21 | end_session |\n| 4 | 3 | 2019-06-25 | open_session |\n| 4 | 3 | 2019-06-25 | end_session |\n+---------+------------+---------------+---------------+\nOutput: \n+------------+--------------+ \n| day | active_users |\n+------------+--------------+ \n| 2019-07-20 | 2 |\n| 2019-07-21 | 2 |\n+------------+--------------+ \nExplanation: Note that we do not care about days with zero active users.\n\n", - "likes": 775, - "dislikes": 881, - "stats": "{\"totalAccepted\": \"337.1K\", \"totalSubmission\": \"684.6K\", \"totalAcceptedRaw\": 337137, \"totalSubmissionRaw\": 684555, \"acRate\": \"49.2%\"}", + "likes": 865, + "dislikes": 927, + "stats": "{\"totalAccepted\": \"395.5K\", \"totalSubmission\": \"799.4K\", \"totalAcceptedRaw\": 395461, \"totalSubmissionRaw\": 799441, \"acRate\": \"49.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -42971,9 +43016,9 @@ "questionFrontendId": "1142", "title": "User Activity for the Past 30 Days II", "content": null, - "likes": 101, - "dislikes": 378, - "stats": "{\"totalAccepted\": \"45.3K\", \"totalSubmission\": \"126.8K\", \"totalAcceptedRaw\": 45298, \"totalSubmissionRaw\": 126767, \"acRate\": \"35.7%\"}", + "likes": 104, + "dislikes": 380, + "stats": "{\"totalAccepted\": \"46.7K\", \"totalSubmission\": \"130.6K\", \"totalAcceptedRaw\": 46653, \"totalSubmissionRaw\": 130636, \"acRate\": \"35.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -42999,9 +43044,9 @@ "questionFrontendId": "1143", "title": "Longest Common Subsequence", "content": "
Given two strings text1
and text2
, return the length of their longest common subsequence. If there is no common subsequence, return 0
.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
\n\n"ace"
is a subsequence of "abcde"
.A common subsequence of two strings is a subsequence that is common to both strings.
\n\n\n
Example 1:
\n\n\nInput: text1 = "abcde", text2 = "ace" \nOutput: 3 \nExplanation: The longest common subsequence is "ace" and its length is 3.\n\n\n
Example 2:
\n\n\nInput: text1 = "abc", text2 = "abc"\nOutput: 3\nExplanation: The longest common subsequence is "abc" and its length is 3.\n\n\n
Example 3:
\n\n\nInput: text1 = "abc", text2 = "def"\nOutput: 0\nExplanation: There is no such common subsequence, so the result is 0.\n\n\n
\n
Constraints:
\n\n1 <= text1.length, text2.length <= 1000
text1
and text2
consist of only lowercase English characters.Given an array nums
of integers, a move consists of choosing any element and decreasing it by 1.
An array A
is a zigzag array if either:
A[0] > A[1] < A[2] > A[3] < A[4] > ...
A[0] < A[1] > A[2] < A[3] > A[4] < ...
Return the minimum number of moves to transform the given array nums
into a zigzag array.
\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: We can decrease 2 to 0 or 3 to 1.\n\n\n
Example 2:
\n\n\nInput: nums = [9,6,1,6,2]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
Two players play a turn based game on a binary tree. We are given the root
of this binary tree, and the number of nodes n
in the tree. n
is odd, and each node has a distinct value from 1
to n
.
Initially, the first player names a value x
with 1 <= x <= n
, and the second player names a value y
with 1 <= y <= n
and y != x
. The first player colors the node with value x
red, and the second player colors the node with value y
blue.
Then, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)
\n\nIf (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.
\n\nYou are the second player. If it is possible to choose such a y
to ensure you win the game, return true
. If it is not possible, return false
.
\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput: true\nExplanation: The second player can choose the node with value 2.\n\n\n
Example 2:
\n\n\nInput: root = [1,2,3], n = 3, x = 1\nOutput: false\n\n\n
\n
Constraints:
\n\nn
.1 <= x <= n <= 100
n
is odd.Implement a SnapshotArray that supports the following interface:
\n\nSnapshotArray(int length)
initializes an array-like data structure with the given length. Initially, each element equals 0.void set(index, val)
sets the element at the given index
to be equal to val
.int snap()
takes a snapshot of the array and returns the snap_id
: the total number of times we called snap()
minus 1
.int get(index, snap_id)
returns the value at the given index
, at the time we took the snapshot with the given snap_id
\n
Example 1:
\n\n\nInput: ["SnapshotArray","set","snap","set","get"]\n[[3],[0,5],[],[0,6],[0,0]]\nOutput: [null,null,0,null,5]\nExplanation: \nSnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\nsnapshotArr.set(0,5); // Set array[0] = 5\nsnapshotArr.snap(); // Take a snapshot, return snap_id = 0\nsnapshotArr.set(0,6);\nsnapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5\n\n
\n
Constraints:
\n\n1 <= length <= 5 * 104
0 <= index < length
0 <= val <= 109
0 <= snap_id <
(the total number of times we call snap()
)5 * 104
calls will be made to set
, snap
, and get
.You are given a string text
. You should split it to k substrings (subtext1, subtext2, ..., subtextk)
such that:
subtexti
is a non-empty string.text
(i.e., subtext1 + subtext2 + ... + subtextk == text
).subtexti == subtextk - i + 1
for all valid values of i
(i.e., 1 <= i <= k
).Return the largest possible value of k
.
\n
Example 1:
\n\n\nInput: text = "ghiabcdefhelloadamhelloabcdefghi"\nOutput: 7\nExplanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".\n\n\n
Example 2:
\n\n\nInput: text = "merchant"\nOutput: 1\nExplanation: We can split the string on "(merchant)".\n\n\n
Example 3:
\n\n\nInput: text = "antaprezatepzapreanta"\nOutput: 11\nExplanation: We can split the string on "(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)".\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 1000
text
consists only of lowercase English characters.Table: Views
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| article_id | int |\n| author_id | int |\n| viewer_id | int |\n| view_date | date |\n+---------------+---------+\nThere is no primary key (column with unique values) for this table, the table may have duplicate rows.\nEach row of this table indicates that some viewer viewed an article (written by some author) on some date. \nNote that equal author_id and viewer_id indicate the same person.\n\n\n
\n\n
Write a solution to find all the authors that viewed at least one of their own articles.
\n\nReturn the result table sorted by id
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nViews table:\n+------------+-----------+-----------+------------+\n| article_id | author_id | viewer_id | view_date |\n+------------+-----------+-----------+------------+\n| 1 | 3 | 5 | 2019-08-01 |\n| 1 | 3 | 6 | 2019-08-02 |\n| 2 | 7 | 7 | 2019-08-01 |\n| 2 | 7 | 6 | 2019-08-02 |\n| 4 | 7 | 1 | 2019-07-22 |\n| 3 | 4 | 4 | 2019-07-21 |\n| 3 | 4 | 4 | 2019-07-21 |\n+------------+-----------+-----------+------------+\nOutput: \n+------+\n| id |\n+------+\n| 4 |\n| 7 |\n+------+\n\n", - "likes": 1752, - "dislikes": 102, - "stats": "{\"totalAccepted\": \"1M\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 1033647, \"totalSubmissionRaw\": 1341070, \"acRate\": \"77.1%\"}", + "likes": 1915, + "dislikes": 116, + "stats": "{\"totalAccepted\": \"1.2M\", \"totalSubmission\": \"1.6M\", \"totalAcceptedRaw\": 1231223, \"totalSubmissionRaw\": 1595657, \"acRate\": \"77.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -43225,9 +43270,9 @@ "questionFrontendId": "1149", "title": "Article Views II", "content": null, - "likes": 130, - "dislikes": 28, - "stats": "{\"totalAccepted\": \"40.3K\", \"totalSubmission\": \"85.4K\", \"totalAcceptedRaw\": 40274, \"totalSubmissionRaw\": 85355, \"acRate\": \"47.2%\"}", + "likes": 132, + "dislikes": 29, + "stats": "{\"totalAccepted\": \"41.8K\", \"totalSubmission\": \"88.6K\", \"totalAcceptedRaw\": 41810, \"totalSubmissionRaw\": 88576, \"acRate\": \"47.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -43256,9 +43301,9 @@ "questionFrontendId": "1150", "title": "Check If a Number Is Majority Element in a Sorted Array", "content": null, - "likes": 461, + "likes": 464, "dislikes": 35, - "stats": "{\"totalAccepted\": \"53.9K\", \"totalSubmission\": \"91.3K\", \"totalAcceptedRaw\": 53907, \"totalSubmissionRaw\": 91322, \"acRate\": \"59.0%\"}", + "stats": "{\"totalAccepted\": \"55.9K\", \"totalSubmission\": \"94.6K\", \"totalAcceptedRaw\": 55921, \"totalSubmissionRaw\": 94632, \"acRate\": \"59.1%\"}", "similarQuestions": "[{\"title\": \"Majority Element\", \"titleSlug\": \"majority-element\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Majority Element II\", \"titleSlug\": \"majority-element-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -43295,9 +43340,9 @@ "questionFrontendId": "1151", "title": "Minimum Swaps to Group All 1's Together", "content": null, - "likes": 1235, + "likes": 1265, "dislikes": 18, - "stats": "{\"totalAccepted\": \"77.6K\", \"totalSubmission\": \"128.7K\", \"totalAcceptedRaw\": 77606, \"totalSubmissionRaw\": 128723, \"acRate\": \"60.3%\"}", + "stats": "{\"totalAccepted\": \"86.1K\", \"totalSubmission\": \"140.9K\", \"totalAcceptedRaw\": 86066, \"totalSubmissionRaw\": 140901, \"acRate\": \"61.1%\"}", "similarQuestions": "[{\"title\": \"Minimum Adjacent Swaps for K Consecutive Ones\", \"titleSlug\": \"minimum-adjacent-swaps-for-k-consecutive-ones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Swaps to Group All 1's Together II\", \"titleSlug\": \"minimum-swaps-to-group-all-1s-together-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Time Needed to Rearrange a Binary String\", \"titleSlug\": \"time-needed-to-rearrange-a-binary-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Moves to Pick K Ones\", \"titleSlug\": \"minimum-moves-to-pick-k-ones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -43336,9 +43381,9 @@ "questionFrontendId": "1152", "title": "Analyze User Website Visit Pattern", "content": null, - "likes": 517, - "dislikes": 3818, - "stats": "{\"totalAccepted\": \"110.4K\", \"totalSubmission\": \"256.1K\", \"totalAcceptedRaw\": 110421, \"totalSubmissionRaw\": 256090, \"acRate\": \"43.1%\"}", + "likes": 532, + "dislikes": 3924, + "stats": "{\"totalAccepted\": \"121.2K\", \"totalSubmission\": \"277.3K\", \"totalAcceptedRaw\": 121221, \"totalSubmissionRaw\": 277333, \"acRate\": \"43.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -43375,9 +43420,9 @@ "questionFrontendId": "1153", "title": "String Transforms Into Another String", "content": null, - "likes": 884, - "dislikes": 337, - "stats": "{\"totalAccepted\": \"53K\", \"totalSubmission\": \"152.1K\", \"totalAcceptedRaw\": 52975, \"totalSubmissionRaw\": 152128, \"acRate\": \"34.8%\"}", + "likes": 886, + "dislikes": 338, + "stats": "{\"totalAccepted\": \"53.5K\", \"totalSubmission\": \"153.8K\", \"totalAcceptedRaw\": 53478, \"totalSubmissionRaw\": 153795, \"acRate\": \"34.8%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -43416,9 +43461,9 @@ "questionFrontendId": "1154", "title": "Day of the Year", "content": "
Given a string date
representing a Gregorian calendar date formatted as YYYY-MM-DD
, return the day number of the year.
\n
Example 1:
\n\n\nInput: date = "2019-01-09"\nOutput: 9\nExplanation: Given date is the 9th day of the year in 2019.\n\n\n
Example 2:
\n\n\nInput: date = "2019-02-10"\nOutput: 41\n\n\n
\n
Constraints:
\n\ndate.length == 10
date[4] == date[7] == '-'
, and all other date[i]
's are digitsdate
represents a calendar date between Jan 1st, 1900 and Dec 31st, 2019.You have n
dice, and each dice has k
faces numbered from 1
to k
.
Given three integers n
, k
, and target
, return the number of possible ways (out of the kn
total ways) to roll the dice, so the sum of the face-up numbers equals target
. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 1, k = 6, target = 3\nOutput: 1\nExplanation: You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\n\n\n
Example 2:
\n\n\nInput: n = 2, k = 6, target = 7\nOutput: 6\nExplanation: You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\n\n\n
Example 3:
\n\n\nInput: n = 30, k = 30, target = 500\nOutput: 222616187\nExplanation: The answer must be returned modulo 109 + 7.\n\n\n
\n
Constraints:
\n\n1 <= n, k <= 30
1 <= target <= 1000
You are given a string text
. You can swap two of the characters in the text
.
Return the length of the longest substring with repeated characters.
\n\n\n
Example 1:
\n\n\nInput: text = "ababa"\nOutput: 3\nExplanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is "aaa" with length 3.\n\n\n
Example 2:
\n\n\nInput: text = "aaabaaa"\nOutput: 6\nExplanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring "aaaaaa" with length 6.\n\n\n
Example 3:
\n\n\nInput: text = "aaaaa"\nOutput: 5\nExplanation: No need to swap, longest repeated character substring is "aaaaa" with length is 5.\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 2 * 104
text
consist of lowercase English characters only.Design a data structure that efficiently finds the majority element of a given subarray.
\n\nThe majority element of a subarray is an element that occurs threshold
times or more in the subarray.
Implementing the MajorityChecker
class:
MajorityChecker(int[] arr)
Initializes the instance of the class with the given array arr
.int query(int left, int right, int threshold)
returns the element in the subarray arr[left...right]
that occurs at least threshold
times, or -1
if no such element exists.\n
Example 1:
\n\n\nInput\n["MajorityChecker", "query", "query", "query"]\n[[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]\nOutput\n[null, 1, -1, 2]\n\nExplanation\nMajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\nmajorityChecker.query(0, 5, 4); // return 1\nmajorityChecker.query(0, 3, 3); // return -1\nmajorityChecker.query(2, 3, 2); // return 2\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 2 * 104
1 <= arr[i] <= 2 * 104
0 <= left <= right < arr.length
threshold <= right - left + 1
2 * threshold > right - left + 1
104
calls will be made to query
.Table: Users
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| user_id | int |\n| join_date | date |\n| favorite_brand | varchar |\n+----------------+---------+\nuser_id is the primary key (column with unique values) of this table.\nThis table has the info of the users of an online shopping website where users can sell and buy items.\n\n\n
\n\n
Table: Orders
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| order_id | int |\n| order_date | date |\n| item_id | int |\n| buyer_id | int |\n| seller_id | int |\n+---------------+---------+\norder_id is the primary key (column with unique values) of this table.\nitem_id is a foreign key (reference column) to the Items table.\nbuyer_id and seller_id are foreign keys to the Users table.\n\n\n
\n\n
Table: Items
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| item_id | int |\n| item_brand | varchar |\n+---------------+---------+\nitem_id is the primary key (column with unique values) of this table.\n\n\n
\n\n
Write a solution to find for each user, the join date and the number of orders they made as a buyer in 2019
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+---------+------------+----------------+\n| user_id | join_date | favorite_brand |\n+---------+------------+----------------+\n| 1 | 2018-01-01 | Lenovo |\n| 2 | 2018-02-09 | Samsung |\n| 3 | 2018-01-19 | LG |\n| 4 | 2018-05-21 | HP |\n+---------+------------+----------------+\nOrders table:\n+----------+------------+---------+----------+-----------+\n| order_id | order_date | item_id | buyer_id | seller_id |\n+----------+------------+---------+----------+-----------+\n| 1 | 2019-08-01 | 4 | 1 | 2 |\n| 2 | 2018-08-02 | 2 | 1 | 3 |\n| 3 | 2019-08-03 | 3 | 2 | 3 |\n| 4 | 2018-08-04 | 1 | 4 | 2 |\n| 5 | 2018-08-04 | 1 | 3 | 4 |\n| 6 | 2019-08-05 | 2 | 2 | 4 |\n+----------+------------+---------+----------+-----------+\nItems table:\n+---------+------------+\n| item_id | item_brand |\n+---------+------------+\n| 1 | Samsung |\n| 2 | Lenovo |\n| 3 | LG |\n| 4 | HP |\n+---------+------------+\nOutput: \n+-----------+------------+----------------+\n| buyer_id | join_date | orders_in_2019 |\n+-----------+------------+----------------+\n| 1 | 2018-01-01 | 1 |\n| 2 | 2018-02-09 | 2 |\n| 3 | 2018-01-19 | 0 |\n| 4 | 2018-05-21 | 0 |\n+-----------+------------+----------------+\n\n", - "likes": 670, - "dislikes": 68, - "stats": "{\"totalAccepted\": \"122.2K\", \"totalSubmission\": \"213.9K\", \"totalAcceptedRaw\": 122238, \"totalSubmissionRaw\": 213867, \"acRate\": \"57.2%\"}", + "likes": 695, + "dislikes": 70, + "stats": "{\"totalAccepted\": \"133.7K\", \"totalSubmission\": \"233.9K\", \"totalAcceptedRaw\": 133722, \"totalSubmissionRaw\": 233867, \"acRate\": \"57.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -43595,9 +43640,9 @@ "questionFrontendId": "1159", "title": "Market Analysis II", "content": null, - "likes": 122, + "likes": 123, "dislikes": 80, - "stats": "{\"totalAccepted\": \"20.8K\", \"totalSubmission\": \"36.1K\", \"totalAcceptedRaw\": 20794, \"totalSubmissionRaw\": 36098, \"acRate\": \"57.6%\"}", + "stats": "{\"totalAccepted\": \"21.8K\", \"totalSubmission\": \"37.6K\", \"totalAcceptedRaw\": 21751, \"totalSubmissionRaw\": 37608, \"acRate\": \"57.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -43625,10 +43670,10 @@ "questionId": "1112", "questionFrontendId": "1160", "title": "Find Words That Can Be Formed by Characters", - "content": "
You are given an array of strings words
and a string chars
.
A string is good if it can be formed by characters from chars
(each character can only be used once).
Return the sum of lengths of all good strings in words.
\n\n\n
Example 1:
\n\n\nInput: words = ["cat","bt","hat","tree"], chars = "atach"\nOutput: 6\nExplanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.\n\n\n
Example 2:
\n\n\nInput: words = ["hello","world","leetcode"], chars = "welldonehoneyr"\nOutput: 10\nExplanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i]
and chars
consist of lowercase English letters.You are given an array of strings words
and a string chars
.
A string is good if it can be formed by characters from chars
(each character can only be used once for each word in words
).
Return the sum of lengths of all good strings in words.
\n\n\n
Example 1:
\n\n\nInput: words = ["cat","bt","hat","tree"], chars = "atach"\nOutput: 6\nExplanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.\n\n\n
Example 2:
\n\n\nInput: words = ["hello","world","leetcode"], chars = "welldonehoneyr"\nOutput: 10\nExplanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
words[i]
and chars
consist of lowercase English letters.Given the root
of a binary tree, the level of its root is 1
, the level of its children is 2
, and so on.
Return the smallest level x
such that the sum of all the values of nodes at level x
is maximal.
\n
Example 1:
\n\nInput: root = [1,7,0,7,-8,null,null]\nOutput: 2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.\n\n\n
Example 2:
\n\n\nInput: root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput: 2\n\n\n
\n
Constraints:
\n\n[1, 104]
.-105 <= Node.val <= 105
Given an n x n
grid
containing only values 0
and 1
, where 0
represents water and 1
represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1
.
The distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0)
and (x1, y1)
is |x0 - x1| + |y0 - y1|
.
\n
Example 1:
\n\nInput: grid = [[1,0,1],[0,0,0],[1,0,1]]\nOutput: 2\nExplanation: The cell (1, 1) is as far as possible from all the land with distance 2.\n\n\n
Example 2:
\n\nInput: grid = [[1,0,0],[0,0,0],[0,0,0]]\nOutput: 4\nExplanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
1 <= n <= 100
grid[i][j]
is 0
or 1
Given a string s
, return the last substring of s
in lexicographical order.
\n
Example 1:
\n\n\nInput: s = "abab"\nOutput: "bab"\nExplanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".\n\n\n
Example 2:
\n\n\nInput: s = "leetcode"\nOutput: "tcode"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 4 * 105
s
contains only lowercase English letters.Table: Products
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| new_price | int |\n| change_date | date |\n+---------------+---------+\n(product_id, change_date) is the primary key (combination of columns with unique values) of this table.\nEach row of this table indicates that the price of some product was changed to a new price at some date.\n\n
\n\n
Write a solution to find the prices of all products on 2019-08-16
. Assume the price of all products before any change is 10
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProducts table:\n+------------+-----------+-------------+\n| product_id | new_price | change_date |\n+------------+-----------+-------------+\n| 1 | 20 | 2019-08-14 |\n| 2 | 50 | 2019-08-14 |\n| 1 | 30 | 2019-08-15 |\n| 1 | 35 | 2019-08-16 |\n| 2 | 65 | 2019-08-17 |\n| 3 | 20 | 2019-08-18 |\n+------------+-----------+-------------+\nOutput: \n+------------+-------+\n| product_id | price |\n+------------+-------+\n| 2 | 50 |\n| 1 | 35 |\n| 3 | 10 |\n+------------+-------+\n\n", - "likes": 1060, - "dislikes": 270, - "stats": "{\"totalAccepted\": \"204.2K\", \"totalSubmission\": \"358K\", \"totalAcceptedRaw\": 204157, \"totalSubmissionRaw\": 357966, \"acRate\": \"57.0%\"}", + "content": "
Table: Products
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| new_price | int |\n| change_date | date |\n+---------------+---------+\n(product_id, change_date) is the primary key (combination of columns with unique values) of this table.\nEach row of this table indicates that the price of some product was changed to a new price at some date.\n\n
Initially, all products have price 10.
\n\nWrite a solution to find the prices of all products on the date 2019-08-16
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProducts table:\n+------------+-----------+-------------+\n| product_id | new_price | change_date |\n+------------+-----------+-------------+\n| 1 | 20 | 2019-08-14 |\n| 2 | 50 | 2019-08-14 |\n| 1 | 30 | 2019-08-15 |\n| 1 | 35 | 2019-08-16 |\n| 2 | 65 | 2019-08-17 |\n| 3 | 20 | 2019-08-18 |\n+------------+-----------+-------------+\nOutput: \n+------------+-------+\n| product_id | price |\n+------------+-------+\n| 2 | 50 |\n| 1 | 35 |\n| 3 | 10 |\n+------------+-------+\n\n", + "likes": 1158, + "dislikes": 287, + "stats": "{\"totalAccepted\": \"246.5K\", \"totalSubmission\": \"429.1K\", \"totalAcceptedRaw\": 246518, \"totalSubmissionRaw\": 429148, \"acRate\": \"57.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -43828,9 +43873,9 @@ "questionFrontendId": "1165", "title": "Single-Row Keyboard", "content": null, - "likes": 533, - "dislikes": 22, - "stats": "{\"totalAccepted\": \"89.3K\", \"totalSubmission\": \"101.9K\", \"totalAcceptedRaw\": 89342, \"totalSubmissionRaw\": 101932, \"acRate\": \"87.6%\"}", + "likes": 538, + "dislikes": 23, + "stats": "{\"totalAccepted\": \"91.1K\", \"totalSubmission\": \"103.8K\", \"totalAcceptedRaw\": 91063, \"totalSubmissionRaw\": 103835, \"acRate\": \"87.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -43867,9 +43912,9 @@ "questionFrontendId": "1166", "title": "Design File System", "content": null, - "likes": 590, - "dislikes": 70, - "stats": "{\"totalAccepted\": \"68.8K\", \"totalSubmission\": \"108.1K\", \"totalAcceptedRaw\": 68807, \"totalSubmissionRaw\": 108052, \"acRate\": \"63.7%\"}", + "likes": 601, + "dislikes": 73, + "stats": "{\"totalAccepted\": \"75.4K\", \"totalSubmission\": \"117.5K\", \"totalAcceptedRaw\": 75358, \"totalSubmissionRaw\": 117511, \"acRate\": \"64.1%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -43911,9 +43956,9 @@ "questionFrontendId": "1167", "title": "Minimum Cost to Connect Sticks", "content": null, - "likes": 1330, + "likes": 1340, "dislikes": 158, - "stats": "{\"totalAccepted\": \"133.2K\", \"totalSubmission\": \"188.3K\", \"totalAcceptedRaw\": 133243, \"totalSubmissionRaw\": 188288, \"acRate\": \"70.8%\"}", + "stats": "{\"totalAccepted\": \"138.5K\", \"totalSubmission\": \"194.7K\", \"totalAcceptedRaw\": 138516, \"totalSubmissionRaw\": 194658, \"acRate\": \"71.2%\"}", "similarQuestions": "[{\"title\": \"Minimum Cost to Merge Stones\", \"titleSlug\": \"minimum-cost-to-merge-stones\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -43953,9 +43998,9 @@ "questionFrontendId": "1168", "title": "Optimize Water Distribution in a Village", "content": null, - "likes": 1183, + "likes": 1192, "dislikes": 40, - "stats": "{\"totalAccepted\": \"52.8K\", \"totalSubmission\": \"81.3K\", \"totalAcceptedRaw\": 52834, \"totalSubmissionRaw\": 81335, \"acRate\": \"65.0%\"}", + "stats": "{\"totalAccepted\": \"55.3K\", \"totalSubmission\": \"84.9K\", \"totalAcceptedRaw\": 55344, \"totalSubmissionRaw\": 84892, \"acRate\": \"65.2%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -43999,9 +44044,9 @@ "questionFrontendId": "1169", "title": "Invalid Transactions", "content": "
A transaction is possibly invalid if:
\n\n$1000
, or;60
minutes of another transaction with the same name in a different city.You are given an array of strings transaction
where transactions[i]
consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
Return a list of transactions
that are possibly invalid. You may return the answer in any order.
\n
Example 1:
\n\n\nInput: transactions = ["alice,20,800,mtv","alice,50,100,beijing"]\nOutput: ["alice,20,800,mtv","alice,50,100,beijing"]\nExplanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.\n\n
Example 2:
\n\n\nInput: transactions = ["alice,20,800,mtv","alice,50,1200,mtv"]\nOutput: ["alice,50,1200,mtv"]\n\n\n
Example 3:
\n\n\nInput: transactions = ["alice,20,800,mtv","bob,50,1200,mtv"]\nOutput: ["bob,50,1200,mtv"]\n\n\n
\n
Constraints:
\n\ntransactions.length <= 1000
transactions[i]
takes the form "{name},{time},{amount},{city}"
{name}
and {city}
consist of lowercase English letters, and have lengths between 1
and 10
.{time}
consist of digits, and represent an integer between 0
and 1000
.{amount}
consist of digits, and represent an integer between 0
and 2000
.Let the function f(s)
be the frequency of the lexicographically smallest character in a non-empty string s
. For example, if s = "dcce"
then f(s) = 2
because the lexicographically smallest character is 'c'
, which has a frequency of 2.
You are given an array of strings words
and another array of query strings queries
. For each query queries[i]
, count the number of words in words
such that f(queries[i])
< f(W)
for each W
in words
.
Return an integer array answer
, where each answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: queries = ["cbd"], words = ["zaaaz"]\nOutput: [1]\nExplanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").\n\n\n
Example 2:
\n\n\nInput: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]\nOutput: [1,2]\nExplanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").\n\n\n
\n
Constraints:
\n\n1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j]
, words[i][j]
consist of lowercase English letters.Given the head
of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0
until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
\r\n\n\n
(Note that in the examples below, all sequences are serializations of ListNode
objects.)
Example 1:
\n\n\nInput: head = [1,2,-3,3,1]\nOutput: [3,1]\nNote: The answer [1,2,1] would also be accepted.\n\n\n
Example 2:
\n\n\nInput: head = [1,2,3,-3,4]\nOutput: [1,2,4]\n\n\n
Example 3:
\n\n\nInput: head = [1,2,3,-3,-2]\nOutput: [1]\n\n\n
\n
Constraints:
\n\n1
and 1000
nodes.-1000 <= node.val <= 1000
.You have an infinite number of stacks arranged in a row and numbered (left to right) from 0
, each of the stacks has the same maximum capacity.
Implement the DinnerPlates
class:
DinnerPlates(int capacity)
Initializes the object with the maximum capacity of the stacks capacity
.void push(int val)
Pushes the given integer val
into the leftmost stack with a size less than capacity
.int pop()
Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1
if all the stacks are empty.int popAtStack(int index)
Returns the value at the top of the stack with the given index index
and removes it from that stack or returns -1
if the stack with that given index is empty.\n
Example 1:
\n\n\nInput\n["DinnerPlates", "push", "push", "push", "push", "push", "popAtStack", "push", "push", "popAtStack", "popAtStack", "pop", "pop", "pop", "pop", "pop"]\n[[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]\nOutput\n[null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\n\nExplanation: \nDinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\nD.push(1);\nD.push(2);\nD.push(3);\nD.push(4);\nD.push(5); // The stacks are now: 2 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\nD.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\nD.push(20); // The stacks are now: 20 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\nD.push(21); // The stacks are now: 20 4 21\n 1 3 5\n \ufe48 \ufe48 \ufe48\nD.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n \ufe48 \ufe48 \ufe48\nD.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n \ufe48 \ufe48 \ufe48 \nD.pop() // Returns 5. The stacks are now: 4\n 1 3 \n \ufe48 \ufe48 \nD.pop() // Returns 4. The stacks are now: 1 3 \n \ufe48 \ufe48 \nD.pop() // Returns 3. The stacks are now: 1 \n \ufe48 \nD.pop() // Returns 1. There are no stacks.\nD.pop() // Returns -1. There are still no stacks.\n\n\n
\n
Constraints:
\n\n1 <= capacity <= 2 * 104
1 <= val <= 2 * 104
0 <= index <= 105
2 * 105
calls will be made to push
, pop
, and popAtStack
.Table: Delivery
\n+-----------------------------+---------+\n| Column Name | Type |\n+-----------------------------+---------+\n| delivery_id | int |\n| customer_id | int |\n| order_date | date |\n| customer_pref_delivery_date | date |\n+-----------------------------+---------+\ndelivery_id is the column of unique values of this table.\nThe table holds information about food delivery to customers that make orders at some date and specify a preferred delivery date (on the same order date or after it).\n\n\n
\n\n
If the customer's preferred delivery date is the same as the order date, then the order is called immediate; otherwise, it is called scheduled.
\n\nThe first order of a customer is the order with the earliest order date that the customer made. It is guaranteed that a customer has precisely one first order.
\n\nWrite a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nDelivery table:\n+-------------+-------------+------------+-----------------------------+\n| delivery_id | customer_id | order_date | customer_pref_delivery_date |\n+-------------+-------------+------------+-----------------------------+\n| 1 | 1 | 2019-08-01 | 2019-08-02 |\n| 2 | 2 | 2019-08-02 | 2019-08-02 |\n| 3 | 1 | 2019-08-11 | 2019-08-12 |\n| 4 | 3 | 2019-08-24 | 2019-08-24 |\n| 5 | 3 | 2019-08-21 | 2019-08-22 |\n| 6 | 2 | 2019-08-11 | 2019-08-13 |\n| 7 | 4 | 2019-08-09 | 2019-08-09 |\n+-------------+-------------+------------+-----------------------------+\nOutput: \n+----------------------+\n| immediate_percentage |\n+----------------------+\n| 50.00 |\n+----------------------+\nExplanation: \nThe customer id 1 has a first order with delivery id 1 and it is scheduled.\nThe customer id 2 has a first order with delivery id 2 and it is immediate.\nThe customer id 3 has a first order with delivery id 5 and it is scheduled.\nThe customer id 4 has a first order with delivery id 7 and it is immediate.\nHence, half the customers have immediate first orders.\n\n", - "likes": 887, - "dislikes": 147, - "stats": "{\"totalAccepted\": \"264.8K\", \"totalSubmission\": \"494.6K\", \"totalAcceptedRaw\": 264835, \"totalSubmissionRaw\": 494621, \"acRate\": \"53.5%\"}", + "likes": 984, + "dislikes": 160, + "stats": "{\"totalAccepted\": \"324.3K\", \"totalSubmission\": \"597.3K\", \"totalAcceptedRaw\": 324311, \"totalSubmissionRaw\": 597268, \"acRate\": \"54.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -44220,9 +44265,9 @@ "questionFrontendId": "1175", "title": "Prime Arrangements", "content": "
Return the number of permutations of 1 to n
so that prime numbers are at prime indices (1-indexed.)
(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)
\n\nSince the answer may be large, return the answer modulo 10^9 + 7
.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n\n\n
Example 2:
\n\n\nInput: n = 100\nOutput: 682289015\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
You are given a string s
and array queries
where queries[i] = [lefti, righti, ki]
. We may rearrange the substring s[lefti...righti]
for each query and then choose up to ki
of them to replace with any lowercase English letter.
If the substring is possible to be a palindrome string after the operations above, the result of the query is true
. Otherwise, the result is false
.
Return a boolean array answer
where answer[i]
is the result of the ith
query queries[i]
.
Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa"
, and ki = 2
, we can only replace two of the letters. Also, note that no query modifies the initial string s
.
\n
Example :
\n\n\nInput: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput: [true,false,false,true,true]\nExplanation:\nqueries[0]: substring = "d", is palidrome.\nqueries[1]: substring = "bc", is not palidrome.\nqueries[2]: substring = "abcd", is not palidrome after replacing only 1 character.\nqueries[3]: substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".\nqueries[4]: substring = "abcda", could be changed to "abcba" which is palidrome.\n\n\n
Example 2:
\n\n\nInput: s = "lyb", queries = [[0,1,0],[2,2,1]]\nOutput: [false,true]\n\n\n
\n
Constraints:
\n\n1 <= s.length, queries.length <= 105
0 <= lefti <= righti < s.length
0 <= ki <= s.length
s
consists of lowercase English letters.puzzle
string, a word
is valid if both the following conditions are satisfied:\nword
contains the first letter of puzzle
.word
, that letter is in puzzle
.\n\t"abcdefg"
, then valid words are "faced"
, "cabbage"
, and "baggage"
, while"beefed"
(does not include 'a'
) and "based"
(includes 's'
which is not in the puzzle).answer
, where answer[i]
is the number of words in the given word list words
that is valid with respect to the puzzle puzzles[i]
.\n\n
Example 1:
\n\n\nInput: words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]\nOutput: [1,1,3,2,4,0]\nExplanation: \n1 valid word for "aboveyz" : "aaaa" \n1 valid word for "abrodyz" : "aaaa"\n3 valid words for "abslute" : "aaaa", "asas", "able"\n2 valid words for "absoryz" : "aaaa", "asas"\n4 valid words for "actresz" : "aaaa", "asas", "actt", "access"\nThere are no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.\n\n\n
Example 2:
\n\n\nInput: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz","aelpsxy","saelpxy","xaelpsy"]\nOutput: [0,1,3,2,0]\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 105
4 <= words[i].length <= 50
1 <= puzzles.length <= 104
puzzles[i].length == 7
words[i]
and puzzles[i]
consist of lowercase English letters.puzzles[i]
does not contain repeated characters.Table: Department
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| id | int |\n| revenue | int |\n| month | varchar |\n+-------------+---------+\nIn SQL,(id, month) is the primary key of this table.\nThe table has information about the revenue of each department per month.\nThe month has values in ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].\n\n\n
\n\n
Reformat the table such that there is a department id column and a revenue column for each month.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nDepartment table:\n+------+---------+-------+\n| id | revenue | month |\n+------+---------+-------+\n| 1 | 8000 | Jan |\n| 2 | 9000 | Jan |\n| 3 | 10000 | Feb |\n| 1 | 7000 | Feb |\n| 1 | 6000 | Mar |\n+------+---------+-------+\nOutput: \n+------+-------------+-------------+-------------+-----+-------------+\n| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | ... | Dec_Revenue |\n+------+-------------+-------------+-------------+-----+-------------+\n| 1 | 8000 | 7000 | 6000 | ... | null |\n| 2 | 9000 | null | null | ... | null |\n| 3 | null | 10000 | null | ... | null |\n+------+-------------+-------------+-------------+-----+-------------+\nExplanation: The revenue from Apr to Dec is null.\nNote that the result table has 13 columns (1 for the department id + 12 for the months).\n\n", - "likes": 772, - "dislikes": 613, - "stats": "{\"totalAccepted\": \"134.9K\", \"totalSubmission\": \"175.5K\", \"totalAcceptedRaw\": 134856, \"totalSubmissionRaw\": 175490, \"acRate\": \"76.8%\"}", + "likes": 801, + "dislikes": 621, + "stats": "{\"totalAccepted\": \"145.2K\", \"totalSubmission\": \"189.5K\", \"totalAcceptedRaw\": 145179, \"totalSubmissionRaw\": 189458, \"acRate\": \"76.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -44409,9 +44454,9 @@ "questionFrontendId": "1180", "title": "Count Substrings with Only One Distinct Letter", "content": null, - "likes": 356, - "dislikes": 51, - "stats": "{\"totalAccepted\": \"29.1K\", \"totalSubmission\": \"36.2K\", \"totalAcceptedRaw\": 29104, \"totalSubmissionRaw\": 36200, \"acRate\": \"80.4%\"}", + "likes": 360, + "dislikes": 52, + "stats": "{\"totalAccepted\": \"29.8K\", \"totalSubmission\": \"37K\", \"totalAcceptedRaw\": 29841, \"totalSubmissionRaw\": 37004, \"acRate\": \"80.6%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -44449,7 +44494,7 @@ "content": null, "likes": 76, "dislikes": 154, - "stats": "{\"totalAccepted\": \"9.9K\", \"totalSubmission\": \"21.4K\", \"totalAcceptedRaw\": 9919, \"totalSubmissionRaw\": 21416, \"acRate\": \"46.3%\"}", + "stats": "{\"totalAccepted\": \"10.1K\", \"totalSubmission\": \"21.6K\", \"totalAcceptedRaw\": 10050, \"totalSubmissionRaw\": 21582, \"acRate\": \"46.6%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -44487,9 +44532,9 @@ "questionFrontendId": "1182", "title": "Shortest Distance to Target Color", "content": null, - "likes": 522, + "likes": 523, "dislikes": 22, - "stats": "{\"totalAccepted\": \"36.9K\", \"totalSubmission\": \"66.6K\", \"totalAcceptedRaw\": 36909, \"totalSubmissionRaw\": 66564, \"acRate\": \"55.4%\"}", + "stats": "{\"totalAccepted\": \"37.5K\", \"totalSubmission\": \"67.7K\", \"totalAcceptedRaw\": 37542, \"totalSubmissionRaw\": 67668, \"acRate\": \"55.5%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -44528,9 +44573,9 @@ "questionFrontendId": "1183", "title": "Maximum Number of Ones", "content": null, - "likes": 167, - "dislikes": 30, - "stats": "{\"totalAccepted\": \"5.4K\", \"totalSubmission\": \"7.9K\", \"totalAcceptedRaw\": 5431, \"totalSubmissionRaw\": 7938, \"acRate\": \"68.4%\"}", + "likes": 168, + "dislikes": 31, + "stats": "{\"totalAccepted\": \"5.7K\", \"totalSubmission\": \"8.2K\", \"totalAcceptedRaw\": 5662, \"totalSubmissionRaw\": 8235, \"acRate\": \"68.8%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -44570,9 +44615,9 @@ "questionFrontendId": "1184", "title": "Distance Between Bus Stops", "content": "
A bus has n
stops numbered from 0
to n - 1
that form a circle. We know the distance between all pairs of neighboring stops where distance[i]
is the distance between the stops number i
and (i + 1) % n
.
The bus goes along both directions i.e. clockwise and counterclockwise.
\r\n\r\nReturn the shortest distance between the given start
and destination
stops.
\r\n
Example 1:
\r\n\r\n\r\nInput: distance = [1,2,3,4], start = 0, destination = 1\r\nOutput: 1\r\nExplanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\r\n\r\n
\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: distance = [1,2,3,4], start = 0, destination = 2\r\nOutput: 3\r\nExplanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\r\n\r\n\r\n
\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: distance = [1,2,3,4], start = 0, destination = 3\r\nOutput: 4\r\nExplanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= n <= 10^4
distance.length == n
0 <= start, destination < n
0 <= distance[i] <= 10^4
Given a date, return the corresponding day of the week for that date.
\n\nThe input is given as three integers representing the day
, month
and year
respectively.
Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
.
\n
Example 1:
\n\n\nInput: day = 31, month = 8, year = 2019\nOutput: "Saturday"\n\n\n
Example 2:
\n\n\nInput: day = 18, month = 7, year = 1999\nOutput: "Sunday"\n\n\n
Example 3:
\n\n\nInput: day = 15, month = 8, year = 1993\nOutput: "Sunday"\n\n\n
\n
Constraints:
\n\n1971
and 2100
.Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
\n\nNote that the subarray needs to be non-empty after deleting one element.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,-2,0,3]\nOutput: 4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.\n\n
Example 2:
\n\n\nInput: arr = [1,-2,-2,3]\nOutput: 3\nExplanation: We just choose [3] and it's the maximum sum.\n\n\n
Example 3:
\n\n\nInput: arr = [-1,-1,-1,-1]\nOutput: -1\nExplanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
-104 <= arr[i] <= 104
Given two integer arrays arr1
and arr2
, return the minimum number of operations (possibly zero) needed to make arr1
strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length
and 0 <= j < arr2.length
and do the assignment arr1[i] = arr2[j]
.
If there is no way to make arr1
strictly increasing, return -1
.
\n
Example 1:
\n\n\nInput: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\nOutput: 1\nExplanation: Replace\n\n5
with2
, thenarr1 = [1, 2, 3, 6, 7]
.\n
Example 2:
\n\n\nInput: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\nOutput: 2\nExplanation: Replace\n\n5
with3
and then replace3
with4
.arr1 = [1, 3, 4, 6, 7]
.\n
Example 3:
\n\n\nInput: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\nOutput: -1\nExplanation: You can't make arr1
strictly increasing.
\n\n\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9
\n", - "likes": 2272, + "likes": 2289, "dislikes": 50, - "stats": "{\"totalAccepted\": \"61K\", \"totalSubmission\": \"105.3K\", \"totalAcceptedRaw\": 60986, \"totalSubmissionRaw\": 105257, \"acRate\": \"57.9%\"}", + "stats": "{\"totalAccepted\": \"62.7K\", \"totalSubmission\": \"108.4K\", \"totalAcceptedRaw\": 62683, \"totalSubmissionRaw\": 108411, \"acRate\": \"57.8%\"}", "similarQuestions": "[{\"title\": \"Make Array Non-decreasing or Non-increasing\", \"titleSlug\": \"make-array-non-decreasing-or-non-increasing\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -44710,9 +44755,9 @@ "questionFrontendId": "1188", "title": "Design Bounded Blocking Queue", "content": null, - "likes": 526, + "likes": 532, "dislikes": 43, - "stats": "{\"totalAccepted\": \"56K\", \"totalSubmission\": \"77K\", \"totalAcceptedRaw\": 56029, \"totalSubmissionRaw\": 77020, \"acRate\": \"72.7%\"}", + "stats": "{\"totalAccepted\": \"59.7K\", \"totalSubmission\": \"81.8K\", \"totalAcceptedRaw\": 59707, \"totalSubmissionRaw\": 81784, \"acRate\": \"73.0%\"}", "similarQuestions": "[]", "categoryTitle": "Concurrency", "hints": [], @@ -44738,9 +44783,9 @@ "questionFrontendId": "1189", "title": "Maximum Number of Balloons", "content": "
Given a string text
, you want to use the characters of text
to form as many instances of the word "balloon" as possible.
You can use each character in text
at most once. Return the maximum number of instances that can be formed.
\n
Example 1:
\n\n\nInput: text = "nlaebolko"\nOutput: 1\n\n\n
Example 2:
\n\n\nInput: text = "loonbalxballpoon"\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: text = "leetcode"\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 104
text
consists of lower case English letters only.\n
Note: This question is the same as 2287: Rearrange Characters to Make Target String.
\n", - "likes": 1778, - "dislikes": 113, - "stats": "{\"totalAccepted\": \"255K\", \"totalSubmission\": \"427K\", \"totalAcceptedRaw\": 255010, \"totalSubmissionRaw\": 427025, \"acRate\": \"59.7%\"}", + "likes": 1804, + "dislikes": 115, + "stats": "{\"totalAccepted\": \"278.1K\", \"totalSubmission\": \"465.6K\", \"totalAcceptedRaw\": 278099, \"totalSubmissionRaw\": 465570, \"acRate\": \"59.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -44778,9 +44823,9 @@ "questionFrontendId": "1190", "title": "Reverse Substrings Between Each Pair of Parentheses", "content": "You are given a string s
that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
\n\nYour result should not contain any brackets.
\n\n\n
Example 1:
\n\n\nInput: s = "(abcd)"\nOutput: "dcba"\n\n\n
Example 2:
\n\n\nInput: s = "(u(love)i)"\nOutput: "iloveu"\nExplanation: The substring "love" is reversed first, then the whole string is reversed.\n\n\n
Example 3:
\n\n\nInput: s = "(ed(et(oc))el)"\nOutput: "leetcode"\nExplanation: First, we reverse the substring "oc", then "etco", and finally, the whole string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2000
s
only contains lower case English characters and parentheses.Given an integer array arr
and an integer k
, modify the array by repeating it k
times.
For example, if arr = [1, 2]
and k = 3
then the modified array will be [1, 2, 1, 2, 1, 2]
.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0
and its sum in that case is 0
.
As the answer can be very large, return the answer modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: arr = [1,2], k = 3\nOutput: 9\n\n\n
Example 2:
\n\n\nInput: arr = [1,-2,1], k = 5\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: arr = [-1,-2], k = 7\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= k <= 105
-104 <= arr[i] <= 104
There are n
servers numbered from 0
to n - 1
connected by undirected server-to-server connections
forming a network where connections[i] = [ai, bi]
represents a connection between servers ai
and bi
. Any server can reach other servers directly or indirectly through the network.
A critical connection is a connection that, if removed, will make some servers unable to reach some other server.
\n\nReturn all critical connections in the network in any order.
\n\n\n
Example 1:
\n\nInput: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput: [[1,3]]\nExplanation: [[3,1]] is also accepted.\n\n\n
Example 2:
\n\n\nInput: n = 2, connections = [[0,1]]\nOutput: [[0,1]]\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
n - 1 <= connections.length <= 105
0 <= ai, bi <= n - 1
ai != bi
Table: Transactions
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| country | varchar |\n| state | enum |\n| amount | int |\n| trans_date | date |\n+---------------+---------+\nid is the primary key of this table.\nThe table has information about incoming transactions.\nThe state column is an enum of type ["approved", "declined"].\n\n\n
\n\n
Write an SQL query to find for each month and country, the number of transactions and their total amount, the number of approved transactions and their total amount.
\n\nReturn the result table in any order.
\n\nThe query result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTransactions table:\n+------+---------+----------+--------+------------+\n| id | country | state | amount | trans_date |\n+------+---------+----------+--------+------------+\n| 121 | US | approved | 1000 | 2018-12-18 |\n| 122 | US | declined | 2000 | 2018-12-19 |\n| 123 | US | approved | 2000 | 2019-01-01 |\n| 124 | DE | approved | 2000 | 2019-01-07 |\n+------+---------+----------+--------+------------+\nOutput: \n+----------+---------+-------------+----------------+--------------------+-----------------------+\n| month | country | trans_count | approved_count | trans_total_amount | approved_total_amount |\n+----------+---------+-------------+----------------+--------------------+-----------------------+\n| 2018-12 | US | 2 | 1 | 3000 | 1000 |\n| 2019-01 | US | 1 | 1 | 2000 | 2000 |\n| 2019-01 | DE | 1 | 1 | 2000 | 2000 |\n+----------+---------+-------------+----------------+--------------------+-----------------------+\n\n", - "likes": 1006, - "dislikes": 111, - "stats": "{\"totalAccepted\": \"308.2K\", \"totalSubmission\": \"528.1K\", \"totalAcceptedRaw\": 308160, \"totalSubmissionRaw\": 528128, \"acRate\": \"58.3%\"}", + "likes": 1099, + "dislikes": 120, + "stats": "{\"totalAccepted\": \"374.3K\", \"totalSubmission\": \"642K\", \"totalAcceptedRaw\": 374347, \"totalSubmissionRaw\": 642010, \"acRate\": \"58.3%\"}", "similarQuestions": "[{\"title\": \"Monthly Transactions II\", \"titleSlug\": \"monthly-transactions-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -44921,7 +44966,7 @@ "content": null, "likes": 151, "dislikes": 57, - "stats": "{\"totalAccepted\": \"22.4K\", \"totalSubmission\": \"45.3K\", \"totalAcceptedRaw\": 22434, \"totalSubmissionRaw\": 45270, \"acRate\": \"49.6%\"}", + "stats": "{\"totalAccepted\": \"23.3K\", \"totalSubmission\": \"46.8K\", \"totalAcceptedRaw\": 23327, \"totalSubmissionRaw\": 46780, \"acRate\": \"49.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -44950,9 +44995,9 @@ "questionFrontendId": "1195", "title": "Fizz Buzz Multithreaded", "content": "
You have the four functions:
\n\nprintFizz
that prints the word "fizz"
to the console,printBuzz
that prints the word "buzz"
to the console,printFizzBuzz
that prints the word "fizzbuzz"
to the console, andprintNumber
that prints a given integer to the console.You are given an instance of the class FizzBuzz
that has four functions: fizz
, buzz
, fizzbuzz
and number
. The same instance of FizzBuzz
will be passed to four different threads:
fizz()
that should output the word "fizz"
.buzz()
that should output the word "buzz"
.fizzbuzz()
that should output the word "fizzbuzz"
.number()
that should only output the integers.Modify the given class to output the series [1, 2, "fizz", 4, "buzz", ...]
where the ith
token (1-indexed) of the series is:
"fizzbuzz"
if i
is divisible by 3
and 5
,"fizz"
if i
is divisible by 3
and not 5
,"buzz"
if i
is divisible by 5
and not 3
, ori
if i
is not divisible by 3
or 5
.Implement the FizzBuzz
class:
FizzBuzz(int n)
Initializes the object with the number n
that represents the length of the sequence that should be printed.void fizz(printFizz)
Calls printFizz
to output "fizz"
.void buzz(printBuzz)
Calls printBuzz
to output "buzz"
.void fizzbuzz(printFizzBuzz)
Calls printFizzBuzz
to output "fizzbuzz"
.void number(printNumber)
Calls printnumber
to output the numbers.\n
Example 1:
\nInput: n = 15\nOutput: [1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"]\n
Example 2:
\nInput: n = 5\nOutput: [1,2,\"fizz\",4,\"buzz\"]\n\n
\n
Constraints:
\n\n1 <= n <= 50
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b]
follows
a, b
are from arr
a < b
b - a
equals to the minimum absolute difference of any two elements in arr
\n
Example 1:
\n\n\nInput: arr = [4,2,1,3]\nOutput: [[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\n\n
Example 2:
\n\n\nInput: arr = [1,3,6,10,15]\nOutput: [[1,3]]\n\n\n
Example 3:
\n\n\nInput: arr = [3,8,-10,23,19,-4,-14,27]\nOutput: [[-14,-10],[19,23],[23,27]]\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 105
-106 <= arr[i] <= 106
An ugly number is a positive integer that is divisible by a
, b
, or c
.
Given four integers n
, a
, b
, and c
, return the nth
ugly number.
\n
Example 1:
\n\n\nInput: n = 3, a = 2, b = 3, c = 5\nOutput: 4\nExplanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.\n\n\n
Example 2:
\n\n\nInput: n = 4, a = 2, b = 3, c = 4\nOutput: 6\nExplanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.\n\n\n
Example 3:
\n\n\nInput: n = 5, a = 2, b = 11, c = 13\nOutput: 10\nExplanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.\n\n\n
\n
Constraints:
\n\n1 <= n, a, b, c <= 109
1 <= a * b * c <= 1018
[1, 2 * 109]
.You are given a string s
, and an array of pairs of indices in the string pairs
where pairs[i] = [a, b]
indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs
any number of times.
Return the lexicographically smallest string that s
can be changed to after using the swaps.
\n
Example 1:
\n\n\nInput: s = "dcab", pairs = [[0,3],[1,2]]\nOutput: "bacd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[1] and s[2], s = "bacd"\n\n\n
Example 2:
\n\n\nInput: s = "dcab", pairs = [[0,3],[1,2],[0,2]]\nOutput: "abcd"\nExplaination: \nSwap s[0] and s[3], s = "bcad"\nSwap s[0] and s[2], s = "acbd"\nSwap s[1] and s[2], s = "abcd"\n\n
Example 3:
\n\n\nInput: s = "cba", pairs = [[0,1],[1,2]]\nOutput: "abc"\nExplaination: \nSwap s[0] and s[1], s = "bca"\nSwap s[1] and s[2], s = "bac"\nSwap s[0] and s[1], s = "abc"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 10^5
0 <= pairs.length <= 10^5
0 <= pairs[i][0], pairs[i][1] < s.length
s
only contains lower case English letters.There are n
items each belonging to zero or one of m
groups where group[i]
is the group that the i
-th item belongs to and it's equal to -1
if the i
-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.
Return a sorted list of the items such that:
\n\nbeforeItems[i]
is a list containing all the items that should come before the i
-th item in the sorted array (to the left of the i
-th item).Return any solution if there is more than one solution and return an empty list if there is no solution.
\n\n\n
Example 1:
\n\n\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\nOutput: [6,3,4,1,5,2,0,7]\n\n\n
Example 2:
\n\n\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\nOutput: []\nExplanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n\n\n
\n
Constraints:
\n\n1 <= m <= n <= 3 * 104
group.length == beforeItems.length == n
-1 <= group[i] <= m - 1
0 <= beforeItems[i].length <= n - 1
0 <= beforeItems[i][j] <= n - 1
i != beforeItems[i][j]
beforeItems[i]
does not contain duplicates elements.Table: Queue
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| person_id | int |\n| person_name | varchar |\n| weight | int |\n| turn | int |\n+-------------+---------+\nperson_id column contains unique values.\nThis table has the information about all people waiting for a bus.\nThe person_id and turn columns will contain all numbers from 1 to n, where n is the number of rows in the table.\nturn determines the order of which the people will board the bus, where turn=1 denotes the first person to board and turn=n denotes the last person to board.\nweight is the weight of the person in kilograms.\n\n\n
\n\n
There is a queue of people waiting to board a bus. However, the bus has a weight limit of 1000
kilograms, so there may be some people who cannot board.
Write a solution to find the person_name
of the last person that can fit on the bus without exceeding the weight limit. The test cases are generated such that the first person does not exceed the weight limit.
Note that only one person can board the bus at any given turn.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nQueue table:\n+-----------+-------------+--------+------+\n| person_id | person_name | weight | turn |\n+-----------+-------------+--------+------+\n| 5 | Alice | 250 | 1 |\n| 4 | Bob | 175 | 5 |\n| 3 | Alex | 350 | 2 |\n| 6 | John Cena | 400 | 3 |\n| 1 | Winston | 500 | 6 |\n| 2 | Marie | 200 | 4 |\n+-----------+-------------+--------+------+\nOutput: \n+-------------+\n| person_name |\n+-------------+\n| John Cena |\n+-------------+\nExplanation: The folowing table is ordered by the turn for simplicity.\n+------+----+-----------+--------+--------------+\n| Turn | ID | Name | Weight | Total Weight |\n+------+----+-----------+--------+--------------+\n| 1 | 5 | Alice | 250 | 250 |\n| 2 | 3 | Alex | 350 | 600 |\n| 3 | 6 | John Cena | 400 | 1000 | (last person to board)\n| 4 | 2 | Marie | 200 | 1200 | (cannot board)\n| 5 | 4 | Bob | 175 | ___ |\n| 6 | 1 | Winston | 500 | ___ |\n+------+----+-----------+--------+--------------+\n\n", - "likes": 836, - "dislikes": 39, - "stats": "{\"totalAccepted\": \"201.7K\", \"totalSubmission\": \"296.2K\", \"totalAcceptedRaw\": 201710, \"totalSubmissionRaw\": 296185, \"acRate\": \"68.1%\"}", + "likes": 914, + "dislikes": 44, + "stats": "{\"totalAccepted\": \"243.9K\", \"totalSubmission\": \"356.9K\", \"totalAcceptedRaw\": 243912, \"totalSubmissionRaw\": 356894, \"acRate\": \"68.3%\"}", "similarQuestions": "[{\"title\": \"Running Total for Different Genders\", \"titleSlug\": \"running-total-for-different-genders\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Number of Seniors and Juniors to Join the Company\", \"titleSlug\": \"the-number-of-seniors-and-juniors-to-join-the-company\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"The Number of Seniors and Juniors to Join the Company II\", \"titleSlug\": \"the-number-of-seniors-and-juniors-to-join-the-company-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -45351,9 +45396,9 @@ "questionFrontendId": "1205", "title": "Monthly Transactions II", "content": null, - "likes": 161, - "dislikes": 551, - "stats": "{\"totalAccepted\": \"25.1K\", \"totalSubmission\": \"60K\", \"totalAcceptedRaw\": 25143, \"totalSubmissionRaw\": 60005, \"acRate\": \"41.9%\"}", + "likes": 162, + "dislikes": 553, + "stats": "{\"totalAccepted\": \"26.4K\", \"totalSubmission\": \"62.9K\", \"totalAcceptedRaw\": 26412, \"totalSubmissionRaw\": 62905, \"acRate\": \"42.0%\"}", "similarQuestions": "[{\"title\": \"Monthly Transactions I\", \"titleSlug\": \"monthly-transactions-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -45382,9 +45427,9 @@ "questionFrontendId": "1206", "title": "Design Skiplist", "content": "
Design a Skiplist without using any built-in libraries.
\n\nA skiplist is a data structure that takes O(log(n))
time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.
For example, we have a Skiplist containing [30,40,50,60,70,90]
and we want to add 80
and 45
into it. The Skiplist works this way:
\nArtyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons
You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n)
. It can be proven that the average time complexity for each operation is O(log(n))
and space complexity is O(n)
.
See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list
\n\nImplement the Skiplist
class:
Skiplist()
Initializes the object of the skiplist.bool search(int target)
Returns true
if the integer target
exists in the Skiplist or false
otherwise.void add(int num)
Inserts the value num
into the SkipList.bool erase(int num)
Removes the value num
from the Skiplist and returns true
. If num
does not exist in the Skiplist, do nothing and return false
. If there exist multiple num
values, removing any one of them is fine.Note that duplicates may exist in the Skiplist, your code needs to handle this situation.
\n\n\n
Example 1:
\n\n\nInput\n["Skiplist", "add", "add", "add", "search", "add", "search", "erase", "erase", "search"]\n[[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]\nOutput\n[null, null, null, null, false, null, true, false, true, false]\n\nExplanation\nSkiplist skiplist = new Skiplist();\nskiplist.add(1);\nskiplist.add(2);\nskiplist.add(3);\nskiplist.search(0); // return False\nskiplist.add(4);\nskiplist.search(1); // return True\nskiplist.erase(0); // return False, 0 is not in skiplist.\nskiplist.erase(1); // return True\nskiplist.search(1); // return False, 1 has already been erased.\n\n
\n
Constraints:
\n\n0 <= num, target <= 2 * 104
5 * 104
calls will be made to search
, add
, and erase
.Given an array of integers arr
, return true
if the number of occurrences of each value in the array is unique or false
otherwise.
\n
Example 1:
\n\n\nInput: arr = [1,2,2,1,1,3]\nOutput: true\nExplanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n\n
Example 2:
\n\n\nInput: arr = [1,2]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
You are given two strings s
and t
of the same length and an integer maxCost
.
You want to change s
to t
. Changing the ith
character of s
to ith
character of t
costs |s[i] - t[i]|
(i.e., the absolute difference between the ASCII values of the characters).
Return the maximum length of a substring of s
that can be changed to be the same as the corresponding substring of t
with a cost less than or equal to maxCost
. If there is no substring from s
that can be changed to its corresponding substring from t
, return 0
.
\n
Example 1:
\n\n\nInput: s = "abcd", t = "bcdf", maxCost = 3\nOutput: 3\nExplanation: "abc" of s can change to "bcd".\nThat costs 3, so the maximum length is 3.\n\n\n
Example 2:
\n\n\nInput: s = "abcd", t = "cdef", maxCost = 3\nOutput: 1\nExplanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.\n\n\n
Example 3:
\n\n\nInput: s = "abcd", t = "acde", maxCost = 0\nOutput: 1\nExplanation: You cannot make any change, so the maximum length is 1.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
t.length == s.length
0 <= maxCost <= 106
s
and t
consist of only lowercase English letters.You are given a string s
and an integer k
, a k
duplicate removal consists of choosing k
adjacent and equal letters from s
and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make k
duplicate removals on s
until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.
\n\n\n
Example 1:
\n\n\nInput: s = "abcd", k = 2\nOutput: "abcd"\nExplanation: There's nothing to delete.\n\n
Example 2:
\n\n\nInput: s = "deeedbbcccbdaa", k = 3\nOutput: "aa"\nExplanation: \nFirst delete "eee" and "ccc", get "ddbbbdaa"\nThen delete "bbb", get "dddaa"\nFinally delete "ddd", get "aa"\n\n
Example 3:
\n\n\nInput: s = "pbbcggttciiippooaais", k = 2\nOutput: "ps"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
2 <= k <= 104
s
only contains lowercase English letters.In an n*n
grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0)
and (0, 1)
. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2)
and (n-1, n-1)
.
In one move the snake can:
\n\n(r, c)
and (r, c+1)
to (r, c)
and (r+1, c)
.(r, c)
and (r+1, c)
to (r, c)
and (r, c+1)
.Return the minimum number of moves to reach the target.
\n\nIf there is no way to reach the target, return -1
.
\n
Example 1:
\n\n\nInput: grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n [0,0,0,0,1,1],\n [0,0,1,0,1,0],\n [0,1,1,0,0,0],\n [0,1,1,0,0,0]]\nOutput: 11\nExplanation:\nOne possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n\n\n
Example 2:
\n\n\nInput: grid = [[0,0,1,1,1,1],\n [0,0,0,0,1,1],\n [1,1,0,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,0]]\nOutput: 9\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
0 <= grid[i][j] <= 1
Table: Queries
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| query_name | varchar |\n| result | varchar |\n| position | int |\n| rating | int |\n+-------------+---------+\nThis table may have duplicate rows.\nThis table contains information collected from some queries on a database.\nThe\n\nposition
column has a value from 1 to 500.\nTherating
column has a value from 1 to 5. Query withrating
less than 3 is a poor query.\n
\n\n
We define query quality
as:
\n\n\nThe average of the ratio between query rating and its position.
\n
We also define poor query percentage
as:
\n\n\nThe percentage of all queries with rating less than 3.
\n
Write a solution to find each query_name
, the quality
and poor_query_percentage
.
Both quality
and poor_query_percentage
should be rounded to 2 decimal places.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nQueries table:\n+------------+-------------------+----------+--------+\n| query_name | result | position | rating |\n+------------+-------------------+----------+--------+\n| Dog | Golden Retriever | 1 | 5 |\n| Dog | German Shepherd | 2 | 5 |\n| Dog | Mule | 200 | 1 |\n| Cat | Shirazi | 5 | 2 |\n| Cat | Siamese | 3 | 3 |\n| Cat | Sphynx | 7 | 4 |\n+------------+-------------------+----------+--------+\nOutput: \n+------------+---------+-----------------------+\n| query_name | quality | poor_query_percentage |\n+------------+---------+-----------------------+\n| Dog | 2.50 | 33.33 |\n| Cat | 0.66 | 33.33 |\n+------------+---------+-----------------------+\nExplanation: \nDog queries quality is ((5 / 1) + (5 / 2) + (1 / 200)) / 3 = 2.50\nDog queries poor_ query_percentage is (1 / 3) * 100 = 33.33\n\nCat queries quality equals ((2 / 5) + (3 / 3) + (4 / 7)) / 3 = 0.66\nCat queries poor_ query_percentage is (1 / 3) * 100 = 33.33\n\n", - "likes": 787, - "dislikes": 477, - "stats": "{\"totalAccepted\": \"305.4K\", \"totalSubmission\": \"674.6K\", \"totalAcceptedRaw\": 305356, \"totalSubmissionRaw\": 674625, \"acRate\": \"45.3%\"}", + "likes": 880, + "dislikes": 504, + "stats": "{\"totalAccepted\": \"371.9K\", \"totalSubmission\": \"771.5K\", \"totalAcceptedRaw\": 371933, \"totalSubmissionRaw\": 771549, \"acRate\": \"48.2%\"}", "similarQuestions": "[{\"title\": \"Percentage of Users Attended a Contest\", \"titleSlug\": \"percentage-of-users-attended-a-contest\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -45595,9 +45640,9 @@ "questionFrontendId": "1212", "title": "Team Scores in Football Tournament", "content": null, - "likes": 318, - "dislikes": 25, - "stats": "{\"totalAccepted\": \"44.5K\", \"totalSubmission\": \"79.8K\", \"totalAcceptedRaw\": 44492, \"totalSubmissionRaw\": 79824, \"acRate\": \"55.7%\"}", + "likes": 321, + "dislikes": 26, + "stats": "{\"totalAccepted\": \"47.5K\", \"totalSubmission\": \"85K\", \"totalAcceptedRaw\": 47472, \"totalSubmissionRaw\": 85013, \"acRate\": \"55.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -45623,9 +45668,9 @@ "questionFrontendId": "1213", "title": "Intersection of Three Sorted Arrays", "content": null, - "likes": 614, + "likes": 615, "dislikes": 26, - "stats": "{\"totalAccepted\": \"97.8K\", \"totalSubmission\": \"122K\", \"totalAcceptedRaw\": 97812, \"totalSubmissionRaw\": 122019, \"acRate\": \"80.2%\"}", + "stats": "{\"totalAccepted\": \"99.9K\", \"totalSubmission\": \"124.7K\", \"totalAcceptedRaw\": 99876, \"totalSubmissionRaw\": 124701, \"acRate\": \"80.1%\"}", "similarQuestions": "[{\"title\": \"Intersection of Two Arrays\", \"titleSlug\": \"intersection-of-two-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Intersection of Multiple Arrays\", \"titleSlug\": \"intersection-of-multiple-arrays\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -45666,9 +45711,9 @@ "questionFrontendId": "1214", "title": "Two Sum BSTs", "content": null, - "likes": 558, + "likes": 563, "dislikes": 46, - "stats": "{\"totalAccepted\": \"52.6K\", \"totalSubmission\": \"78.2K\", \"totalAcceptedRaw\": 52636, \"totalSubmissionRaw\": 78235, \"acRate\": \"67.3%\"}", + "stats": "{\"totalAccepted\": \"54.7K\", \"totalSubmission\": \"81.2K\", \"totalAcceptedRaw\": 54723, \"totalSubmissionRaw\": 81212, \"acRate\": \"67.4%\"}", "similarQuestions": "[{\"title\": \"Two Sum IV - Input is a BST\", \"titleSlug\": \"two-sum-iv-input-is-a-bst\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -45719,9 +45764,9 @@ "questionFrontendId": "1215", "title": "Stepping Numbers", "content": null, - "likes": 185, + "likes": 186, "dislikes": 21, - "stats": "{\"totalAccepted\": \"10.2K\", \"totalSubmission\": \"21.5K\", \"totalAcceptedRaw\": 10232, \"totalSubmissionRaw\": 21534, \"acRate\": \"47.5%\"}", + "stats": "{\"totalAccepted\": \"10.5K\", \"totalSubmission\": \"22.1K\", \"totalAcceptedRaw\": 10532, \"totalSubmissionRaw\": 22097, \"acRate\": \"47.7%\"}", "similarQuestions": "[{\"title\": \"Count Stepping Numbers in Range\", \"titleSlug\": \"count-stepping-numbers-in-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -45757,9 +45802,9 @@ "questionFrontendId": "1216", "title": "Valid Palindrome III", "content": null, - "likes": 803, + "likes": 821, "dislikes": 14, - "stats": "{\"totalAccepted\": \"90.2K\", \"totalSubmission\": \"183.7K\", \"totalAcceptedRaw\": 90225, \"totalSubmissionRaw\": 183666, \"acRate\": \"49.1%\"}", + "stats": "{\"totalAccepted\": \"100.1K\", \"totalSubmission\": \"203.8K\", \"totalAcceptedRaw\": 100063, \"totalSubmissionRaw\": 203842, \"acRate\": \"49.1%\"}", "similarQuestions": "[{\"title\": \"Valid Palindrome II\", \"titleSlug\": \"valid-palindrome-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Valid Palindrome IV\", \"titleSlug\": \"valid-palindrome-iv\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -45796,9 +45841,9 @@ "questionFrontendId": "1217", "title": "Minimum Cost to Move Chips to The Same Position", "content": "
We have n
chips, where the position of the ith
chip is position[i]
.
We need to move all the chips to the same position. In one step, we can change the position of the ith
chip from position[i]
to:
position[i] + 2
or position[i] - 2
with cost = 0
.position[i] + 1
or position[i] - 1
with cost = 1
.Return the minimum cost needed to move all the chips to the same position.
\n\n\n
Example 1:
\n\nInput: position = [1,2,3]\nOutput: 1\nExplanation: First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.\n\n\n
Example 2:
\n\nInput: position = [2,2,2,3,3]\nOutput: 2\nExplanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.\n\n\n
Example 3:
\n\n\nInput: position = [1,1000000000]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= position.length <= 100
1 <= position[i] <= 10^9
Given an integer array arr
and an integer difference
, return the length of the longest subsequence in arr
which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference
.
A subsequence is a sequence that can be derived from arr
by deleting some or no elements without changing the order of the remaining elements.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4], difference = 1\nOutput: 4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].\n\n
Example 2:
\n\n\nInput: arr = [1,3,5,7], difference = 1\nOutput: 1\nExplanation: The longest arithmetic subsequence is any single element.\n\n\n
Example 3:
\n\n\nInput: arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput: 4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
-104 <= arr[i], difference <= 104
In a gold mine grid
of size m x n
, each cell in this mine has an integer representing the amount of gold in that cell, 0
if it is empty.
Return the maximum amount of gold you can collect under the conditions:
\n\n0
gold.\n
Example 1:
\n\n\nInput: grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput: 24\nExplanation:\n[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.\n\n\n
Example 2:
\n\n\nInput: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput: 28\nExplanation:\n[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 15
0 <= grid[i][j] <= 100
Given an integer n
, your task is to count how many strings of length n
can be formed under the following rules:
'a'
, 'e'
, 'i'
, 'o'
, 'u'
)'a'
may only be followed by an 'e'
.'e'
may only be followed by an 'a'
or an 'i'
.'i'
may not be followed by another 'i'
.'o'
may only be followed by an 'i'
or a 'u'
.'u'
may only be followed by an 'a'
.Since the answer may be too large, return it modulo 10^9 + 7
.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 5\nExplanation: All possible strings are: "a", "e", "i" , "o" and "u".\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 10\nExplanation: All possible strings are: "ae", "ea", "ei", "ia", "ie", "io", "iu", "oi", "ou" and "ua".\n\n\n
Example 3:
\n\n\nInput: n = 5\nOutput: 68\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 10^4
Balanced strings are those that have an equal quantity of 'L'
and 'R'
characters.
Given a balanced string s
, split it into some number of substrings such that:
Return the maximum number of balanced strings you can obtain.
\n\n\n
Example 1:
\n\n\nInput: s = "RLRRLLRLRL"\nOutput: 4\nExplanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.\n\n\n
Example 2:
\n\n\nInput: s = "RLRRRLLRLL"\nOutput: 2\nExplanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced.\n\n
Example 3:
\n\n\nInput: s = "LLLLRRRR"\nOutput: 1\nExplanation: s can be split into "LLLLRRRR".\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 1000
s[i]
is either 'L'
or 'R'
.s
is a balanced string.On a 0-indexed 8 x 8
chessboard, there can be multiple black queens and one white king.
You are given a 2D integer array queens
where queens[i] = [xQueeni, yQueeni]
represents the position of the ith
black queen on the chessboard. You are also given an integer array king
of length 2
where king = [xKing, yKing]
represents the position of the white king.
Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
\n\n\n
Example 1:
\n\nInput: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput: [[0,1],[1,0],[3,3]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\n\n\n
Example 2:
\n\nInput: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput: [[2,2],[3,4],[4,4]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\n\n\n
\n
Constraints:
\n\n1 <= queens.length < 64
queens[i].length == king.length == 2
0 <= xQueeni, yQueeni, xKing, yKing < 8
A die simulator generates a random number from 1
to 6
for each roll. You introduced a constraint to the generator such that it cannot roll the number i
more than rollMax[i]
(1-indexed) consecutive times.
Given an array of integers rollMax
and an integer n
, return the number of distinct sequences that can be obtained with exact n
rolls. Since the answer may be too large, return it modulo 109 + 7
.
Two sequences are considered different if at least one element differs from each other.
\n\n\n
Example 1:
\n\n\nInput: n = 2, rollMax = [1,1,2,2,2,3]\nOutput: 34\nExplanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n\n\n
Example 2:
\n\n\nInput: n = 2, rollMax = [1,1,1,1,1,1]\nOutput: 30\n\n\n
Example 3:
\n\n\nInput: n = 3, rollMax = [1,1,1,2,2,3]\nOutput: 181\n\n\n
\n
Constraints:
\n\n1 <= n <= 5000
rollMax.length == 6
1 <= rollMax[i] <= 15
Given an array nums
of positive integers, return the longest possible length of an array prefix of nums
, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
\n\n\n
Example 1:
\n\n\nInput: nums = [2,2,1,1,5,3,3,5]\nOutput: 7\nExplanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput: 13\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 105
Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.
\n\nEach philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.
\n\nEating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.
\n\nDesign a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.
\n\nThe problem statement and the image above are taken from wikipedia.org
\n\n\n\n
The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork)
where:
philosopher
is the id of the philosopher who wants to eat.pickLeftFork
and pickRightFork
are functions you can call to pick the corresponding forks of that philosopher.eat
is a function you can call to let the philosopher eat once he has picked both forks.putLeftFork
and putRightFork
are functions you can call to put down the corresponding forks of that philosopher.Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.
\n\n\n
Example 1:
\n\n\nInput: n = 1\nOutput: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]\nExplanation:\nn is the number of times each philosopher will call the function.\nThe output array describes the calls you made to the functions controlling the forks and the eat function, its format is:\noutput[i] = [a, b, c] (three integers)\n- a is the id of a philosopher.\n- b specifies the fork: {1 : left, 2 : right}.\n- c specifies the operation: {1 : pick, 2 : put, 3 : eat}.\n\n
\n
Constraints:
\n\n1 <= n <= 60
n
passengers board an airplane with exactly n
seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:
Return the probability that the nth
person gets his own seat.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 1.00000\nExplanation: The first person can only get the first seat.\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 0.50000\nExplanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given an array coordinates
, coordinates[i] = [x, y]
, where [x, y]
represents the coordinate of a point. Check if these points make a straight line in the XY plane.
\n\n
\n
Example 1:
\n\n\nInput: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput: true\n\n\n
Example 2:
\n\n\nInput: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput: false\n\n\n
\n
Constraints:
\n\n2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates
contains no duplicate point.Given a list of folders folder
, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i]
is located within another folder[j]
, it is called a sub-folder of it. A sub-folder of folder[j]
must start with folder[j]
, followed by a "/"
. For example, "/a/b"
is a sub-folder of "/a"
, but "/b"
is not a sub-folder of "/a/b/c"
.
The format of a path is one or more concatenated strings of the form: '/'
followed by one or more lowercase English letters.
"/leetcode"
and "/leetcode/problems"
are valid paths while an empty string and "/"
are not.\n
Example 1:
\n\n\nInput: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]\nOutput: ["/a","/c/d","/c/f"]\nExplanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.\n\n\n
Example 2:
\n\n\nInput: folder = ["/a","/a/b/c","/a/b/d"]\nOutput: ["/a"]\nExplanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".\n\n\n
Example 3:
\n\n\nInput: folder = ["/a/b/c","/a/b/ca","/a/b/d"]\nOutput: ["/a/b/c","/a/b/ca","/a/b/d"]\n\n\n
\n
Constraints:
\n\n1 <= folder.length <= 4 * 104
2 <= folder[i].length <= 100
folder[i]
contains only lowercase letters and '/'
.folder[i]
always starts with the character '/'
.You are given a string s of length n
containing only four kinds of characters: 'Q'
, 'W'
, 'E'
, and 'R'
.
A string is said to be balanced if each of its characters appears n / 4
times where n
is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make s
balanced. If s is already balanced, return 0
.
\n
Example 1:
\n\n\nInput: s = "QWER"\nOutput: 0\nExplanation: s is already balanced.\n\n\n
Example 2:
\n\n\nInput: s = "QQWE"\nOutput: 1\nExplanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.\n\n\n
Example 3:
\n\n\nInput: s = "QQQW"\nOutput: 2\nExplanation: We can replace the first "QQ" to "ER". \n\n\n
\n
Constraints:
\n\nn == s.length
4 <= n <= 105
n
is a multiple of 4
.s
contains only 'Q'
, 'W'
, 'E'
, and 'R'
.We have n
jobs, where every job is scheduled to be done from startTime[i]
to endTime[i]
, obtaining a profit of profit[i]
.
You're given the startTime
, endTime
and profit
arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time X
you will be able to start another job that starts at time X
.
\n
Example 1:
\n\n\nInput: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\nOutput: 120\nExplanation: The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n\n\n
Example 2:
\n\n
\nInput: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\nOutput: 150\nExplanation: The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.\n\n\n
Example 3:
\n\n\nInput: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\nOutput: 6\n\n\n
\n
Constraints:
\n\n1 <= startTime.length == endTime.length == profit.length <= 5 * 104
1 <= startTime[i] < endTime[i] <= 109
1 <= profit[i] <= 104
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.:
\n\nf(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
\n\n\ninterface CustomFunction {\npublic:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n};\n\n\n
We will judge your solution as follows:
\n\n9
hidden implementations of CustomFunction
, along with a way to generate an answer key of all valid pairs for a specific z
.function_id
(to determine which implementation to test your code with), and the target z
.findSolution
and compare your results with the answer key.Accepted
.\n
Example 1:
\n\n\nInput: function_id = 1, z = 5\nOutput: [[1,4],[2,3],[3,2],[4,1]]\nExplanation: The hidden formula for function_id = 1 is f(x, y) = x + y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=4 -> f(1, 4) = 1 + 4 = 5.\nx=2, y=3 -> f(2, 3) = 2 + 3 = 5.\nx=3, y=2 -> f(3, 2) = 3 + 2 = 5.\nx=4, y=1 -> f(4, 1) = 4 + 1 = 5.\n\n\n
Example 2:
\n\n\nInput: function_id = 2, z = 5\nOutput: [[1,5],[5,1]]\nExplanation: The hidden formula for function_id = 2 is f(x, y) = x * y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=5 -> f(1, 5) = 1 * 5 = 5.\nx=5, y=1 -> f(5, 1) = 5 * 1 = 5.\n\n\n
\n
Constraints:
\n\n1 <= function_id <= 9
1 <= z <= 100
f(x, y) == z
will be in the range 1 <= x, y <= 1000
.f(x, y)
will fit in 32 bit signed integer if 1 <= x, y <= 1000
.Given 2 integers n
and start
. Your task is return any permutation p
of (0,1,2.....,2^n -1)
such that :
p[0] = start
p[i]
and p[i+1]
differ by only one bit in their binary representation.p[0]
and p[2^n -1]
must also differ by only one bit in their binary representation.\r\n
Example 1:
\r\n\r\n\r\nInput: n = 2, start = 3\r\nOutput: [3,2,0,1]\r\nExplanation: The binary representation of the permutation is (11,10,00,01). \r\nAll the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: n = 3, start = 2\r\nOutput: [2,6,7,5,4,0,1,3]\r\nExplanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= n <= 16
0 <= start < 2 ^ n
You are given an array of strings arr
. A string s
is formed by the concatenation of a subsequence of arr
that has unique characters.
Return the maximum possible length of s
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: arr = ["un","iq","ue"]\nOutput: 4\nExplanation: All the valid concatenations are:\n- ""\n- "un"\n- "iq"\n- "ue"\n- "uniq" ("un" + "iq")\n- "ique" ("iq" + "ue")\nMaximum length is 4.\n\n\n
Example 2:
\n\n\nInput: arr = ["cha","r","act","ers"]\nOutput: 6\nExplanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").\n\n\n
Example 3:
\n\n\nInput: arr = ["abcdefghijklmnopqrstuvwxyz"]\nOutput: 26\nExplanation: The only string in arr has all 26 characters.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i]
contains only lowercase English letters.Given a rectangle of size n
x m
, return the minimum number of integer-sided squares that tile the rectangle.
\n
Example 1:
\n\n\nInput: n = 2, m = 3\nOutput: 3\nExplanation:\n\n3
squares are necessary to cover the rectangle.\n2
(squares of1x1
)\n1
(square of2x2
)
Example 2:
\n\n\nInput: n = 5, m = 8\nOutput: 5\n\n\n
Example 3:
\n\n\nInput: n = 11, m = 13\nOutput: 6\n\n\n
\n
Constraints:
\n\n1 <= n, m <= 13
You are given two strings s1
and s2
of equal length consisting of letters "x"
and "y"
only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i]
and s2[j]
.
Return the minimum number of swaps required to make s1
and s2
equal, or return -1
if it is impossible to do so.
\n
Example 1:
\n\n\nInput: s1 = "xx", s2 = "yy"\nOutput: 1\nExplanation: Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".\n\n\n
Example 2:
\n\n\nInput: s1 = "xy", s2 = "yx"\nOutput: 2\nExplanation: Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".\nSwap s1[0] and s2[1], s1 = "xy", s2 = "xy".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.\n\n\n
Example 3:
\n\n\nInput: s1 = "xx", s2 = "xy"\nOutput: -1\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 1000
s1.length == s2.length
s1, s2
only contain 'x'
or 'y'
.Given an array of integers nums
and an integer k
. A continuous subarray is called nice if there are k
odd numbers on it.
Return the number of nice sub-arrays.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There are no odd numbers in the array.\n\n\n
Example 3:
\n\n\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length
Given a string s of '('
, ')'
and lowercase English characters.
Your task is to remove the minimum number of parentheses ( '('
or ')'
, in any positions ) so that the resulting parentheses string is valid and return any valid string.
Formally, a parentheses string is valid if and only if:
\n\nAB
(A
concatenated with B
), where A
and B
are valid strings, or(A)
, where A
is a valid string.\n
Example 1:
\n\n\nInput: s = "lee(t(c)o)de)"\nOutput: "lee(t(c)o)de"\nExplanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.\n\n\n
Example 2:
\n\n\nInput: s = "a)b(c)d"\nOutput: "ab(c)d"\n\n\n
Example 3:
\n\n\nInput: s = "))(("\nOutput: ""\nExplanation: An empty string is also valid.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '('
, ')'
, or lowercase English letter.Given an array nums
of positive integers. Your task is to select some subset of nums
, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1
from the array by any possible subset and multiplicand.
Return True
if the array is good otherwise return False
.
\n
Example 1:
\n\n\nInput: nums = [12,5,7,23]\nOutput: true\nExplanation: Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1\n\n\n
Example 2:
\n\n\nInput: nums = [29,6,10]\nOutput: true\nExplanation: Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1\n\n\n
Example 3:
\n\n\nInput: nums = [3,6]\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Table: Prices
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| start_date | date |\n| end_date | date |\n| price | int |\n+---------------+---------+\n(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.\nEach row of this table indicates the price of the product_id in the period from start_date to end_date.\nFor each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.\n\n\n
\n\n
Table: UnitsSold
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| purchase_date | date |\n| units | int |\n+---------------+---------+\nThis table may contain duplicate rows.\nEach row of this table indicates the date, units, and product_id of each product sold. \n\n\n
\n\n
Write a solution to find the average selling price for each product. average_price
should be rounded to 2 decimal places. If a product does not have any sold units, its average selling price is assumed to be 0.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nPrices table:\n+------------+------------+------------+--------+\n| product_id | start_date | end_date | price |\n+------------+------------+------------+--------+\n| 1 | 2019-02-17 | 2019-02-28 | 5 |\n| 1 | 2019-03-01 | 2019-03-22 | 20 |\n| 2 | 2019-02-01 | 2019-02-20 | 15 |\n| 2 | 2019-02-21 | 2019-03-31 | 30 |\n+------------+------------+------------+--------+\nUnitsSold table:\n+------------+---------------+-------+\n| product_id | purchase_date | units |\n+------------+---------------+-------+\n| 1 | 2019-02-25 | 100 |\n| 1 | 2019-03-01 | 15 |\n| 2 | 2019-02-10 | 200 |\n| 2 | 2019-03-22 | 30 |\n+------------+---------------+-------+\nOutput: \n+------------+---------------+\n| product_id | average_price |\n+------------+---------------+\n| 1 | 6.96 |\n| 2 | 16.96 |\n+------------+---------------+\nExplanation: \nAverage selling price = Total Price of Product / Number of products sold.\nAverage selling price for product 1 = ((100 * 5) + (15 * 20)) / 115 = 6.96\nAverage selling price for product 2 = ((200 * 15) + (30 * 30)) / 230 = 16.96\n\n", - "likes": 1417, - "dislikes": 206, - "stats": "{\"totalAccepted\": \"393.3K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 393285, \"totalSubmissionRaw\": 1062553, \"acRate\": \"37.0%\"}", + "likes": 1585, + "dislikes": 222, + "stats": "{\"totalAccepted\": \"472.6K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 472576, \"totalSubmissionRaw\": 1284582, \"acRate\": \"36.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -47115,9 +47160,9 @@ "questionFrontendId": "1252", "title": "Cells with Odd Values in a Matrix", "content": "
There is an m x n
matrix that is initialized to all 0
's. There is also a 2D array indices
where each indices[i] = [ri, ci]
represents a 0-indexed location to perform some increment operations on the matrix.
For each location indices[i]
, do both of the following:
ri
.ci
.Given m
, n
, and indices
, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices
.
\n
Example 1:
\n\nInput: m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput: 6\nExplanation: Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.\n\n\n
Example 2:
\n\nInput: m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput: 0\nExplanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 50
1 <= indices.length <= 100
0 <= ri < m
0 <= ci < n
\n
Follow up: Could you solve this in O(n + m + indices.length)
time with only O(n + m)
extra space?
Given the following details of a matrix with n
columns and 2
rows :
0
or 1
.upper
.lower
.colsum[i]
, where colsum
is given as an integer array with length n
.Your task is to reconstruct the matrix with upper
, lower
and colsum
.
Return it as a 2-D integer array.
\n\nIf there are more than one valid solution, any of them will be accepted.
\n\nIf no valid solution exists, return an empty 2-D array.
\n\n\n
Example 1:
\n\n\nInput: upper = 2, lower = 1, colsum = [1,1,1]\nOutput: [[1,1,0],[0,0,1]]\nExplanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.\n\n\n
Example 2:
\n\n\nInput: upper = 2, lower = 3, colsum = [2,2,1,1]\nOutput: []\n\n\n
Example 3:
\n\n\nInput: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]\nOutput: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]\n\n\n
\n
Constraints:
\n\n1 <= colsum.length <= 10^5
0 <= upper, lower <= colsum.length
0 <= colsum[i] <= 2
Given a 2D grid
consists of 0s
(land) and 1s
(water). An island is a maximal 4-directionally connected group of 0s
and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.
Return the number of closed islands.
\n\n\n
Example 1:
\n\n\nInput: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput: 2\nExplanation: \nIslands in gray are closed because they are completely surrounded by water (group of 1s).\n\n
Example 2:
\n\n\nInput: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,1,1,1,1,1],\n [1,0,0,0,0,0,1],\n [1,0,1,1,1,0,1],\n [1,0,1,0,1,0,1],\n [1,0,1,1,1,0,1],\n [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput: 2\n\n\n
\n
Constraints:
\n\n1 <= grid.length, grid[0].length <= 100
0 <= grid[i][j] <=1
Given a list of words
, list of single letters
(might be repeating) and score
of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i]
cannot be used two or more times).
It is not necessary to use all characters in letters
and each letter can only be used once. Score of letters 'a'
, 'b'
, 'c'
, ... ,'z'
is given by score[0]
, score[1]
, ... , score[25]
respectively.
\n
Example 1:
\n\n\nInput: words = ["dog","cat","dad","good"], letters = ["a","a","c","d","d","d","g","o","o"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput: 23\nExplanation:\nScore a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words "dad" (5+1+5) and "good" (3+2+2+5) with a score of 23.\nWords "dad" and "dog" only get a score of 21.\n\n
Example 2:
\n\n\nInput: words = ["xxxz","ax","bx","cx"], letters = ["z","a","b","c","x","x","x"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput: 27\nExplanation:\nScore a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words "ax" (4+5), "bx" (4+5) and "cx" (4+5) with a score of 27.\nWord "xxxz" only get a score of 25.\n\n
Example 3:
\n\n\nInput: words = ["leetcode"], letters = ["l","e","t","c","o","d"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput: 0\nExplanation:\nLetter "e" can only be used once.\n\n
\n
Constraints:
\n\n1 <= words.length <= 14
1 <= words[i].length <= 15
1 <= letters.length <= 100
letters[i].length == 1
score.length == 26
0 <= score[i] <= 10
words[i]
, letters[i]
contains only lower case English letters.Given a 2D grid
of size m x n
and an integer k
. You need to shift the grid
k
times.
In one shift operation:
\n\ngrid[i][j]
moves to grid[i][j + 1]
.grid[i][n - 1]
moves to grid[i + 1][0]
.grid[m - 1][n - 1]
moves to grid[0][0]
.Return the 2D grid after applying shift operation k
times.
\n
Example 1:
\n\nInput: grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[9,1,2],[3,4,5],[6,7,8]]\n
\n\nExample 2:
\n\nInput: grid
= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n
\n\nExample 3:
\n\n\nInput: grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput: [[1,2,3],[4,5,6],[7,8,9]]\n
\n\n\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
Given a binary tree with the following rules:
\n\nroot.val == 0
treeNode.val == x
and treeNode.left != null
, then treeNode.left.val == 2 * x + 1
treeNode.val == x
and treeNode.right != null
, then treeNode.right.val == 2 * x + 2
Now the binary tree is contaminated, which means all treeNode.val
have been changed to -1
.
Implement the FindElements
class:
FindElements(TreeNode* root)
Initializes the object with a contaminated binary tree and recovers it.bool find(int target)
Returns true
if the target
value exists in the recovered binary tree.\n
Example 1:
\n\nInput\n["FindElements","find","find"]\n[[[-1,null,-1]],[1],[2]]\nOutput\n[null,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True\n\n
Example 2:
\n\nInput\n["FindElements","find","find","find"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]\nOutput\n[null,true,true,false]\nExplanation\nFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False\n\n
Example 3:
\n\nInput\n["FindElements","find","find","find","find"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\nOutput\n[null,true,false,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True\n\n\n
\n
Constraints:
\n\nTreeNode.val == -1
20
[1, 104]
find()
is between [1, 104]
0 <= target <= 106
Given a binary tree with the following rules:
\n\nroot.val == 0
treeNode
:\n\ttreeNode.val
has a value x
and treeNode.left != null
, then treeNode.left.val == 2 * x + 1
treeNode.val
has a value x
and treeNode.right != null
, then treeNode.right.val == 2 * x + 2
Now the binary tree is contaminated, which means all treeNode.val
have been changed to -1
.
Implement the FindElements
class:
FindElements(TreeNode* root)
Initializes the object with a contaminated binary tree and recovers it.bool find(int target)
Returns true
if the target
value exists in the recovered binary tree.\n
Example 1:
\n\nInput\n["FindElements","find","find"]\n[[[-1,null,-1]],[1],[2]]\nOutput\n[null,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1]); \nfindElements.find(1); // return False \nfindElements.find(2); // return True\n\n
Example 2:
\n\nInput\n["FindElements","find","find","find"]\n[[[-1,-1,-1,-1,-1]],[1],[3],[5]]\nOutput\n[null,true,true,false]\nExplanation\nFindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\nfindElements.find(1); // return True\nfindElements.find(3); // return True\nfindElements.find(5); // return False\n\n
Example 3:
\n\nInput\n["FindElements","find","find","find","find"]\n[[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\nOutput\n[null,true,false,false,true]\nExplanation\nFindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\nfindElements.find(2); // return True\nfindElements.find(3); // return False\nfindElements.find(4); // return False\nfindElements.find(5); // return True\n\n\n
\n
Constraints:
\n\nTreeNode.val == -1
20
[1, 104]
find()
is between [1, 104]
0 <= target <= 106
Given an integer array nums
, return the maximum possible sum of elements of the array such that it is divisible by three.
\n
Example 1:
\n\n\nInput: nums = [3,6,5,1,8]\nOutput: 18\nExplanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\n\n
Example 2:
\n\n\nInput: nums = [4]\nOutput: 0\nExplanation: Since 4 is not divisible by 3, do not pick any number.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,4]\nOutput: 12\nExplanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 4 * 104
1 <= nums[i] <= 104
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
\n\nThe game is represented by an m x n
grid of characters grid
where each element is a wall, floor, or box.
Your task is to move the box 'B'
to the target position 'T'
under the following rules:
'S'
represents the player. The player can move up, down, left, right in grid
if it is a floor (empty cell).'.'
represents the floor which means a free cell to walk.'#'
represents the wall which means an obstacle (impossible to walk there).'B'
and one target cell 'T'
in the grid
.Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1
.
\n
Example 1:
\n\nInput: grid = [["#","#","#","#","#","#"],\n ["#","T","#","#","#","#"],\n ["#",".",".","B",".","#"],\n ["#",".","#","#",".","#"],\n ["#",".",".",".","S","#"],\n ["#","#","#","#","#","#"]]\nOutput: 3\nExplanation: We return only the number of times the box is pushed.\n\n
Example 2:
\n\n\nInput: grid = [["#","#","#","#","#","#"],\n ["#","T","#","#","#","#"],\n ["#",".",".","B",".","#"],\n ["#","#","#","#",".","#"],\n ["#",".",".",".","S","#"],\n ["#","#","#","#","#","#"]]\nOutput: -1\n\n\n
Example 3:
\n\n\nInput: grid = [["#","#","#","#","#","#"],\n ["#","T",".",".","#","#"],\n ["#",".","#","B",".","#"],\n ["#",".",".",".",".","#"],\n ["#",".",".",".","S","#"],\n ["#","#","#","#","#","#"]]\nOutput: 5\nExplanation: push the box down, left, left, up and up.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 20
grid
contains only characters '.'
, '#'
, 'S'
, 'T'
, or 'B'
.'S'
, 'B'
, and 'T'
in the grid
.On a 2D plane, there are n
points with integer coordinates points[i] = [xi, yi]
. Return the minimum time in seconds to visit all the points in the order given by points
.
You can move according to these rules:
\n\n1
second, you can either:\n\n\tsqrt(2)
units (in other words, move one unit vertically then one unit horizontally in 1
second).\n
Example 1:
\n\nInput: points = [[1,1],[3,4],[-1,0]]\nOutput: 7\nExplanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] \nTime from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds\n\n
Example 2:
\n\n\nInput: points = [[3,2],[-2,2]]\nOutput: 5\n\n\n
\n
Constraints:
\n\npoints.length == n
1 <= n <= 100
points[i].length == 2
-1000 <= points[i][0], points[i][1] <= 1000
You are given a map of a server center, represented as a m * n
integer matrix grid
, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
\n
\nReturn the number of servers that communicate with any other server.
\n
Example 1:
\n\n\nInput: grid = [[1,0],[0,1]]\nOutput: 0\nExplanation: No servers can communicate with others.\n\n
Example 2:
\n\n\nInput: grid = [[1,0],[1,1]]\nOutput: 3\nExplanation: All three servers can communicate with at least one other server.\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput: 4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m <= 250
1 <= n <= 250
grid[i][j] == 0 or 1
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 return the three lexicographically minimums products.
Return a list of lists of the suggested products after each character of searchWord
is typed.
\n
Example 1:
\n\n\nInput: products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"\nOutput: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]\nExplanation: products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"].\nAfter typing m and mo all products match and we show user ["mobile","moneypot","monitor"].\nAfter typing mou, mous and mouse the system suggests ["mouse","mousepad"].\n\n\n
Example 2:
\n\n\nInput: products = ["havana"], searchWord = "havana"\nOutput: [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]\nExplanation: The only word "havana" will be always suggested while typing the search word.\n\n\n
\n
Constraints:
\n\n1 <= products.length <= 1000
1 <= products[i].length <= 3000
1 <= sum(products[i].length) <= 2 * 104
products
are unique.products[i]
consists of lowercase English letters.1 <= searchWord.length <= 1000
searchWord
consists of lowercase English letters.You have a pointer at index 0
in an array of size arrLen
. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers steps
and arrLen
, return the number of ways such that your pointer is still at index 0
after exactly steps
steps. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: steps = 3, arrLen = 2\nOutput: 4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay\n\n\n
Example 2:
\n\n\nInput: steps = 2, arrLen = 4\nOutput: 2\nExplanation: There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay\n\n\n
Example 3:
\n\n\nInput: steps = 4, arrLen = 2\nOutput: 8\n\n\n
\n
Constraints:
\n\n1 <= steps <= 500
1 <= arrLen <= 106
Tic-tac-toe is played by two players A
and B
on a 3 x 3
grid. The rules of Tic-Tac-Toe are:
' '
.A
always places 'X'
characters, while the second player B
always places 'O'
characters.'X'
and 'O'
characters are always placed into empty squares, never on filled ones.Given a 2D integer array moves
where moves[i] = [rowi, coli]
indicates that the ith
move will be played on grid[rowi][coli]
. return the winner of the game if it exists (A
or B
). In case the game ends in a draw return "Draw"
. If there are still movements to play return "Pending"
.
You can assume that moves
is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A
will play first.
\n
Example 1:
\n\nInput: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput: "A"\nExplanation: A wins, they always play first.\n\n\n
Example 2:
\n\nInput: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput: "B"\nExplanation: B wins.\n\n\n
Example 3:
\n\nInput: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput: "Draw"\nExplanation: The game ends in a draw since there are no moves to make.\n\n\n
\n
Constraints:
\n\n1 <= moves.length <= 9
moves[i].length == 2
0 <= rowi, coli <= 2
moves
.moves
follow the rules of tic tac toe.Given two integers tomatoSlices
and cheeseSlices
. The ingredients of different burgers are as follows:
4
tomato slices and 1
cheese slice.2
Tomato slices and 1
cheese slice.Return [total_jumbo, total_small]
so that the number of remaining tomatoSlices
equal to 0
and the number of remaining cheeseSlices
equal to 0
. If it is not possible to make the remaining tomatoSlices
and cheeseSlices
equal to 0
return []
.
\n
Example 1:
\n\n\nInput: tomatoSlices = 16, cheeseSlices = 7\nOutput: [1,6]\nExplantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.\n\n\n
Example 2:
\n\n\nInput: tomatoSlices = 17, cheeseSlices = 4\nOutput: []\nExplantion: There will be no way to use all ingredients to make small and jumbo burgers.\n\n\n
Example 3:
\n\n\nInput: tomatoSlices = 4, cheeseSlices = 17\nOutput: []\nExplantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n\n\n
\n
Constraints:
\n\n0 <= tomatoSlices, cheeseSlices <= 107
Given a m * n
matrix of ones and zeros, return how many square submatrices have all ones.
\n
Example 1:
\n\n\nInput: matrix =\n[\n [0,1,1,1],\n [1,1,1,1],\n [0,1,1,1]\n]\nOutput: 15\nExplanation: \nThere are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is 1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15.\n\n\n
Example 2:
\n\n\nInput: matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]\nOutput: 7\nExplanation: \nThere are 6 squares of side 1. \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 300
1 <= arr[0].length <= 300
0 <= arr[i][j] <= 1
You are given a string s
containing lowercase letters and an integer k
. You need to :
s
to other lowercase English letters.s
into k
non-empty disjoint substrings such that each substring is a palindrome.Return the minimal number of characters that you need to change to divide the string.
\n\n\n
Example 1:
\n\n\nInput: s = "abc", k = 2\nOutput: 1\nExplanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.\n\n\n
Example 2:
\n\n\nInput: s = "aabbc", k = 3\nOutput: 0\nExplanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.\n\n
Example 3:
\n\n\nInput: s = "leetcode", k = 8\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 100
.s
only contains lowercase English letters.Table: Students
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| student_id | int |\n| student_name | varchar |\n+---------------+---------+\nstudent_id is the primary key (column with unique values) for this table.\nEach row of this table contains the ID and the name of one student in the school.\n\n\n
\n\n
Table: Subjects
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| subject_name | varchar |\n+--------------+---------+\nsubject_name is the primary key (column with unique values) for this table.\nEach row of this table contains the name of one subject in the school.\n\n\n
\n\n
Table: Examinations
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| student_id | int |\n| subject_name | varchar |\n+--------------+---------+\nThere is no primary key (column with unique values) for this table. It may contain duplicates.\nEach student from the Students table takes every course from the Subjects table.\nEach row of this table indicates that a student with ID student_id attended the exam of subject_name.\n\n\n
\n\n
Write a solution to find the number of times each student attended each exam.
\n\nReturn the result table ordered by student_id
and subject_name
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nStudents table:\n+------------+--------------+\n| student_id | student_name |\n+------------+--------------+\n| 1 | Alice |\n| 2 | Bob |\n| 13 | John |\n| 6 | Alex |\n+------------+--------------+\nSubjects table:\n+--------------+\n| subject_name |\n+--------------+\n| Math |\n| Physics |\n| Programming |\n+--------------+\nExaminations table:\n+------------+--------------+\n| student_id | subject_name |\n+------------+--------------+\n| 1 | Math |\n| 1 | Physics |\n| 1 | Programming |\n| 2 | Programming |\n| 1 | Physics |\n| 1 | Math |\n| 13 | Math |\n| 13 | Programming |\n| 13 | Physics |\n| 2 | Math |\n| 1 | Math |\n+------------+--------------+\nOutput: \n+------------+--------------+--------------+----------------+\n| student_id | student_name | subject_name | attended_exams |\n+------------+--------------+--------------+----------------+\n| 1 | Alice | Math | 3 |\n| 1 | Alice | Physics | 2 |\n| 1 | Alice | Programming | 1 |\n| 2 | Bob | Math | 1 |\n| 2 | Bob | Physics | 0 |\n| 2 | Bob | Programming | 1 |\n| 6 | Alex | Math | 0 |\n| 6 | Alex | Physics | 0 |\n| 6 | Alex | Programming | 0 |\n| 13 | John | Math | 1 |\n| 13 | John | Physics | 1 |\n| 13 | John | Programming | 1 |\n+------------+--------------+--------------+----------------+\nExplanation: \nThe result table should contain all students and all subjects.\nAlice attended the Math exam 3 times, the Physics exam 2 times, and the Programming exam 1 time.\nBob attended the Math exam 1 time, the Programming exam 1 time, and did not attend the Physics exam.\nAlex did not attend any exams.\nJohn attended the Math exam 1 time, the Physics exam 1 time, and the Programming exam 1 time.\n\n", - "likes": 2190, - "dislikes": 270, - "stats": "{\"totalAccepted\": \"435.3K\", \"totalSubmission\": \"724.7K\", \"totalAcceptedRaw\": 435343, \"totalSubmissionRaw\": 724714, \"acRate\": \"60.1%\"}", + "likes": 2437, + "dislikes": 304, + "stats": "{\"totalAccepted\": \"529.3K\", \"totalSubmission\": \"875.1K\", \"totalAcceptedRaw\": 529292, \"totalSubmissionRaw\": 875085, \"acRate\": \"60.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -48248,9 +48296,9 @@ "questionFrontendId": "1281", "title": "Subtract the Product and Sum of Digits of an Integer", "content": "Given an integer number
n
, return the difference between the product of its digits and the sum of its digits.\n\n
Example 1:
\n\n\nInput: n = 234\nOutput: 15 \nExplanation: \nProduct of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15\n\n\n
Example 2:
\n\n\nInput: n = 4421\nOutput: 21\nExplanation: \nProduct of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21\n\n\n
\n
Constraints:
\n\n1 <= n <= 10^5
There are n
people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0
to n - 1
.
You are given an integer array groupSizes
, where groupSizes[i]
is the size of the group that person i
is in. For example, if groupSizes[1] = 3
, then person 1
must be in a group of size 3
.
Return a list of groups such that each person i
is in a group of size groupSizes[i]
.
Each person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.
\n\n\n
Example 1:
\n\n\nInput: groupSizes = [3,3,3,3,3,1,3]\nOutput: [[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\n\n\n
Example 2:
\n\n\nInput: groupSizes = [2,1,3,3,3,2]\nOutput: [[1],[0,5],[2,3,4]]\n\n\n
\n
Constraints:
\n\ngroupSizes.length == n
1 <= n <= 500
1 <= groupSizes[i] <= n
Given an array of integers nums
and an integer threshold
, we will choose a positive integer divisor
, divide all the array by it, and sum the division's result. Find the smallest divisor
such that the result mentioned above is less than or equal to threshold
.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3
and 10/2 = 5
).
The test cases are generated so that there will be an answer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,5,9], threshold = 6\nOutput: 5\nExplanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). \n\n\n
Example 2:
\n\n\nInput: nums = [44,22,33,11,1], threshold = 5\nOutput: 44\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106
Given a m x n
binary matrix mat
. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1
to 0
and 0
to 1
). A pair of cells are called neighbors if they share one edge.
Return the minimum number of steps required to convert mat
to a zero matrix or -1
if you cannot.
A binary matrix is a matrix with all cells equal to 0
or 1
only.
A zero matrix is a matrix with all cells equal to 0
.
\n
Example 1:
\n\nInput: mat = [[0,0],[0,1]]\nOutput: 3\nExplanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n\n\n
Example 2:
\n\n\nInput: mat = [[0]]\nOutput: 0\nExplanation: Given matrix is a zero matrix. We do not need to change it.\n\n\n
Example 3:
\n\n\nInput: mat = [[1,0,0],[1,0,0]]\nOutput: -1\nExplanation: Given matrix cannot be a zero matrix.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 3
mat[i][j]
is either 0
or 1
.Design the CombinationIterator
class:
CombinationIterator(string characters, int combinationLength)
Initializes the object with a string characters
of sorted distinct lowercase English letters and a number combinationLength
as arguments.next()
Returns the next combination of length combinationLength
in lexicographical order.hasNext()
Returns true
if and only if there exists a next combination.\n
Example 1:
\n\n\nInput\n["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]\n[["abc", 2], [], [], [], [], [], []]\nOutput\n[null, "ab", true, "ac", true, "bc", false]\n\nExplanation\nCombinationIterator itr = new CombinationIterator("abc", 2);\nitr.next(); // return "ab"\nitr.hasNext(); // return True\nitr.next(); // return "ac"\nitr.hasNext(); // return True\nitr.next(); // return "bc"\nitr.hasNext(); // return False\n\n\n
\n
Constraints:
\n\n1 <= combinationLength <= characters.length <= 15
characters
are unique.104
calls will be made to next
and hasNext
.next
are valid.Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,2,2,6,6,6,6,7,10]\nOutput: 6\n\n\n
Example 2:
\n\n\nInput: arr = [1,1]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
0 <= arr[i] <= 105
Given an array intervals
where intervals[i] = [li, ri]
represent the interval [li, ri)
, remove all intervals that are covered by another interval in the list.
The interval [a, b)
is covered by the interval [c, d)
if and only if c <= a
and b <= d
.
Return the number of remaining intervals.
\n\n\n
Example 1:
\n\n\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 1000
intervals[i].length == 2
0 <= li < ri <= 105
Given an n x n
integer matrix grid
, return the minimum sum of a falling path with non-zero shifts.
A falling path with non-zero shifts is a choice of exactly one element from each row of grid
such that no two elements chosen in adjacent rows are in the same column.
\n
Example 1:
\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 13\nExplanation: \nThe possible falling paths are:\n[1,5,9], [1,5,7], [1,6,7], [1,6,8],\n[2,4,8], [2,4,9], [2,6,7], [2,6,8],\n[3,4,8], [3,4,9], [3,5,7], [3,5,9]\nThe falling path with the smallest sum is [1,5,7], so the answer is 13.\n\n\n
Example 2:
\n\n\nInput: grid = [[7]]\nOutput: 7\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
1 <= n <= 200
-99 <= grid[i][j] <= 99
Given head
which is a reference node to a singly-linked list. The value of each node in the linked list is either 0
or 1
. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
\n\nThe most significant bit is at the head of the linked list.
\n\n\n
Example 1:
\n\nInput: head = [1,0,1]\nOutput: 5\nExplanation: (101) in base 2 = (5) in base 10\n\n\n
Example 2:
\n\n\nInput: head = [0]\nOutput: 0\n\n\n
\n
Constraints:
\n\n30
.0
or 1
.An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
\n\nReturn a sorted list of all the integers in the range [low, high]
inclusive that have sequential digits.
\n
Example 1:
\nInput: low = 100, high = 300\nOutput: [123,234]\n
Example 2:
\nInput: low = 1000, high = 13000\nOutput: [1234,2345,3456,4567,5678,6789,12345]\n\n
\n
Constraints:
\n\n10 <= low <= high <= 10^9
Given a m x n
matrix mat
and an integer threshold
, return the maximum side-length of a square with a sum less than or equal to threshold
or return 0
if there is no such square.
\n
Example 1:
\n\nInput: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput: 2\nExplanation: The maximum side length of square with sum less than 4 is 2 as shown.\n\n\n
Example 2:
\n\n\nInput: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 300
0 <= mat[i][j] <= 104
0 <= threshold <= 105
You are given an m x n
integer matrix grid
where each cell is either 0
(empty) or 1
(obstacle). You can move up, down, left, or right from and to an empty cell in one step.
Return the minimum number of steps to walk from the upper left corner (0, 0)
to the lower right corner (m - 1, n - 1)
given that you can eliminate at most k
obstacles. If it is not possible to find such walk return -1
.
\n
Example 1:
\n\nInput: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\nOutput: 6\nExplanation: \nThe shortest path without eliminating any obstacle is 10.\nThe shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\n\n\n
Example 2:
\n\nInput: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput: -1\nExplanation: We need to eliminate at least two obstacles to find such a walk.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 40
1 <= k <= m * n
grid[i][j]
is either 0
or 1
.grid[0][0] == grid[m - 1][n - 1] == 0
Given an array nums
of integers, return how many of them contain an even number of digits.
\n
Example 1:
\n\n\nInput: nums = [12,345,2,6,7896]\nOutput: 2\nExplanation: \n12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.\n\n\n
Example 2:
\n\n\nInput: nums = [555,901,482,1771]\nOutput: 1 \nExplanation: \nOnly 1771 contains an even number of digits.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 500
1 <= nums[i] <= 105
Given an array of integers nums
and a positive integer k
, check whether it is possible to divide this array into sets of k
consecutive numbers.
Return true
if it is possible. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,3,4,4,5,6], k = 4\nOutput: true\nExplanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput: true\nExplanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4], k = 3\nOutput: false\nExplanation: Each array should be divided in subarrays of size 3.\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
\nNote: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/", - "likes": 1902, - "dislikes": 115, - "stats": "{\"totalAccepted\": \"105.9K\", \"totalSubmission\": \"180.6K\", \"totalAcceptedRaw\": 105876, \"totalSubmissionRaw\": 180635, \"acRate\": \"58.6%\"}", + "likes": 1929, + "dislikes": 116, + "stats": "{\"totalAccepted\": \"112.6K\", \"totalSubmission\": \"191.8K\", \"totalAcceptedRaw\": 112554, \"totalSubmissionRaw\": 191772, \"acRate\": \"58.7%\"}", "similarQuestions": "[{\"title\": \"Split Array into Consecutive Subsequences\", \"titleSlug\": \"split-array-into-consecutive-subsequences\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"All Divisions With the Highest Score of a Binary Array\", \"titleSlug\": \"all-divisions-with-the-highest-score-of-a-binary-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -48844,9 +48892,9 @@ "questionFrontendId": "1297", "title": "Maximum Number of Occurrences of a Substring", "content": "
Given a string s
, return the maximum number of occurrences of any substring under the following rules:
maxLetters
.minSize
and maxSize
inclusive.\n
Example 1:
\n\n\nInput: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4\nOutput: 2\nExplanation: Substring "aab" has 2 occurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).\n\n\n
Example 2:
\n\n\nInput: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3\nOutput: 2\nExplanation: Substring "aaa" occur 2 times in the string. It can overlap.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s
consists of only lowercase English letters.You have n
boxes labeled from 0
to n - 1
. You are given four arrays: status
, candies
, keys
, and containedBoxes
where:
status[i]
is 1
if the ith
box is open and 0
if the ith
box is closed,candies[i]
is the number of candies in the ith
box,keys[i]
is a list of the labels of the boxes you can open after opening the ith
box.containedBoxes[i]
is a list of the boxes you found inside the ith
box.You are given an integer array initialBoxes
that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.
Return the maximum number of candies you can get following the rules above.
\n\n\n
Example 1:
\n\n\nInput: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\nOutput: 16\nExplanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.\n\n\n
Example 2:
\n\n\nInput: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\nOutput: 6\nExplanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.\n\n\n
\n
Constraints:
\n\nn == status.length == candies.length == keys.length == containedBoxes.length
1 <= n <= 1000
status[i]
is either 0
or 1
.1 <= candies[i] <= 1000
0 <= keys[i].length <= n
0 <= keys[i][j] < n
keys[i]
are unique.0 <= containedBoxes[i].length <= n
0 <= containedBoxes[i][j] < n
containedBoxes[i]
are unique.0 <= initialBoxes.length <= n
0 <= initialBoxes[i] < n
Given an array arr
, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1
.
After doing so, return the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [17,18,5,4,6,1]\nOutput: [18,6,6,6,1,-1]\nExplanation: \n- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.\n\n\n
Example 2:
\n\n\nInput: arr = [400]\nOutput: [-1]\nExplanation: There are no elements to the right of index 0.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
1 <= arr[i] <= 105
Given an integer array arr
and a target value target
, return the integer value
such that when we change all the integers larger than value
in the given array to be equal to value
, the sum of the array gets as close as possible (in absolute difference) to target
.
In case of a tie, return the minimum such integer.
\n\nNotice that the answer is not neccesarilly a number from arr
.
\n
Example 1:
\n\n\nInput: arr = [4,9,3], target = 10\nOutput: 3\nExplanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\n\n\n
Example 2:
\n\n\nInput: arr = [2,3,5], target = 10\nOutput: 5\n\n\n
Example 3:
\n\n\nInput: arr = [60864,25176,27249,21296,20204], target = 56803\nOutput: 11361\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 104
1 <= arr[i], target <= 105
You are given a square board
of characters. You can move on the board starting at the bottom right square marked with the character 'S'
.
You need to reach the top left square marked with the character 'E'
. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9
or with an obstacle 'X'
. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.
Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7
.
In case there is no path, return [0, 0]
.
\r\n
Example 1:
\r\nInput: board = [\"E23\",\"2X2\",\"12S\"]\r\nOutput: [7,1]\r\n
Example 2:
\r\nInput: board = [\"E12\",\"1X1\",\"21S\"]\r\nOutput: [4,2]\r\n
Example 3:
\r\nInput: board = [\"E11\",\"XXX\",\"11S\"]\r\nOutput: [0,0]\r\n\r\n
\r\n
Constraints:
\r\n\r\n2 <= board.length == board[i].length <= 100
root
of a binary tree, return the sum of values of its deepest leaves.\n\n
Example 1:
\n\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\n\n\n
Example 2:
\n\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 19\n\n\n
\n
Constraints:
\n\n[1, 104]
.1 <= Node.val <= 100
Given an integer n
, return any array containing n
unique integers such that they add up to 0
.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: [-7,-1,1,3,4]\nExplanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: [-1,0,1]\n\n\n
Example 3:
\n\n\nInput: n = 1\nOutput: [0]\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
Given two binary search trees root1
and root2
, return a list containing all the integers from both trees sorted in ascending order.
\n
Example 1:
\n\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\n\n\n
Example 2:
\n\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n\n\n
\n
Constraints:
\n\n[0, 5000]
.-105 <= Node.val <= 105
Given an array of non-negative integers arr
, you are initially positioned at start
index of the array. When you are at index i
, you can jump to i + arr[i]
or i - arr[i]
, check if you can reach any index with value 0.
Notice that you can not jump outside of the array at any time.
\n\n\n
Example 1:
\n\n\nInput: arr = [4,2,3,0,3,1,2], start = 5\nOutput: true\nExplanation: \nAll possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3 \n\n\n
Example 2:
\n\n\nInput: arr = [4,2,3,0,3,1,2], start = 0\nOutput: true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3\n\n\n
Example 3:
\n\n\nInput: arr = [3,0,2,1,2], start = 2\nOutput: false\nExplanation: There is no way to reach at index 1 with value 0.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 5 * 104
0 <= arr[i] < arr.length
0 <= start < arr.length
Given an equation, represented by words
on the left side and the result
on the right side.
You need to check if the equation is solvable under the following rules:
\n\nwords[i]
and result
are decoded as one number without leading zeros.words
) will equal to the number on the right side (result
).Return true
if the equation is solvable, otherwise return false
.
\n
Example 1:
\n\n\nInput: words = ["SEND","MORE"], result = "MONEY"\nOutput: true\nExplanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652\n\n
Example 2:
\n\n\nInput: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"\nOutput: true\nExplanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 = 138214\n\n
Example 3:
\n\n\nInput: words = ["LEET","CODE"], result = "POINT"\nOutput: false\nExplanation: There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.\n\n\n
\n
Constraints:
\n\n2 <= words.length <= 5
1 <= words[i].length, result.length <= 7
words[i], result
contain only uppercase English letters.10
.You are given a string s
formed by digits and '#'
. We want to map s
to English lowercase characters as follows:
'a'
to 'i'
) are represented by ('1'
to '9'
) respectively.'j'
to 'z'
) are represented by ('10#'
to '26#'
) respectively.Return the string formed after mapping.
\n\nThe test cases are generated so that a unique mapping will always exist.
\n\n\n
Example 1:
\n\n\nInput: s = "10#11#12"\nOutput: "jkab"\nExplanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".\n\n\n
Example 2:
\n\n\nInput: s = "1326#"\nOutput: "acz"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of digits and the '#'
letter.s
will be a valid string such that mapping is always possible.You are given an array arr
of positive integers. You are also given the array queries
where queries[i] = [lefti, righti]
.
For each query i
compute the XOR of elements from lefti
to righti
(that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti]
).
Return an array answer
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput: [2,7,14,8] \nExplanation: \nThe binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8\n\n\n
Example 2:
\n\n\nInput: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput: [8,0,4,4]\n\n\n
\n
Constraints:
\n\n1 <= arr.length, queries.length <= 3 * 104
1 <= arr[i] <= 109
queries[i].length == 2
0 <= lefti <= righti < arr.length
There are n
people, each person has a unique id between 0
and n-1
. Given the arrays watchedVideos
and friends
, where watchedVideos[i]
and friends[i]
contain the list of watched videos and the list of friends respectively for the person with id = i
.
Level 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k
of videos are all watched videos by people with the shortest path exactly equal to k
with you. Given your id
and the level
of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest.
\n
Example 1:
\n\n\nInput: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput: ["B","C"] \nExplanation: \nYou have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = ["C"] \nPerson with id = 2 -> watchedVideos = ["B","C"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2\n\n\n
Example 2:
\n\n\nInput: watchedVideos = [["A","B"],["C"],["B","C"],["D"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput: ["D"]\nExplanation: \nYou have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).\n\n\n
\n
Constraints:
\n\nn == watchedVideos.length == friends.length
2 <= n <= 100
1 <= watchedVideos[i].length <= 100
1 <= watchedVideos[i][j].length <= 8
0 <= friends[i].length < n
0 <= friends[i][j] < n
0 <= id < n
1 <= level < n
friends[i]
contains j
, then friends[j]
contains i
Given a string s
. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s
palindrome.
A Palindrome String is one that reads the same backward as well as forward.
\n\n\n
Example 1:
\n\n\nInput: s = "zzazz"\nOutput: 0\nExplanation: The string "zzazz" is already palindrome we do not need any insertions.\n\n\n
Example 2:
\n\n\nInput: s = "mbadm"\nOutput: 2\nExplanation: String can be "mbdadbm" or "mdbabdm".\n\n\n
Example 3:
\n\n\nInput: s = "leetcode"\nOutput: 5\nExplanation: Inserting 5 characters the string becomes "leetcodocteel".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of lowercase English letters.We are given a list nums
of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]]
(with i >= 0
). For each such pair, there are freq
elements with value val
concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.
Return the decompressed list.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: [2,4,4,4]\nExplanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,2,3]\nOutput: [1,3,3]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100
Given a m x n
matrix mat
and an integer k
, return a matrix answer
where each answer[i][j]
is the sum of all elements mat[r][c]
for:
i - k <= r <= i + k,
j - k <= c <= j + k
, and(r, c)
is a valid position in the matrix.\n
Example 1:
\n\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[12,21,16],[27,45,33],[24,39,28]]\n\n\n
Example 2:
\n\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput: [[45,45,45],[45,45,45],[45,45,45]]\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n, k <= 100
1 <= mat[i][j] <= 100
Given the root
of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0
.
A grandparent of a node is the parent of its parent if it exists.
\n\n\n
Example 1:
\n\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 18\nExplanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\n\n\n
Example 2:
\n\nInput: root = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n[1, 104]
.1 <= Node.val <= 100
Return the number of distinct non-empty substrings of text
that can be written as the concatenation of some string with itself (i.e. it can be written as a + a
where a
is some string).
\n
Example 1:
\n\n\nInput: text = "abcabcabc"\nOutput: 3\nExplanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".\n\n\n
Example 2:
\n\n\nInput: text = "leetcodeleetcode"\nOutput: 2\nExplanation: The 2 substrings are "ee" and "leetcodeleetcode".\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 2000
text
has only lowercase English letters.No-Zero integer is a positive integer that does not contain any 0
in its decimal representation.
Given an integer n
, return a list of two integers [a, b]
where:
a
and b
are No-Zero integers.a + b = n
The test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.
\n\n\n
Example 1:
\n\n\nInput: n = 2\nOutput: [1,1]\nExplanation: Let a = 1 and b = 1.\nBoth a and b are no-zero integers, and a + b = 2 = n.\n\n\n
Example 2:
\n\n\nInput: n = 11\nOutput: [2,9]\nExplanation: Let a = 2 and b = 9.\nBoth a and b are no-zero integers, and a + b = 11 = n.\nNote that there are other valid answers as [8, 3] that can be accepted.\n\n\n
\n
Constraints:
\n\n2 <= n <= 104
Given 3 positives numbers a
, b
and c
. Return the minimum flips required in some bits of a
and b
to make ( a
OR b
== c
). (bitwise OR operation).
\r\nFlip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
\r\n
Example 1:
\r\n\r\n\r\nInput: a = 2, b = 6, c = 5\r\nOutput: 3\r\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (\r\n\r\na
ORb
==c
)
Example 2:
\r\n\r\n\r\nInput: a = 4, b = 2, c = 7\r\nOutput: 1\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: a = 1, b = 2, c = 3\r\nOutput: 0\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= a <= 10^9
1 <= b <= 10^9
1 <= c <= 10^9
There are n
computers numbered from 0
to n - 1
connected by ethernet cables connections
forming a network where connections[i] = [ai, bi]
represents a connection between computers ai
and bi
. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network connections
. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1
.
\n
Example 1:
\n\nInput: n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput: 1\nExplanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\n\n\n
Example 2:
\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput: -1\nExplanation: There are not enough cables.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= connections.length <= min(n * (n - 1) / 2, 105)
connections[i].length == 2
0 <= ai, bi < n
ai != bi
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
\n\n'A'
is located at coordinate (0, 0)
, the letter 'B'
is located at coordinate (0, 1)
, the letter 'P'
is located at coordinate (2, 3)
and the letter 'Z'
is located at coordinate (4, 1)
.Given the string word
, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1)
and (x2, y2)
is |x1 - x2| + |y1 - y2|
.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
\n\n\n
Example 1:
\n\n\nInput: word = "CAKE"\nOutput: 3\nExplanation: Using two fingers, one optimal way to type "CAKE" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3\n\n\n
Example 2:
\n\n\nInput: word = "HAPPY"\nOutput: 6\nExplanation: Using two fingers, one optimal way to type "HAPPY" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6\n\n\n
\n
Constraints:
\n\n2 <= word.length <= 300
word
consists of uppercase English letters.Table: Customer
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| customer_id | int |\n| name | varchar |\n| visited_on | date |\n| amount | int |\n+---------------+---------+\nIn SQL,(customer_id, visited_on) is the primary key for this table.\nThis table contains data about customer transactions in a restaurant.\nvisited_on is the date on which the customer with ID (customer_id) has visited the restaurant.\namount is the total paid by a customer.\n\n\n
\n\n
You are the restaurant owner and you want to analyze a possible expansion (there will be at least one customer every day).
\n\nCompute the moving average of how much the customer paid in a seven days window (i.e., current day + 6 days before). average_amount
should be rounded to two decimal places.
Return the result table ordered by visited_on
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nCustomer table:\n+-------------+--------------+--------------+-------------+\n| customer_id | name | visited_on | amount |\n+-------------+--------------+--------------+-------------+\n| 1 | Jhon | 2019-01-01 | 100 |\n| 2 | Daniel | 2019-01-02 | 110 |\n| 3 | Jade | 2019-01-03 | 120 |\n| 4 | Khaled | 2019-01-04 | 130 |\n| 5 | Winston | 2019-01-05 | 110 | \n| 6 | Elvis | 2019-01-06 | 140 | \n| 7 | Anna | 2019-01-07 | 150 |\n| 8 | Maria | 2019-01-08 | 80 |\n| 9 | Jaze | 2019-01-09 | 110 | \n| 1 | Jhon | 2019-01-10 | 130 | \n| 3 | Jade | 2019-01-10 | 150 | \n+-------------+--------------+--------------+-------------+\nOutput: \n+--------------+--------------+----------------+\n| visited_on | amount | average_amount |\n+--------------+--------------+----------------+\n| 2019-01-07 | 860 | 122.86 |\n| 2019-01-08 | 840 | 120 |\n| 2019-01-09 | 840 | 120 |\n| 2019-01-10 | 1000 | 142.86 |\n+--------------+--------------+----------------+\nExplanation: \n1st moving average from 2019-01-01 to 2019-01-07 has an average_amount of (100 + 110 + 120 + 130 + 110 + 140 + 150)/7 = 122.86\n2nd moving average from 2019-01-02 to 2019-01-08 has an average_amount of (110 + 120 + 130 + 110 + 140 + 150 + 80)/7 = 120\n3rd moving average from 2019-01-03 to 2019-01-09 has an average_amount of (120 + 130 + 110 + 140 + 150 + 80 + 110)/7 = 120\n4th moving average from 2019-01-04 to 2019-01-10 has an average_amount of (130 + 110 + 140 + 150 + 80 + 110 + 130 + 150)/7 = 142.86\n\n", - "likes": 898, - "dislikes": 320, - "stats": "{\"totalAccepted\": \"150.8K\", \"totalSubmission\": \"272.7K\", \"totalAcceptedRaw\": 150824, \"totalSubmissionRaw\": 272676, \"acRate\": \"55.3%\"}", + "likes": 974, + "dislikes": 337, + "stats": "{\"totalAccepted\": \"183.4K\", \"totalSubmission\": \"324.1K\", \"totalAcceptedRaw\": 183394, \"totalSubmissionRaw\": 324143, \"acRate\": \"56.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -49755,9 +49806,9 @@ "questionFrontendId": "1322", "title": "Ads Performance", "content": null, - "likes": 264, - "dislikes": 66, - "stats": "{\"totalAccepted\": \"46.9K\", \"totalSubmission\": \"78.9K\", \"totalAcceptedRaw\": 46880, \"totalSubmissionRaw\": 78874, \"acRate\": \"59.4%\"}", + "likes": 269, + "dislikes": 67, + "stats": "{\"totalAccepted\": \"49K\", \"totalSubmission\": \"82.7K\", \"totalAcceptedRaw\": 49010, \"totalSubmissionRaw\": 82704, \"acRate\": \"59.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -49786,9 +49837,9 @@ "questionFrontendId": "1323", "title": "Maximum 69 Number", "content": "
You are given a positive integer num
consisting only of digits 6
and 9
.
Return the maximum number you can get by changing at most one digit (6
becomes 9
, and 9
becomes 6
).
\n
Example 1:
\n\n\nInput: num = 9669\nOutput: 9969\nExplanation: \nChanging the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.\n\n\n
Example 2:
\n\n\nInput: num = 9996\nOutput: 9999\nExplanation: Changing the last digit 6 to 9 results in the maximum number.\n\n\n
Example 3:
\n\n\nInput: num = 9999\nOutput: 9999\nExplanation: It is better not to apply any change.\n\n\n
\n
Constraints:
\n\n1 <= num <= 104
num
consists of only 6
and 9
digits.Given a string s
. Return all the words vertically in the same order in which they appear in s
.
\r\nWords are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).
\r\nEach word would be put on only one column and that in one column there will be only one word.
\r\n
Example 1:
\r\n\r\n\r\nInput: s = "HOW ARE YOU"\r\nOutput: ["HAY","ORO","WEU"]\r\nExplanation: Each word is printed vertically. \r\n "HAY"\r\n "ORO"\r\n "WEU"\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: s = "TO BE OR NOT TO BE"\r\nOutput: ["TBONTB","OEROOE"," T"]\r\nExplanation: Trailing spaces is not allowed. \r\n"TBONTB"\r\n"OEROOE"\r\n" T"\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: s = "CONTEST IS COMING"\r\nOutput: ["CIC","OSO","N M","T I","E N","S G","T"]\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= s.length <= 200
s
contains only upper case English letters.Given a binary tree root
and an integer target
, delete all the leaf nodes with value target
.
Note that once you delete a leaf node with value target
, if its parent node becomes a leaf node and has the value target
, it should also be deleted (you need to continue doing that until you cannot).
\n
Example 1:
\n\n\nInput: root = [1,2,3,2,null,2,4], target = 2\nOutput: [1,null,3,null,4]\nExplanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\n\n\n
Example 2:
\n\n\nInput: root = [1,3,3,3,2], target = 3\nOutput: [1,3,null,null,2]\n\n\n
Example 3:
\n\n\nInput: root = [1,2,null,2,null,2], target = 2\nOutput: [1]\nExplanation: Leaf nodes in green with value (target = 2) are removed at each step.\n\n\n
\n
Constraints:
\n\n[1, 3000]
.1 <= Node.val, target <= 1000
There is a one-dimensional garden on the x-axis. The garden starts at the point 0
and ends at the point n
. (i.e., the length of the garden is n
).
There are n + 1
taps located at points [0, 1, ..., n]
in the garden.
Given an integer n
and an integer array ranges
of length n + 1
where ranges[i]
(0-indexed) means the i-th
tap can water the area [i - ranges[i], i + ranges[i]]
if it was open.
Return the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.
\n\n\n
Example 1:
\n\nInput: n = 5, ranges = [3,4,1,1,0,0]\nOutput: 1\nExplanation: The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]\n\n\n
Example 2:
\n\n\nInput: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
ranges.length == n + 1
0 <= ranges[i] <= 100
Table: Products
\n+------------------+---------+\n| Column Name | Type |\n+------------------+---------+\n| product_id | int |\n| product_name | varchar |\n| product_category | varchar |\n+------------------+---------+\nproduct_id is the primary key (column with unique values) for this table.\nThis table contains data about the company's products.\n\n\n
\n\n
Table: Orders
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| order_date | date |\n| unit | int |\n+---------------+---------+\nThis table may have duplicate rows.\nproduct_id is a foreign key (reference column) to the Products table.\nunit is the number of products ordered in order_date.\n\n\n
\n\n
Write a solution to get the names of products that have at least 100
units ordered in February 2020 and their amount.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProducts table:\n+-------------+-----------------------+------------------+\n| product_id | product_name | product_category |\n+-------------+-----------------------+------------------+\n| 1 | Leetcode Solutions | Book |\n| 2 | Jewels of Stringology | Book |\n| 3 | HP | Laptop |\n| 4 | Lenovo | Laptop |\n| 5 | Leetcode Kit | T-shirt |\n+-------------+-----------------------+------------------+\nOrders table:\n+--------------+--------------+----------+\n| product_id | order_date | unit |\n+--------------+--------------+----------+\n| 1 | 2020-02-05 | 60 |\n| 1 | 2020-02-10 | 70 |\n| 2 | 2020-01-18 | 30 |\n| 2 | 2020-02-11 | 80 |\n| 3 | 2020-02-17 | 2 |\n| 3 | 2020-02-24 | 3 |\n| 4 | 2020-03-01 | 20 |\n| 4 | 2020-03-04 | 30 |\n| 4 | 2020-03-04 | 60 |\n| 5 | 2020-02-25 | 50 |\n| 5 | 2020-02-27 | 50 |\n| 5 | 2020-03-01 | 50 |\n+--------------+--------------+----------+\nOutput: \n+--------------------+---------+\n| product_name | unit |\n+--------------------+---------+\n| Leetcode Solutions | 130 |\n| Leetcode Kit | 100 |\n+--------------------+---------+\nExplanation: \nProducts with product_id = 1 is ordered in February a total of (60 + 70) = 130.\nProducts with product_id = 2 is ordered in February a total of 80.\nProducts with product_id = 3 is ordered in February a total of (2 + 3) = 5.\nProducts with product_id = 4 was not ordered in February 2020.\nProducts with product_id = 5 is ordered in February a total of (50 + 50) = 100.\n\n", - "likes": 426, - "dislikes": 38, - "stats": "{\"totalAccepted\": \"186.2K\", \"totalSubmission\": \"259.2K\", \"totalAcceptedRaw\": 186185, \"totalSubmissionRaw\": 259226, \"acRate\": \"71.8%\"}", + "likes": 476, + "dislikes": 41, + "stats": "{\"totalAccepted\": \"223.8K\", \"totalSubmission\": \"311.6K\", \"totalAcceptedRaw\": 223802, \"totalSubmissionRaw\": 311554, \"acRate\": \"71.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -49967,9 +50018,9 @@ "questionFrontendId": "1328", "title": "Break a Palindrome", "content": "
Given a palindromic string of lowercase English letters palindrome
, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.
Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.
\n\nA string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly smaller than the corresponding character in b
. For example, "abcc"
is lexicographically smaller than "abcd"
because the first position they differ is at the fourth character, and 'c'
is smaller than 'd'
.
\n
Example 1:
\n\n\nInput: palindrome = "abccba"\nOutput: "aaccba"\nExplanation: There are many ways to make "abccba" not a palindrome, such as "zbccba", "aaccba", and "abacba".\nOf all the ways, "aaccba" is the lexicographically smallest.\n\n\n
Example 2:
\n\n\nInput: palindrome = "a"\nOutput: ""\nExplanation: There is no way to replace a single character to make "a" not a palindrome, so return an empty string.\n\n\n
\n
Constraints:
\n\n1 <= palindrome.length <= 1000
palindrome
consists of only lowercase English letters.A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0]
, where mat
is a 6 x 3
matrix, includes cells mat[2][0]
, mat[3][1]
, and mat[4][2]
.
Given an m x n
matrix mat
of integers, sort each matrix diagonal in ascending order and return the resulting matrix.
\n
Example 1:
\n\nInput: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n\n\n
Example 2:
\n\n\nInput: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 100
1 <= mat[i][j] <= 100
You are given an integer array nums
. The value of this array is defined as the sum of |nums[i] - nums[i + 1]|
for all 0 <= i < nums.length - 1
.
You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.
\n\nFind maximum possible value of the final array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,1,5,4]\nOutput: 10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,9,24,2,1,10]\nOutput: 68\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
Given an array of integers arr
, replace each element with its rank.
The rank represents how large the element is. The rank has the following rules:
\n\n\n
Example 1:
\n\n\nInput: arr = [40,10,20,30]\nOutput: [4,1,2,3]\nExplanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.\n\n
Example 2:
\n\n\nInput: arr = [100,100,100]\nOutput: [1,1,1]\nExplanation: Same elements share the same rank.\n\n\n
Example 3:
\n\n\nInput: arr = [37,12,28,9,100,56,80,5,12]\nOutput: [5,3,4,2,8,6,7,1,3]\n\n\n
\n
Constraints:
\n\n0 <= arr.length <= 105
-109 <= arr[i] <= 109
You are given a string s
consisting only of letters 'a'
and 'b'
. In a single step you can remove one palindromic subsequence from s
.
Return the minimum number of steps to make the given string empty.
\n\nA string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.
\n\nA string is called palindrome if is one that reads the same backward as well as forward.
\n\n\n
Example 1:
\n\n\nInput: s = "ababa"\nOutput: 1\nExplanation: s is already a palindrome, so its entirety can be removed in a single step.\n\n\n
Example 2:
\n\n\nInput: s = "abb"\nOutput: 2\nExplanation: "abb" -> "bb" -> "". \nRemove palindromic subsequence "a" then "bb".\n\n\n
Example 3:
\n\n\nInput: s = "baabb"\nOutput: 2\nExplanation: "baabb" -> "b" -> "". \nRemove palindromic subsequence "baab" then "b".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either 'a'
or 'b'
.Given the array restaurants
where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]
. You have to filter the restaurants using three filters.
The veganFriendly
filter will be either true (meaning you should only include restaurants with veganFriendlyi
set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice
and maxDistance
which are the maximum value for price and distance of restaurants you should consider respectively.
Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi
and veganFriendly
take value 1 when it is true, and 0 when it is false.
\n
Example 1:
\n\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput: [3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). \n\n\n
Example 2:
\n\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput: [4,3,2,1,5]\nExplanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.\n\n\n
Example 3:
\n\n\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput: [4,5]\n\n\n
\n
Constraints:
\n\n1 <= restaurants.length <= 10^4
restaurants[i].length == 5
1 <= idi, ratingi, pricei, distancei <= 10^5
1 <= maxPrice, maxDistance <= 10^5
veganFriendlyi
and veganFriendly
are 0 or 1.idi
are distinct.There are n
cities numbered from 0
to n-1
. Given the array edges
where edges[i] = [fromi, toi, weighti]
represents a bidirectional and weighted edge between cities fromi
and toi
, and given the integer distanceThreshold
.
Return the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold
, If there are multiple such cities, return the city with the greatest number.
Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
\n\n\n
Example 1:
\n\n\nInput: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput: 3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\n\n\n
Example 2:
\n\n\nInput: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput: 0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= fromi < toi < n
1 <= weighti, distanceThreshold <= 10^4
(fromi, toi)
are distinct.You want to schedule a list of jobs in d
days. Jobs are dependent (i.e To work on the ith
job, you have to finish all the jobs j
where 0 <= j < i
).
You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d
days. The difficulty of a day is the maximum difficulty of a job done on that day.
You are given an integer array jobDifficulty
and an integer d
. The difficulty of the ith
job is jobDifficulty[i]
.
Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1
.
\n
Example 1:
\n\nInput: jobDifficulty = [6,5,4,3,2,1], d = 2\nOutput: 7\nExplanation: First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7 \n\n\n
Example 2:
\n\n\nInput: jobDifficulty = [9,9,9], d = 4\nOutput: -1\nExplanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n\n\n
Example 3:
\n\n\nInput: jobDifficulty = [1,1,1], d = 3\nOutput: 3\nExplanation: The schedule is one job per day. total difficulty will be 3.\n\n\n
\n
Constraints:
\n\n1 <= jobDifficulty.length <= 300
0 <= jobDifficulty[i] <= 1000
1 <= d <= 10
You are given an m x n
binary matrix mat
of 1
's (representing soldiers) and 0
's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1
's will appear to the left of all the 0
's in each row.
A row i
is weaker than a row j
if one of the following is true:
i
is less than the number of soldiers in row j
.i < j
.Return the indices of the k
weakest rows in the matrix ordered from weakest to strongest.
\n
Example 1:
\n\n\nInput: mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput: [2,0,3]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].\n\n\n
Example 2:
\n\n\nInput: mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput: [0,2]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
2 <= n, m <= 100
1 <= k <= m
matrix[i][j]
is either 0 or 1.You are given an integer array arr
. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
\n\n\n
Example 1:
\n\n\nInput: arr = [3,3,3,3,5,5,5,2,2,7]\nOutput: 2\nExplanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\n\n\n
Example 2:
\n\n\nInput: arr = [7,7,7,7,7,7]\nOutput: 1\nExplanation: The only possible set you can choose is {7}. This will make the new array empty.\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 105
arr.length
is even.1 <= arr[i] <= 105
Given the root
of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.
Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7
.
Note that you need to maximize the answer before taking the mod and not after taking it.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,4,5,6]\nOutput: 110\nExplanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n\n\n
Example 2:
\n\nInput: root = [1,null,2,3,4,null,null,5,6]\nOutput: 90\nExplanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n\n\n
\n
Constraints:
\n\n[2, 5 * 104]
.1 <= Node.val <= 104
Given an array of integers arr
and an integer d
. In one step you can jump from index i
to index:
i + x
where: i + x < arr.length
and 0 < x <= d
.i - x
where: i - x >= 0
and 0 < x <= d
.In addition, you can only jump from index i
to index j
if arr[i] > arr[j]
and arr[i] > arr[k]
for all indices k
between i
and j
(More formally min(i, j) < k < max(i, j)
).
You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.
\n\nNotice that you can not jump outside of the array at any time.
\n\n\n
Example 1:
\n\nInput: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput: 4\nExplanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.\n\n\n
Example 2:
\n\n\nInput: arr = [3,3,3,3,3], d = 3\nOutput: 1\nExplanation: You can start at any index. You always cannot jump to any index.\n\n\n
Example 3:
\n\n\nInput: arr = [7,6,5,4,3,2,1], d = 1\nOutput: 7\nExplanation: Start at index 0. You can visit all the indicies. \n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 1000
1 <= arr[i] <= 105
1 <= d <= arr.length
Table: Movies
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| movie_id | int |\n| title | varchar |\n+---------------+---------+\nmovie_id is the primary key (column with unique values) for this table.\ntitle is the name of the movie.\n\n\n
\n\n
Table: Users
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| user_id | int |\n| name | varchar |\n+---------------+---------+\nuser_id is the primary key (column with unique values) for this table.\nThe column 'name' has unique values.\n\n\n
Table: MovieRating
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| movie_id | int |\n| user_id | int |\n| rating | int |\n| created_at | date |\n+---------------+---------+\n(movie_id, user_id) is the primary key (column with unique values) for this table.\nThis table contains the rating of a movie by a user in their review.\ncreated_at is the user's review date. \n\n\n
\n\n
Write a solution to:
\n\nFebruary 2020
. In case of a tie, return the lexicographically smaller movie name.The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nMovies table:\n+-------------+--------------+\n| movie_id | title |\n+-------------+--------------+\n| 1 | Avengers |\n| 2 | Frozen 2 |\n| 3 | Joker |\n+-------------+--------------+\nUsers table:\n+-------------+--------------+\n| user_id | name |\n+-------------+--------------+\n| 1 | Daniel |\n| 2 | Monica |\n| 3 | Maria |\n| 4 | James |\n+-------------+--------------+\nMovieRating table:\n+-------------+--------------+--------------+-------------+\n| movie_id | user_id | rating | created_at |\n+-------------+--------------+--------------+-------------+\n| 1 | 1 | 3 | 2020-01-12 |\n| 1 | 2 | 4 | 2020-02-11 |\n| 1 | 3 | 2 | 2020-02-12 |\n| 1 | 4 | 1 | 2020-01-01 |\n| 2 | 1 | 5 | 2020-02-17 | \n| 2 | 2 | 2 | 2020-02-01 | \n| 2 | 3 | 2 | 2020-03-01 |\n| 3 | 1 | 3 | 2020-02-22 | \n| 3 | 2 | 4 | 2020-02-25 | \n+-------------+--------------+--------------+-------------+\nOutput: \n+--------------+\n| results |\n+--------------+\n| Daniel |\n| Frozen 2 |\n+--------------+\nExplanation: \nDaniel and Monica have rated 3 movies ("Avengers", "Frozen 2" and "Joker") but Daniel is smaller lexicographically.\nFrozen 2 and Joker have a rating average of 3.5 in February but Frozen 2 is smaller lexicographically.\n\n", - "likes": 692, - "dislikes": 206, - "stats": "{\"totalAccepted\": \"165.5K\", \"totalSubmission\": \"402.9K\", \"totalAcceptedRaw\": 165523, \"totalSubmissionRaw\": 402860, \"acRate\": \"41.1%\"}", + "likes": 774, + "dislikes": 217, + "stats": "{\"totalAccepted\": \"202K\", \"totalSubmission\": \"486.8K\", \"totalAcceptedRaw\": 202027, \"totalSubmissionRaw\": 486801, \"acRate\": \"41.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -50498,9 +50549,9 @@ "questionFrontendId": "1342", "title": "Number of Steps to Reduce a Number to Zero", "content": "
Given an integer num
, return the number of steps to reduce it to zero.
In one step, if the current number is even, you have to divide it by 2
, otherwise, you have to subtract 1
from it.
\n
Example 1:
\n\n\nInput: num = 14\nOutput: 6\nExplanation: \nStep 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.\n\n\n
Example 2:
\n\n\nInput: num = 8\nOutput: 4\nExplanation: \nStep 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.\n\n\n
Example 3:
\n\n\nInput: num = 123\nOutput: 12\n\n\n
\n
Constraints:
\n\n0 <= num <= 106
Given an array of integers arr
and two integers k
and threshold
, return the number of sub-arrays of size k
and average greater than or equal to threshold
.
\n
Example 1:
\n\n\nInput: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput: 3\nExplanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).\n\n\n
Example 2:
\n\n\nInput: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput: 6\nExplanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i] <= 104
1 <= k <= arr.length
0 <= threshold <= 104
Given two numbers, hour
and minutes
, return the smaller angle (in degrees) formed between the hour
and the minute
hand.
Answers within 10-5
of the actual value will be accepted as correct.
\n
Example 1:
\n\nInput: hour = 12, minutes = 30\nOutput: 165\n\n\n
Example 2:
\n\nInput: hour = 3, minutes = 30\nOutput: 75\n\n\n
Example 3:
\n\nInput: hour = 3, minutes = 15\nOutput: 7.5\n\n\n
\n
Constraints:
\n\n1 <= hour <= 12
0 <= minutes <= 59
Given an array of integers arr
, you are initially positioned at the first index of the array.
In one step you can jump from index i
to index:
i + 1
where: i + 1 < arr.length
.i - 1
where: i - 1 >= 0
.j
where: arr[i] == arr[j]
and i != j
.Return the minimum number of steps to reach the last index of the array.
\n\nNotice that you can not jump outside of the array at any time.
\n\n\n
Example 1:
\n\n\nInput: arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput: 3\nExplanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n\n\n
Example 2:
\n\n\nInput: arr = [7]\nOutput: 0\nExplanation: Start index is the last index. You do not need to jump.\n\n\n
Example 3:
\n\n\nInput: arr = [7,6,9,6,9,6,9,7]\nOutput: 1\nExplanation: You can jump directly from index 0 to index 7 which is last index of the array.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 5 * 104
-108 <= arr[i] <= 108
Given an array arr
of integers, check if there exist two indices i
and j
such that :
i != j
0 <= i, j < arr.length
arr[i] == 2 * arr[j]
\n
Example 1:
\n\n\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]\n\n\n
Example 2:
\n\n\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: There is no i and j that satisfy the conditions.\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 500
-103 <= arr[i] <= 103
You are given two strings of the same length s
and t
. In one step you can choose any character of t
and replace it with another character.
Return the minimum number of steps to make t
an anagram of s
.
An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
\n\n\n
Example 1:
\n\n\nInput: s = "bab", t = "aba"\nOutput: 1\nExplanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.\n\n\n
Example 2:
\n\n\nInput: s = "leetcode", t = "practice"\nOutput: 5\nExplanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.\n\n\n
Example 3:
\n\n\nInput: s = "anagram", t = "mangaar"\nOutput: 0\nExplanation: "anagram" and "mangaar" are anagrams. \n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 104
s.length == t.length
s
and t
consist of lowercase English letters only.A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).
\n\nFor example, the period [10, 10000]
(in seconds) would be partitioned into the following time chunks with these frequencies:
[10,69]
, [70,129]
, [130,189]
, ...
, [9970,10000]
[10,3609]
, [3610,7209]
, [7210,10000]
[10,10000]
Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000
in the above example).
Design and implement an API to help the company with their analysis.
\n\nImplement the TweetCounts
class:
TweetCounts()
Initializes the TweetCounts
object.void recordTweet(String tweetName, int time)
Stores the tweetName
at the recorded time
(in seconds).List<Integer> getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime)
Returns a list of integers representing the number of tweets with tweetName
in each time chunk for the given period of time [startTime, endTime]
(in seconds) and frequency freq
.\n\tfreq
is one of "minute"
, "hour"
, or "day"
representing a frequency of every minute, hour, or day respectively.\n
Example:
\n\n\nInput\n["TweetCounts","recordTweet","recordTweet","recordTweet","getTweetCountsPerFrequency","getTweetCountsPerFrequency","recordTweet","getTweetCountsPerFrequency"]\n[[],["tweet3",0],["tweet3",60],["tweet3",10],["minute","tweet3",0,59],["minute","tweet3",0,60],["tweet3",120],["hour","tweet3",0,210]]\n\nOutput\n[null,null,null,null,[2],[2,1],null,[4]]\n\nExplanation\nTweetCounts tweetCounts = new TweetCounts();\ntweetCounts.recordTweet("tweet3", 0); // New tweet "tweet3" at time 0\ntweetCounts.recordTweet("tweet3", 60); // New tweet "tweet3" at time 60\ntweetCounts.recordTweet("tweet3", 10); // New tweet "tweet3" at time 10\ntweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 59); // return [2]; chunk [0,59] had 2 tweets\ntweetCounts.getTweetCountsPerFrequency("minute", "tweet3", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\ntweetCounts.recordTweet("tweet3", 120); // New tweet "tweet3" at time 120\ntweetCounts.getTweetCountsPerFrequency("hour", "tweet3", 0, 210); // return [4]; chunk [0,210] had 4 tweets\n\n\n
\n
Constraints:
\n\n0 <= time, startTime, endTime <= 109
0 <= endTime - startTime <= 104
104
calls in total to recordTweet
and getTweetCountsPerFrequency
.Given a m * n
matrix seats
that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#'
character otherwise it is denoted by a '.'
character.
Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.
\n\nStudents must be placed in seats in good condition.
\n\n\n
Example 1:
\n\nInput: seats = [["#",".","#","#",".","#"],\n [".","#","#","#","#","."],\n ["#",".","#","#",".","#"]]\nOutput: 4\nExplanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n\n\n
Example 2:
\n\n\nInput: seats = [[".","#"],\n ["#","#"],\n ["#","."],\n ["#","#"],\n [".","#"]]\nOutput: 3\nExplanation: Place all students in available seats. \n\n\n\n
Example 3:
\n\n\nInput: seats = [["#",".",".",".","#"],\n [".","#",".","#","."],\n [".",".","#",".","."],\n [".","#",".","#","."],\n ["#",".",".",".","#"]]\nOutput: 10\nExplanation: Place students in available seats in column 1, 3 and 5.\n\n\n
\n
Constraints:
\n\nseats
contains only characters '.' and
'#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8
Given a m x n
matrix grid
which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid
.
\n
Example 1:
\n\n\nInput: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput: 8\nExplanation: There are 8 negatives number in the matrix.\n\n\n
Example 2:
\n\n\nInput: grid = [[3,2],[1,0]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 100
-100 <= grid[i][j] <= 100
\nFollow up: Could you find an
O(n + m)
solution?",
- "likes": 5046,
+ "likes": 5108,
"dislikes": 133,
- "stats": "{\"totalAccepted\": \"465.5K\", \"totalSubmission\": \"600.1K\", \"totalAcceptedRaw\": 465488, \"totalSubmissionRaw\": 600094, \"acRate\": \"77.6%\"}",
+ "stats": "{\"totalAccepted\": \"491.4K\", \"totalSubmission\": \"632.6K\", \"totalAcceptedRaw\": 491449, \"totalSubmissionRaw\": 632613, \"acRate\": \"77.7%\"}",
"similarQuestions": "[{\"title\": \"Maximum Count of Positive Integer and Negative Integer\", \"titleSlug\": \"maximum-count-of-positive-integer-and-negative-integer\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [
@@ -50878,10 +50929,10 @@
"questionId": "1477",
"questionFrontendId": "1352",
"title": "Product of the Last K Numbers",
- "content": "Design an algorithm that accepts a stream of integers and retrieves the product of the last k
integers of the stream.
Implement the ProductOfNumbers
class:
ProductOfNumbers()
Initializes the object with an empty stream.void add(int num)
Appends the integer num
to the stream.int getProduct(int k)
Returns the product of the last k
numbers in the current list. You can assume that always the current list has at least k
numbers.The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
\n\n\n
Example:
\n\n\nInput\n["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]\n\nOutput\n[null,null,null,null,null,null,20,40,0,null,32]\n\nExplanation\nProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 \n\n\n
\n
Constraints:
\n\n0 <= num <= 100
1 <= k <= 4 * 104
4 * 104
calls will be made to add
and getProduct
.Design an algorithm that accepts a stream of integers and retrieves the product of the last k
integers of the stream.
Implement the ProductOfNumbers
class:
ProductOfNumbers()
Initializes the object with an empty stream.void add(int num)
Appends the integer num
to the stream.int getProduct(int k)
Returns the product of the last k
numbers in the current list. You can assume that always the current list has at least k
numbers.The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.
\n\n\n
Example:
\n\n\nInput\n["ProductOfNumbers","add","add","add","add","add","getProduct","getProduct","getProduct","add","getProduct"]\n[[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]\n\nOutput\n[null,null,null,null,null,null,20,40,0,null,32]\n\nExplanation\nProductOfNumbers productOfNumbers = new ProductOfNumbers();\nproductOfNumbers.add(3); // [3]\nproductOfNumbers.add(0); // [3,0]\nproductOfNumbers.add(2); // [3,0,2]\nproductOfNumbers.add(5); // [3,0,2,5]\nproductOfNumbers.add(4); // [3,0,2,5,4]\nproductOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\nproductOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\nproductOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\nproductOfNumbers.add(8); // [3,0,2,5,4,8]\nproductOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 \n\n\n
\n
Constraints:
\n\n0 <= num <= 100
1 <= k <= 4 * 104
4 * 104
calls will be made to add
and getProduct
.\nFollow-up: Can you implement both
GetProduct
and Add
to work in O(1)
time complexity instead of O(k)
time complexity?",
+ "likes": 2106,
+ "dislikes": 104,
+ "stats": "{\"totalAccepted\": \"247.9K\", \"totalSubmission\": \"395.1K\", \"totalAcceptedRaw\": 247931, \"totalSubmissionRaw\": 395085, \"acRate\": \"62.8%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [
@@ -50925,9 +50976,9 @@
"questionFrontendId": "1353",
"title": "Maximum Number of Events That Can Be Attended",
"content": "You are given an array of events
where events[i] = [startDayi, endDayi]
. Every event i
starts at startDayi
and ends at endDayi
.
You can attend an event i
at any day d
where startTimei <= d <= endTimei
. You can only attend one event at any time d
.
Return the maximum number of events you can attend.
\n\n\n
Example 1:
\n\nInput: events = [[1,2],[2,3],[3,4]]\nOutput: 3\nExplanation: You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.\n\n\n
Example 2:
\n\n\nInput: events= [[1,2],[2,3],[3,4],[1,2]]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= events.length <= 105
events[i].length == 2
1 <= startDayi <= endDayi <= 105
You are given an array target
of n integers. From a starting array arr
consisting of n
1's, you may perform the following procedure :
x
be the sum of all elements currently in your array.i
, such that 0 <= i < n
and set the value of arr
at index i
to x
.Return true
if it is possible to construct the target
array from arr
, otherwise, return false
.
\n
Example 1:
\n\n\nInput: target = [9,3,5]\nOutput: true\nExplanation: Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done\n\n\n
Example 2:
\n\n\nInput: target = [1,1,1,2]\nOutput: false\nExplanation: Impossible to create target array from [1,1,1,1].\n\n\n
Example 3:
\n\n\nInput: target = [8,5]\nOutput: true\n\n\n
\n
Constraints:
\n\nn == target.length
1 <= n <= 5 * 104
1 <= target[i] <= 109
You are given an integer array arr
. Sort the integers in the array in ascending order by the number of 1
's in their binary representation and in case of two or more integers have the same number of 1
's you have to sort them in ascending order.
Return the array after sorting it.
\n\n\n
Example 1:
\n\n\nInput: arr = [0,1,2,3,4,5,6,7,8]\nOutput: [0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]\n\n\n
Example 2:
\n\n\nInput: arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput: [1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 500
0 <= arr[i] <= 104
There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products
and prices
, where the ith
product has an ID of products[i]
and a price of prices[i]
.
When a customer is paying, their bill is represented as two parallel integer arrays product
and amount
, where the jth
product they purchased has an ID of product[j]
, and amount[j]
is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product)
.
The supermarket decided to have a sale. Every nth
customer paying for their groceries will be given a percentage discount. The discount amount is given by discount
, where they will be given discount
percent off their subtotal. More formally, if their subtotal is bill
, then they would actually pay bill * ((100 - discount) / 100)
.
Implement the Cashier
class:
Cashier(int n, int discount, int[] products, int[] prices)
Initializes the object with n
, the discount
, and the products
and their prices
.double getBill(int[] product, int[] amount)
Returns the final total of the bill with the discount applied (if any). Answers within 10-5
of the actual value will be accepted.\n
Example 1:
\n\n\nInput\n["Cashier","getBill","getBill","getBill","getBill","getBill","getBill","getBill"]\n[[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]\nOutput\n[null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]\nExplanation\nCashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\ncashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\ncashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\ncashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\ncashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount.\ncashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount.\ncashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\ncashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 7th customer, no discount.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
0 <= discount <= 100
1 <= products.length <= 200
prices.length == products.length
1 <= products[i] <= 200
1 <= prices[i] <= 1000
products
are unique.1 <= product.length <= products.length
amount.length == product.length
product[j]
exists in products
.1 <= amount[j] <= 1000
product
are unique.1000
calls will be made to getBill
.10-5
of the actual value will be accepted.Given a string s
consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
\n\n\n
Example 1:
\n\n\nInput: s = "abcabc"\nOutput: 10\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). \n\n\n
Example 2:
\n\n\nInput: s = "aaacb"\nOutput: 3\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". \n\n\n
Example 3:
\n\n\nInput: s = "abc"\nOutput: 1\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 5 x 10^4
s
only consists of a, b or c characters.Given n
orders, each order consists of a pickup and a delivery service.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
\n\nSince the answer may be too large, return it modulo 10^9 + 7.
\n\n\n
Example 1:
\n\n\nInput: n = 1\nOutput: 1\nExplanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 6\nExplanation: All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n\n\n
Example 3:
\n\n\nInput: n = 3\nOutput: 90\n\n\n
\n
Constraints:
\n\n1 <= n <= 500
Write a program to count the number of days between two dates.
\n\nThe two dates are given as strings, their format is YYYY-MM-DD
as shown in the examples.
\n
Example 1:
\nInput: date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput: 1\n
Example 2:
\nInput: date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput: 15\n\n
\n
Constraints:
\n\n1971
and 2100
.You have n
binary tree nodes numbered from 0
to n - 1
where node i
has two children leftChild[i]
and rightChild[i]
, return true
if and only if all the given nodes form exactly one valid binary tree.
If node i
has no left child then leftChild[i]
will equal -1
, similarly for the right child.
Note that the nodes have no values and that we only use the node numbers in this problem.
\n\n\n
Example 1:
\n\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\n\n\n
Example 2:
\n\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\n\n\n
Example 3:
\n\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n\n\n
\n
Constraints:
\n\nn == leftChild.length == rightChild.length
1 <= n <= 104
-1 <= leftChild[i], rightChild[i] <= n - 1
Given an integer num
, find the closest two integers in absolute difference whose product equals num + 1
or num + 2
.
Return the two integers in any order.
\n\n\n
Example 1:
\n\n\nInput: num = 8\nOutput: [3,3]\nExplanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\n\n\n
Example 2:
\n\n\nInput: num = 123\nOutput: [5,25]\n\n\n
Example 3:
\n\n\nInput: num = 999\nOutput: [40,25]\n\n\n
\n
Constraints:
\n\n1 <= num <= 10^9
Given an array of digits digits
, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
\n\n\n
Example 1:
\n\n\nInput: digits = [8,1,9]\nOutput: "981"\n\n\n
Example 2:
\n\n\nInput: digits = [8,6,7,1,0]\nOutput: "8760"\n\n\n
Example 3:
\n\n\nInput: digits = [1]\nOutput: ""\n\n\n
\n
Constraints:
\n\n1 <= digits.length <= 104
0 <= digits[i] <= 9
Given the array nums
, for each nums[i]
find out how many numbers in the array are smaller than it. That is, for each nums[i]
you have to count the number of valid j's
such that j != i
and nums[j] < nums[i]
.
Return the answer in an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \nFor nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n\n\n
Example 2:
\n\n\nInput: nums = [6,5,4,8]\nOutput: [2,1,0,3]\n\n\n
Example 3:
\n\n\nInput: nums = [7,7,7,7]\nOutput: [0,0,0,0]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 500
0 <= nums[i] <= 100
In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.
\n\nThe ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.
\n\nYou are given an array of strings votes
which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
\n\n\n
Example 1:
\n\n\nInput: votes = ["ABC","ACB","ABC","ACB","ACB"]\nOutput: "ACB"\nExplanation: \nTeam A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third.\n\n\n
Example 2:
\n\n\nInput: votes = ["WXYZ","XYZW"]\nOutput: "XWYZ"\nExplanation:\nX is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position. \n\n\n
Example 3:
\n\n\nInput: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]\nOutput: "ZMNAGUEDSJYLBOPHRQICWFXTVK"\nExplanation: Only one voter, so their votes are used for the ranking.\n\n\n
\n
Constraints:
\n\n1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length
for 0 <= i, j < votes.length
.votes[i][j]
is an English uppercase letter.votes[i]
are unique.votes[0]
also occur in votes[j]
where 1 <= j < votes.length
.Given a binary tree root
and a linked list with head
as the first node.
Return True if all the elements in the linked list starting from the head
correspond to some downward path connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
\n\n\n
Example 1:
\n\n\nInput: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\nExplanation: Nodes in blue form a subpath in the binary Tree. \n\n\n
Example 2:
\n\n\nInput: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\n\n\n
Example 3:
\n\n\nInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: false\nExplanation: There is no path in the binary tree that contains all the elements of the linked list from head
.\n
\n\n\n
Constraints:
\n\n[1, 2500]
.[1, 100]
.1 <= Node.val <= 100
for each node in the linked list and binary tree.Given an m x n
grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j]
can be:
1
which means go to the cell to the right. (i.e go from grid[i][j]
to grid[i][j + 1]
)2
which means go to the cell to the left. (i.e go from grid[i][j]
to grid[i][j - 1]
)3
which means go to the lower cell. (i.e go from grid[i][j]
to grid[i + 1][j]
)4
which means go to the upper cell. (i.e go from grid[i][j]
to grid[i - 1][j]
)Notice that there could be some signs on the cells of the grid that point outside the grid.
\n\nYou will initially start at the upper left cell (0, 0)
. A valid path in the grid is a path that starts from the upper left cell (0, 0)
and ends at the bottom-right cell (m - 1, n - 1)
following the signs on the grid. The valid path does not have to be the shortest.
You can modify the sign on a cell with cost = 1
. You can modify the sign on a cell one time only.
Return the minimum cost to make the grid have at least one valid path.
\n\n\n
Example 1:
\n\nInput: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\nOutput: 3\nExplanation: You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.\n\n\n
Example 2:
\n\nInput: grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput: 0\nExplanation: You can follow the path from (0, 0) to (2, 2).\n\n\n
Example 3:
\n\nInput: grid = [[1,2],[4,3]]\nOutput: 1\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 100
1 <= grid[i][j] <= 4
You are given a string s
. Reorder the string using the following algorithm:
s
and append it to the result.s
that is greater than the last appended character, and append it to the result.s
and append it to the result.s
that is smaller than the last appended character, and append it to the result.s
have been removed.If the smallest or largest character appears more than once, you may choose any occurrence to append to the result.
\n\nReturn the resulting string after reordering s
using this algorithm.
\n
Example 1:
\n\n\nInput: s = "aaaabbbbcccc"\nOutput: "abccbaabccba"\nExplanation: After steps 1, 2 and 3 of the first iteration, result = "abc"\nAfter steps 4, 5 and 6 of the first iteration, result = "abccba"\nFirst iteration is done. Now s = "aabbcc" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = "abccbaabc"\nAfter steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"\n\n\n
Example 2:
\n\n\nInput: s = "rat"\nOutput: "art"\nExplanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of only lowercase English letters.Given the string s
, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
\n
Example 1:
\n\n\nInput: s = "eleetminicoworoep"\nOutput: 13\nExplanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n\n\n
Example 2:
\n\n\nInput: s = "leetcodeisgreat"\nOutput: 5\nExplanation: The longest substring is "leetc" which contains two e's.\n\n\n
Example 3:
\n\n\nInput: s = "bcbcbc"\nOutput: 6\nExplanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 x 10^5
s
contains only lowercase English letters.You are given the root
of a binary tree.
A ZigZag path for a binary tree is defined as follow:
\n\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).
\n\nReturn the longest ZigZag path contained in that tree.
\n\n\n
Example 1:
\n\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\n\n\n
Example 2:
\n\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n\n\n
Example 3:
\n\n\nInput: root = [1]\nOutput: 0\n\n\n
\n
Constraints:
\n\n[1, 5 * 104]
.1 <= Node.val <= 100
Given a binary tree root
, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
\n\n\n
Example 1:
\n\n\nInput: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\nOutput: 20\nExplanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n\n\n
Example 2:
\n\n\nInput: root = [4,3,null,1,2]\nOutput: 2\nExplanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n\n\n
Example 3:
\n\n\nInput: root = [-4,-2,-5]\nOutput: 0\nExplanation: All values are negatives. Return an empty BST.\n\n\n
\n
Constraints:
\n\n[1, 4 * 104]
.-4 * 104 <= Node.val <= 4 * 104
Given an integer n
, return a string with n
characters such that each character in such string occurs an odd number of times.
The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.
\n\n\n
Example 1:
\n\n\nInput: n = 4\nOutput: "pppz"\nExplanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love".\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: "xy"\nExplanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur".\n\n\n
Example 3:
\n\n\nInput: n = 7\nOutput: "holasss"\n\n\n
\n
Constraints:
\n\n1 <= n <= 500
You have a 1-indexed binary string of length n
where all the bits are 0
initially. We will flip all the bits of this binary string (i.e., change them from 0
to 1
) one by one. You are given a 1-indexed integer array flips
where flips[i]
indicates that the bit at index i
will be flipped in the ith
step.
A binary string is prefix-aligned if, after the ith
step, all the bits in the inclusive range [1, i]
are ones and all the other bits are zeros.
Return the number of times the binary string is prefix-aligned during the flipping process.
\n\n\n
Example 1:
\n\n\nInput: flips = [3,2,4,1,5]\nOutput: 2\nExplanation: The binary string is initially "00000".\nAfter applying step 1: The string becomes "00100", which is not prefix-aligned.\nAfter applying step 2: The string becomes "01100", which is not prefix-aligned.\nAfter applying step 3: The string becomes "01110", which is not prefix-aligned.\nAfter applying step 4: The string becomes "11110", which is prefix-aligned.\nAfter applying step 5: The string becomes "11111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2.\n\n\n
Example 2:
\n\n\nInput: flips = [4,1,2,3]\nOutput: 1\nExplanation: The binary string is initially "0000".\nAfter applying step 1: The string becomes "0001", which is not prefix-aligned.\nAfter applying step 2: The string becomes "1001", which is not prefix-aligned.\nAfter applying step 3: The string becomes "1101", which is not prefix-aligned.\nAfter applying step 4: The string becomes "1111", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1.\n\n\n
\n
Constraints:
\n\nn == flips.length
1 <= n <= 5 * 104
flips
is a permutation of the integers in the range [1, n]
.A company has n
employees with a unique ID for each employee from 0
to n - 1
. The head of the company is the one with headID
.
Each employee has one direct manager given in the manager
array where manager[i]
is the direct manager of the i-th
employee, manager[headID] = -1
. Also, it is guaranteed that the subordination relationships have a tree structure.
The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.
\n\nThe i-th
employee needs informTime[i]
minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).
Return the number of minutes needed to inform all the employees about the urgent news.
\n\n\n
Example 1:
\n\n\nInput: n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput: 0\nExplanation: The head of the company is the only employee in the company.\n\n\n
Example 2:
\n\nInput: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput: 1\nExplanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
0 <= headID < n
manager.length == n
0 <= manager[i] < n
manager[headID] == -1
informTime.length == n
0 <= informTime[i] <= 1000
informTime[i] == 0
if employee i
has no subordinates.Given an undirected tree consisting of n
vertices numbered from 1
to n
. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.
The edges of the undirected tree are given in the array edges
, where edges[i] = [ai, bi]
means that exists an edge connecting the vertices ai
and bi
.
Return the probability that after t
seconds the frog is on the vertex target
. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput: 0.16666666666666666 \nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \n\n\n
Example 2:
\n\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput: 0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n\n\n
\n
Constraints:
\n\n1 <= n <= 100
edges.length == n - 1
edges[i].length == 2
1 <= ai, bi <= n
1 <= t <= 50
1 <= target <= n
Table: Employees
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| name | varchar |\n+---------------+---------+\nid is the primary key (column with unique values) for this table.\nEach row of this table contains the id and the name of an employee in a company.\n\n\n
\n\n
Table: EmployeeUNI
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| unique_id | int |\n+---------------+---------+\n(id, unique_id) is the primary key (combination of columns with unique values) for this table.\nEach row of this table contains the id and the corresponding unique id of an employee in the company.\n\n\n
\n\n
Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show null
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+----+----------+\n| id | name |\n+----+----------+\n| 1 | Alice |\n| 7 | Bob |\n| 11 | Meir |\n| 90 | Winston |\n| 3 | Jonathan |\n+----+----------+\nEmployeeUNI table:\n+----+-----------+\n| id | unique_id |\n+----+-----------+\n| 3 | 1 |\n| 11 | 2 |\n| 90 | 3 |\n+----+-----------+\nOutput: \n+-----------+----------+\n| unique_id | name |\n+-----------+----------+\n| null | Alice |\n| null | Bob |\n| 2 | Meir |\n| 3 | Winston |\n| 1 | Jonathan |\n+-----------+----------+\nExplanation: \nAlice and Bob do not have a unique ID, We will show null instead.\nThe unique ID of Meir is 2.\nThe unique ID of Winston is 3.\nThe unique ID of Jonathan is 1.\n\n", - "likes": 1530, - "dislikes": 129, - "stats": "{\"totalAccepted\": \"817.1K\", \"totalSubmission\": \"976.6K\", \"totalAcceptedRaw\": 817087, \"totalSubmissionRaw\": 976611, \"acRate\": \"83.7%\"}", + "likes": 1698, + "dislikes": 142, + "stats": "{\"totalAccepted\": \"986.3K\", \"totalSubmission\": \"1.2M\", \"totalAcceptedRaw\": 986267, \"totalSubmissionRaw\": 1179735, \"acRate\": \"83.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -51915,9 +51975,9 @@ "questionFrontendId": "1379", "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree", "content": "
Given two binary trees original
and cloned
and given a reference to a node target
in the original tree.
The cloned
tree is a copy of the original
tree.
Return a reference to the same node in the cloned
tree.
Note that you are not allowed to change any of the two trees or the target
node and the answer must be a reference to a node in the cloned
tree.
\n
Example 1:
\n\nInput: tree = [7,4,3,null,null,6,19], target = 3\nOutput: 3\nExplanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\n\n\n
Example 2:
\n\nInput: tree = [7], target = 7\nOutput: 7\n\n\n
Example 3:
\n\nInput: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput: 4\n\n\n
\n
Constraints:
\n\ntree
is in the range [1, 104]
.tree
are unique.target
node is a node from the original
tree and is not null
.\n
Follow up: Could you solve the problem if repeated values on the tree are allowed?
\n", - "likes": 1772, - "dislikes": 2013, - "stats": "{\"totalAccepted\": \"245.9K\", \"totalSubmission\": \"286.3K\", \"totalAcceptedRaw\": 245884, \"totalSubmissionRaw\": 286308, \"acRate\": \"85.9%\"}", + "likes": 1787, + "dislikes": 2014, + "stats": "{\"totalAccepted\": \"252K\", \"totalSubmission\": \"294K\", \"totalAcceptedRaw\": 252015, \"totalSubmissionRaw\": 294002, \"acRate\": \"85.7%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -51955,9 +52015,9 @@ "questionFrontendId": "1380", "title": "Lucky Numbers in a Matrix", "content": "Given an m x n
matrix of distinct numbers, return all lucky numbers in the matrix in any order.
A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.
\n\n\n
Example 1:
\n\n\nInput: matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput: [15]\nExplanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\n
Example 2:
\n\n\nInput: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput: [12]\nExplanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\n
Example 3:
\n\n\nInput: matrix = [[7,8],[1,2]]\nOutput: [7]\nExplanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= n, m <= 50
1 <= matrix[i][j] <= 105
.Design a stack that supports increment operations on its elements.
\n\nImplement the CustomStack
class:
CustomStack(int maxSize)
Initializes the object with maxSize
which is the maximum number of elements in the stack.void push(int x)
Adds x
to the top of the stack if the stack has not reached the maxSize
.int pop()
Pops and returns the top of the stack or -1
if the stack is empty.void inc(int k, int val)
Increments the bottom k
elements of the stack by val
. If there are less than k
elements in the stack, increment all the elements in the stack.\n
Example 1:
\n\n\nInput\n["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]\n[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]\nOutput\n[null,null,null,2,null,null,null,null,null,103,202,201,-1]\nExplanation\nCustomStack stk = new CustomStack(3); // Stack is Empty []\nstk.push(1); // stack becomes [1]\nstk.push(2); // stack becomes [1, 2]\nstk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\nstk.push(2); // stack becomes [1, 2]\nstk.push(3); // stack becomes [1, 2, 3]\nstk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4\nstk.increment(5, 100); // stack becomes [101, 102, 103]\nstk.increment(2, 100); // stack becomes [201, 202, 103]\nstk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\nstk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201]\nstk.pop(); // return 201 --> Return top of the stack 201, stack becomes []\nstk.pop(); // return -1 --> Stack is empty return -1.\n\n\n
\n
Constraints:
\n\n1 <= maxSize, x, k <= 1000
0 <= val <= 100
1000
calls will be made to each method of increment
, push
and pop
each separately.Given the root
of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.
A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1
.
\n
Example 1:
\n\nInput: root = [1,null,2,null,3,null,4,null,null]\nOutput: [2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\n\n\n
Example 2:
\n\nInput: root = [2,1,3]\nOutput: [2,1,3]\n\n\n
\n
Constraints:
\n\n[1, 104]
.1 <= Node.val <= 105
You are given two integers n
and k
and two integer arrays speed
and efficiency
both of length n
. There are n
engineers numbered from 1
to n
. speed[i]
and efficiency[i]
represent the speed and efficiency of the ith
engineer respectively.
Choose at most k
different engineers out of the n
engineers to form a team with the maximum performance.
The performance of a team is the sum of its engineers' speeds multiplied by the minimum efficiency among its engineers.
\n\nReturn the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput: 60\nExplanation: \nWe have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n\n\n
Example 2:
\n\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput: 68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n\n\n
Example 3:
\n\n\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput: 72\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 105
speed.length == n
efficiency.length == n
1 <= speed[i] <= 105
1 <= efficiency[i] <= 108
Given two integer arrays arr1
and arr2
, and the integer d
, return the distance value between the two arrays.
The distance value is defined as the number of elements arr1[i]
such that there is not any element arr2[j]
where |arr1[i]-arr2[j]| <= d
.
\n
Example 1:
\n\n\nInput: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput: 2\nExplanation: \nFor arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:\n|8-10|=2 <= d=2\n|8-9|=1 <= d=2\n|8-1|=7 > d=2\n|8-8|=0 <= d=2\n\n\n
Example 2:
\n\n\nInput: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 500
-1000 <= arr1[i], arr2[j] <= 1000
0 <= d <= 100
A cinema has n
rows of seats, numbered from 1 to n
and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array reservedSeats
containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8]
means the seat located in row 3 and labelled with 8 is already reserved.
Return the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
\n\n\n
Example 1:
\n\n\nInput: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput: 4\nExplanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\n\n\n
Example 2:
\n\n\nInput: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= n <= 10^9
1 <= reservedSeats.length <= min(10*n, 10^4)
reservedSeats[i].length == 2
1 <= reservedSeats[i][0] <= n
1 <= reservedSeats[i][1] <= 10
reservedSeats[i]
are distinct.The power of an integer x
is defined as the number of steps needed to transform x
into 1
using the following steps:
x
is even then x = x / 2
x
is odd then x = 3 * x + 1
For example, the power of x = 3
is 7
because 3
needs 7
steps to become 1
(3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1
).
Given three integers lo
, hi
and k
. The task is to sort all integers in the interval [lo, hi]
by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.
Return the kth
integer in the range [lo, hi]
sorted by the power value.
Notice that for any integer x
(lo <= x <= hi)
it is guaranteed that x
will transform into 1
using these steps and that the power of x
is will fit in a 32-bit signed integer.
\n
Example 1:
\n\n\nInput: lo = 12, hi = 15, k = 2\nOutput: 13\nExplanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\n\n\n
Example 2:
\n\n\nInput: lo = 7, hi = 11, k = 4\nOutput: 7\nExplanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.\n\n\n
\n
Constraints:
\n\n1 <= lo <= hi <= 1000
1 <= k <= hi - lo + 1
There is a pizza with 3n
slices of varying size, you and your friends will take slices of pizza as follows:
Given an integer array slices
that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.
\n
Example 1:
\n\nInput: slices = [1,2,3,4,5,6]\nOutput: 10\nExplanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n\n\n
Example 2:
\n\nInput: slices = [8,9,8,6,1,1]\nOutput: 16\nExplanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n\n\n
\n
Constraints:
\n\n3 * n == slices.length
1 <= slices.length <= 500
1 <= slices[i] <= 1000
Given two arrays of integers nums
and index
. Your task is to create target array under the following rules:
index[i]
the value nums[i]
in target array.nums
and index.
Return the target array.
\n\nIt is guaranteed that the insertion operations will be valid.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,1,2,3,4], index = [0,1,2,2,1]\nOutput: [0,4,1,3,2]\nExplanation:\nnums index target\n0 0 [0]\n1 1 [0,1]\n2 2 [0,1,2]\n3 2 [0,1,3,2]\n4 1 [0,4,1,3,2]\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,0], index = [0,1,2,3,0]\nOutput: [0,1,2,3,4]\nExplanation:\nnums index target\n1 0 [1]\n2 1 [1,2]\n3 2 [1,2,3]\n4 3 [1,2,3,4]\n0 0 [0,1,2,3,4]\n\n\n
Example 3:
\n\n\nInput: nums = [1], index = [0]\nOutput: [1]\n\n\n
\n
Constraints:
\n\n1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i
Given an integer array nums
, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0
.
\n
Example 1:
\n\n\nInput: nums = [21,4,7]\nOutput: 32\nExplanation: \n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\n\n\n
Example 2:
\n\n\nInput: nums = [21,21]\nOutput: 64\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
1 <= nums[i] <= 105
You are given an m x n
grid
. Each cell of grid
represents a street. The street of grid[i][j]
can be:
1
which means a street connecting the left cell and the right cell.2
which means a street connecting the upper cell and the lower cell.3
which means a street connecting the left cell and the lower cell.4
which means a street connecting the right cell and the lower cell.5
which means a street connecting the left cell and the upper cell.6
which means a street connecting the right cell and the upper cell.You will initially start at the street of the upper-left cell (0, 0)
. A valid path in the grid is a path that starts from the upper left cell (0, 0)
and ends at the bottom-right cell (m - 1, n - 1)
. The path should only follow the streets.
Notice that you are not allowed to change any street.
\n\nReturn true
if there is a valid path in the grid or false
otherwise.
\n
Example 1:
\n\nInput: grid = [[2,4,3],[6,5,2]]\nOutput: true\nExplanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\n\n\n
Example 2:
\n\nInput: grid = [[1,2,1],[1,2,1]]\nOutput: false\nExplanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,2]]\nOutput: false\nExplanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 300
1 <= grid[i][j] <= 6
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
\n\nGiven a string s
, return the longest happy prefix of s
. Return an empty string ""
if no such prefix exists.
\n
Example 1:
\n\n\nInput: s = "level"\nOutput: "l"\nExplanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l".\n\n\n
Example 2:
\n\n\nInput: s = "ababab"\nOutput: "abab"\nExplanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
contains only lowercase English letters.Table: Stocks
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| stock_name | varchar |\n| operation | enum |\n| operation_day | int |\n| price | int |\n+---------------+---------+\n(stock_name, operation_day) is the primary key (combination of columns with unique values) for this table.\nThe operation column is an ENUM (category) of type ('Sell', 'Buy')\nEach row of this table indicates that the stock which has stock_name had an operation on the day operation_day with the price.\nIt is guaranteed that each 'Sell' operation for a stock has a corresponding 'Buy' operation in a previous day. It is also guaranteed that each 'Buy' operation for a stock has a corresponding 'Sell' operation in an upcoming day.\n\n\n
\n\n
Write a solution to report the Capital gain/loss for each stock.
\n\nThe Capital gain/loss of a stock is the total gain or loss after buying and selling the stock one or many times.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nStocks table:\n+---------------+-----------+---------------+--------+\n| stock_name | operation | operation_day | price |\n+---------------+-----------+---------------+--------+\n| Leetcode | Buy | 1 | 1000 |\n| Corona Masks | Buy | 2 | 10 |\n| Leetcode | Sell | 5 | 9000 |\n| Handbags | Buy | 17 | 30000 |\n| Corona Masks | Sell | 3 | 1010 |\n| Corona Masks | Buy | 4 | 1000 |\n| Corona Masks | Sell | 5 | 500 |\n| Corona Masks | Buy | 6 | 1000 |\n| Handbags | Sell | 29 | 7000 |\n| Corona Masks | Sell | 10 | 10000 |\n+---------------+-----------+---------------+--------+\nOutput: \n+---------------+-------------------+\n| stock_name | capital_gain_loss |\n+---------------+-------------------+\n| Corona Masks | 9500 |\n| Leetcode | 8000 |\n| Handbags | -23000 |\n+---------------+-------------------+\nExplanation: \nLeetcode stock was bought at day 1 for 1000$ and was sold at day 5 for 9000$. Capital gain = 9000 - 1000 = 8000$.\nHandbags stock was bought at day 17 for 30000$ and was sold at day 29 for 7000$. Capital loss = 7000 - 30000 = -23000$.\nCorona Masks stock was bought at day 1 for 10$ and was sold at day 3 for 1010$. It was bought again at day 4 for 1000$ and was sold at day 5 for 500$. At last, it was bought at day 6 for 1000$ and was sold at day 10 for 10000$. Capital gain/loss is the sum of capital gains/losses for each ('Buy' --> 'Sell') operation = (1010 - 10) + (500 - 1000) + (10000 - 1000) = 1000 - 500 + 9000 = 9500$.\n\n", - "likes": 846, + "likes": 881, "dislikes": 48, - "stats": "{\"totalAccepted\": \"129.5K\", \"totalSubmission\": \"152.1K\", \"totalAcceptedRaw\": 129521, \"totalSubmissionRaw\": 152119, \"acRate\": \"85.1%\"}", + "stats": "{\"totalAccepted\": \"138.8K\", \"totalSubmission\": \"163.5K\", \"totalAcceptedRaw\": 138802, \"totalSubmissionRaw\": 163453, \"acRate\": \"84.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -52489,9 +52549,9 @@ "questionFrontendId": "1394", "title": "Find Lucky Integer in an Array", "content": "
Given an array of integers arr
, a lucky integer is an integer that has a frequency in the array equal to its value.
Return the largest lucky integer in the array. If there is no lucky integer return -1
.
\n
Example 1:
\n\n\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\n\n\n
Example 3:
\n\n\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 500
1 <= arr[i] <= 500
There are n
soldiers standing in a line. Each soldier is assigned a unique rating
value.
You have to form a team of 3 soldiers amongst them under the following rules:
\n\ni
, j
, k
) with rating (rating[i]
, rating[j]
, rating[k]
).rating[i] < rating[j] < rating[k]
) or (rating[i] > rating[j] > rating[k]
) where (0 <= i < j < k < n
).Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
\n\n\n
Example 1:
\n\n\nInput: rating = [2,5,3,4,1]\nOutput: 3\nExplanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). \n\n\n
Example 2:
\n\n\nInput: rating = [2,1,3]\nOutput: 0\nExplanation: We can't form any team given the conditions.\n\n\n
Example 3:
\n\n\nInput: rating = [1,2,3,4]\nOutput: 4\n\n\n
\n
Constraints:
\n\nn == rating.length
3 <= n <= 1000
1 <= rating[i] <= 105
rating
are unique.An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
\n\nImplement the UndergroundSystem
class:
void checkIn(int id, string stationName, int t)
\n\n\tid
, checks in at the station stationName
at time t
.void checkOut(int id, string stationName, int t)
\n\tid
, checks out from the station stationName
at time t
.double getAverageTime(string startStation, string endStation)
\n\tstartStation
to endStation
.startStation
to endStation
that happened directly, meaning a check in at startStation
followed by a check out from endStation
.startStation
to endStation
may be different from the time it takes to travel from endStation
to startStation
.startStation
to endStation
before getAverageTime
is called.You may assume all calls to the checkIn
and checkOut
methods are consistent. If a customer checks in at time t1
then checks out at time t2
, then t1 < t2
. All events happen in chronological order.
\n
Example 1:
\n\n\nInput\n["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]\n[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]\n\nOutput\n[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(45, "Leyton", 3);\nundergroundSystem.checkIn(32, "Paradise", 8);\nundergroundSystem.checkIn(27, "Leyton", 10);\nundergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12\nundergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10\nundergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14\nundergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14\nundergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11\nundergroundSystem.checkIn(10, "Leyton", 24);\nundergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000\nundergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14\nundergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12\n\n\n
Example 2:
\n\n\nInput\n["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]\n[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]\n\nOutput\n[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]\n\nExplanation\nUndergroundSystem undergroundSystem = new UndergroundSystem();\nundergroundSystem.checkIn(10, "Leyton", 3);\nundergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5\nundergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5\nundergroundSystem.checkIn(5, "Leyton", 10);\nundergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6\nundergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5\nundergroundSystem.checkIn(2, "Leyton", 21);\nundergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9\nundergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n\n\n
\n
Constraints:
\n\n1 <= id, t <= 106
1 <= stationName.length, startStation.length, endStation.length <= 10
2 * 104
calls in total to checkIn
, checkOut
, and getAverageTime
.10-5
of the actual value will be accepted.Given the strings s1
and s2
of size n
and the string evil
, return the number of good strings.
A good string has size n
, it is alphabetically greater than or equal to s1
, it is alphabetically smaller than or equal to s2
, and it does not contain the string evil
as a substring. Since the answer can be a huge number, return this modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 2, s1 = "aa", s2 = "da", evil = "b"\nOutput: 51 \nExplanation: There are 25 good strings starting with 'a': "aa","ac","ad",...,"az". Then there are 25 good strings starting with 'c': "ca","cc","cd",...,"cz" and finally there is one good string starting with 'd': "da". \n\n\n
Example 2:
\n\n\nInput: n = 8, s1 = "leetcode", s2 = "leetgoes", evil = "leet"\nOutput: 0 \nExplanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix "leet", therefore, there is not any good string.\n\n\n
Example 3:
\n\n\nInput: n = 2, s1 = "gx", s2 = "gz", evil = "x"\nOutput: 2\n\n\n
\n
Constraints:
\n\ns1.length == n
s2.length == n
s1 <= s2
1 <= n <= 500
1 <= evil.length <= 50
You are given an integer n
.
Each number from 1
to n
is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
\n\n\n
Example 1:
\n\n\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
You are given an integer n
.
We need to group the numbers from 1
to n
according to the sum of its digits. For example, the numbers 14 and 5 belong to the same group, whereas 13 and 3 belong to different groups.
Return the number of groups that have the largest size, i.e. the maximum number of elements.
\n\n\n
Example 1:
\n\n\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
Given a string s
and an integer k
, return true
if you can use all the characters in s
to construct non-empty k
palindrome strings or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "annabelle", k = 2\nOutput: true\nExplanation: You can construct two palindromes using all characters in s.\nSome possible constructions "anna" + "elble", "anbna" + "elle", "anellena" + "b"\n\n\n
Example 2:
\n\n\nInput: s = "leetcode", k = 3\nOutput: false\nExplanation: It is impossible to construct 3 palindromes using all the characters of s.\n\n\n
Example 3:
\n\n\nInput: s = "true", k = 4\nOutput: true\nExplanation: The only possible solution is to put each character in a separate string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.1 <= k <= 105
You are given a circle represented as (radius, xCenter, yCenter)
and an axis-aligned rectangle represented as (x1, y1, x2, y2)
, where (x1, y1)
are the coordinates of the bottom-left corner, and (x2, y2)
are the coordinates of the top-right corner of the rectangle.
Return true
if the circle and rectangle are overlapped otherwise return false
. In other words, check if there is any point (xi, yi)
that belongs to the circle and the rectangle at the same time.
\n
Example 1:
\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput: true\nExplanation: Circle and rectangle share the point (1,0).\n\n\n
Example 2:
\n\n\nInput: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput: false\n\n\n
Example 3:
\n\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= radius <= 2000
-104 <= xCenter, yCenter <= 104
-104 <= x1 < x2 <= 104
-104 <= y1 < y2 <= 104
A chef has collected data on the satisfaction
level of his n
dishes. Chef can cook any dish in 1 unit of time.
Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i]
.
Return the maximum sum of like-time coefficient that the chef can obtain after preparing some amount of dishes.
\n\nDishes can be prepared in any order and the chef can discard some dishes to get this maximum value.
\n\n\n
Example 1:
\n\n\nInput: satisfaction = [-1,-8,0,5,-9]\nOutput: 14\nExplanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.\n\n
Example 2:
\n\n\nInput: satisfaction = [4,3,2]\nOutput: 20\nExplanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\n\n\n
Example 3:
\n\n\nInput: satisfaction = [-1,-4,-5]\nOutput: 0\nExplanation: People do not like the dishes. No dish is prepared.\n\n\n
\n
Constraints:
\n\nn == satisfaction.length
1 <= n <= 500
-1000 <= satisfaction[i] <= 1000
Given the array nums
, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence.
If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array.
\n\nNote that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,3,10,9,8]\nOutput: [10,9] \nExplanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements. \n\n\n
Example 2:
\n\n\nInput: nums = [4,4,7,6,7]\nOutput: [7,7,6] \nExplanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order. \n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 500
1 <= nums[i] <= 100
Given the binary representation of an integer as a string s
, return the number of steps to reduce it to 1
under the following rules:
If the current number is even, you have to divide it by 2
.
If the current number is odd, you have to add 1
to it.
It is guaranteed that you can always reach one for all test cases.
\n\n\n
Example 1:
\n\n\nInput: s = "1101"\nOutput: 6\nExplanation: "1101" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4. \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1. \n\n\n
Example 2:
\n\n\nInput: s = "10"\nOutput: 1\nExplanation: "10" corresponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1. \n\n\n
Example 3:
\n\n\nInput: s = "1"\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of characters '0' or '1's[0] == '1'
A string s
is called happy if it satisfies the following conditions:
s
only contains the letters 'a'
, 'b'
, and 'c'
.s
does not contain any of "aaa"
, "bbb"
, or "ccc"
as a substring.s
contains at most a
occurrences of the letter 'a'
.s
contains at most b
occurrences of the letter 'b'
.s
contains at most c
occurrences of the letter 'c'
.Given three integers a
, b
, and c
, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string ""
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: a = 1, b = 1, c = 7\nOutput: "ccaccbcc"\nExplanation: "ccbccacc" would also be a correct answer.\n\n\n
Example 2:
\n\n\nInput: a = 7, b = 1, c = 0\nOutput: "aabaa"\nExplanation: It is the only correct answer in this case.\n\n\n
\n
Constraints:
\n\n0 <= a, b, c <= 100
a + b + c > 0
Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue
.
Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1
, 2
, or 3
stones from the first remaining stones in the row.
The score of each player is the sum of the values of the stones taken. The score of each player is 0
initially.
The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.
\n\nAssume Alice and Bob play optimally.
\n\nReturn "Alice"
if Alice will win, "Bob"
if Bob will win, or "Tie"
if they will end the game with the same score.
\n
Example 1:
\n\n\nInput: stoneValue = [1,2,3,7]\nOutput: "Bob"\nExplanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n\n\n
Example 2:
\n\n\nInput: stoneValue = [1,2,3,-9]\nOutput: "Alice"\nExplanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.\n\n\n
Example 3:
\n\n\nInput: stoneValue = [1,2,3,6]\nOutput: "Tie"\nExplanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n\n\n
\n
Constraints:
\n\n1 <= stoneValue.length <= 5 * 104
-1000 <= stoneValue[i] <= 1000
Table: Users
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| name | varchar |\n+---------------+---------+\nid is the column with unique values for this table.\nname is the name of the user.\n\n\n
\n\n
Table: Rides
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| id | int |\n| user_id | int |\n| distance | int |\n+---------------+---------+\nid is the column with unique values for this table.\nuser_id is the id of the user who traveled the distance "distance".\n\n\n
\n\n
Write a solution to report the distance traveled by each user.
\n\nReturn the result table ordered by travelled_distance
in descending order, if two or more users traveled the same distance, order them by their name
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+------+-----------+\n| id | name |\n+------+-----------+\n| 1 | Alice |\n| 2 | Bob |\n| 3 | Alex |\n| 4 | Donald |\n| 7 | Lee |\n| 13 | Jonathan |\n| 19 | Elvis |\n+------+-----------+\nRides table:\n+------+----------+----------+\n| id | user_id | distance |\n+------+----------+----------+\n| 1 | 1 | 120 |\n| 2 | 2 | 317 |\n| 3 | 3 | 222 |\n| 4 | 7 | 100 |\n| 5 | 13 | 312 |\n| 6 | 19 | 50 |\n| 7 | 7 | 120 |\n| 8 | 19 | 400 |\n| 9 | 7 | 230 |\n+------+----------+----------+\nOutput: \n+----------+--------------------+\n| name | travelled_distance |\n+----------+--------------------+\n| Elvis | 450 |\n| Lee | 450 |\n| Bob | 317 |\n| Jonathan | 312 |\n| Alex | 222 |\n| Alice | 120 |\n| Donald | 0 |\n+----------+--------------------+\nExplanation: \nElvis and Lee traveled 450 miles, Elvis is the top traveler as his name is alphabetically smaller than Lee.\nBob, Jonathan, Alex, and Alice have only one ride and we just order them by the total distances of the ride.\nDonald did not have any rides, the distance traveled by him is 0.\n\n", - "likes": 675, - "dislikes": 70, - "stats": "{\"totalAccepted\": \"151K\", \"totalSubmission\": \"263.7K\", \"totalAcceptedRaw\": 150968, \"totalSubmissionRaw\": 263723, \"acRate\": \"57.2%\"}", + "likes": 692, + "dislikes": 73, + "stats": "{\"totalAccepted\": \"167.8K\", \"totalSubmission\": \"293.9K\", \"totalAcceptedRaw\": 167771, \"totalSubmissionRaw\": 293910, \"acRate\": \"57.1%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -53017,10 +53083,10 @@ "questionId": "1524", "questionFrontendId": "1408", "title": "String Matching in an Array", - "content": "
Given an array of string words
, return all strings in words
that is a substring of another word. You can return the answer in any order.
A substring is a contiguous sequence of characters within a string
\n\n\n
Example 1:
\n\n\nInput: words = ["mass","as","hero","superhero"]\nOutput: ["as","hero"]\nExplanation: "as" is substring of "mass" and "hero" is substring of "superhero".\n["hero","as"] is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: words = ["leetcode","et","code"]\nOutput: ["et","code"]\nExplanation: "et", "code" are substring of "leetcode".\n\n\n
Example 3:
\n\n\nInput: words = ["blue","green","bu"]\nOutput: []\nExplanation: No string of words is substring of another string.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 30
words[i]
contains only lowercase English letters.words
are unique.Given an array of string words
, return all strings in words
that are a substring of another word. You can return the answer in any order.
\n
Example 1:
\n\n\nInput: words = ["mass","as","hero","superhero"]\nOutput: ["as","hero"]\nExplanation: "as" is substring of "mass" and "hero" is substring of "superhero".\n["hero","as"] is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: words = ["leetcode","et","code"]\nOutput: ["et","code"]\nExplanation: "et", "code" are substring of "leetcode".\n\n\n
Example 3:
\n\n\nInput: words = ["blue","green","bu"]\nOutput: []\nExplanation: No string of words is substring of another string.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 30
words[i]
contains only lowercase English letters.words
are unique.Given the array queries
of positive integers between 1
and m
, you have to process all queries[i]
(from i=0
to i=queries.length-1
) according to the following rules:
P=[1,2,3,...,m]
.i
, find the position of queries[i]
in the permutation P
(indexing from 0) and then move this at the beginning of the permutation P
. Notice that the position of queries[i]
in P
is the result for queries[i]
.Return an array containing the result for the given queries
.
\n
Example 1:
\n\n\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1]. \n\n\n
Example 2:
\n\n\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\n\n\n
Example 3:
\n\n\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n\n\n
\n
Constraints:
\n\n1 <= m <= 10^3
1 <= queries.length <= m
1 <= queries[i] <= m
HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.
\n\nThe special characters and their entities for HTML are:
\n\n"
and symbol character is "
.'
and symbol character is '
.&
and symbol character is &
.>
and symbol character is >
.<
and symbol character is <
.⁄
and symbol character is /
.Given the input text
string to the HTML parser, you have to implement the entity parser.
Return the text after replacing the entities by the special characters.
\n\n\n
Example 1:
\n\n\nInput: text = "& is an HTML entity but &ambassador; is not."\nOutput: "& is an HTML entity but &ambassador; is not."\nExplanation: The parser will replace the & entity by &\n\n\n
Example 2:
\n\n\nInput: text = "and I quote: "...""\nOutput: "and I quote: \\"...\\""\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 105
You have a grid
of size n x 3
and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).
Given n
the number of rows of the grid, return the number of ways you can paint this grid
. As the answer may grow large, the answer must be computed modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 1\nOutput: 12\nExplanation: There are 12 possible way to paint the grid as shown.\n\n\n
Example 2:
\n\n\nInput: n = 5000\nOutput: 30228214\n\n\n
\n
Constraints:
\n\nn == grid.length
1 <= n <= 5000
Given an array of integers nums
, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums
(from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
\n\n\n
Example 1:
\n\n\nInput: nums = [-3,2,-3,4,2]\nOutput: 5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2\n\n\n
Example 2:
\n\n\nInput: nums = [1,2]\nOutput: 1\nExplanation: Minimum start value should be positive. \n\n\n
Example 3:
\n\n\nInput: nums = [1,-2,-3]\nOutput: 5\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
-100 <= nums[i] <= 100
Given an integer k
, return the minimum number of Fibonacci numbers whose sum is equal to k
. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
\n\nF1 = 1
F2 = 1
Fn = Fn-1 + Fn-2
for n > 2.
k
.\n\n
Example 1:
\n\n\nInput: k = 7\nOutput: 2 \nExplanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.\n\n
Example 2:
\n\n\nInput: k = 10\nOutput: 2 \nExplanation: For k = 10 we can use 2 + 8 = 10.\n\n\n
Example 3:
\n\n\nInput: k = 19\nOutput: 3 \nExplanation: For k = 19 we can use 1 + 5 + 13 = 19.\n\n\n
\n
Constraints:
\n\n1 <= k <= 109
A happy string is a string that:
\n\n['a', 'b', 'c']
.s[i] != s[i + 1]
for all values of i
from 1
to s.length - 1
(string is 1-indexed).For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
\n\nGiven two integers n
and k
, consider a list of all happy strings of length n
sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k
happy strings of length n
.
\n
Example 1:
\n\n\nInput: n = 1, k = 3\nOutput: "c"\nExplanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".\n\n\n
Example 2:
\n\n\nInput: n = 1, k = 4\nOutput: ""\nExplanation: There are only 3 happy strings of length 1.\n\n\n
Example 3:
\n\n\nInput: n = 3, k = 9\nOutput: "cab"\nExplanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9th string = "cab"\n\n\n
\n
Constraints:
\n\n1 <= n <= 10
1 <= k <= 100
A program was supposed to print an array of integers. The program forgot to print whitespaces and the array is printed as a string of digits s
and all we know is that all integers in the array were in the range [1, k]
and there are no leading zeros in the array.
Given the string s
and the integer k
, return the number of the possible arrays that can be printed as s
using the mentioned program. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "1000", k = 10000\nOutput: 1\nExplanation: The only possible array is [1000]\n\n\n
Example 2:
\n\n\nInput: s = "1000", k = 10\nOutput: 0\nExplanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n\n\n
Example 3:
\n\n\nInput: s = "1317", k = 2000\nOutput: 8\nExplanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only digits and does not contain leading zeros.1 <= k <= 109
You are given an alphanumeric string s
. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
\n\nReturn the reformatted string or return an empty string if it is impossible to reformat the string.
\n\n\n
Example 1:
\n\n\nInput: s = "a0b1c2"\nOutput: "0a1b2c"\nExplanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.\n\n\n
Example 2:
\n\n\nInput: s = "leetcode"\nOutput: ""\nExplanation: "leetcode" has only characters so we cannot separate them by digits.\n\n\n
Example 3:
\n\n\nInput: s = "1229857369"\nOutput: ""\nExplanation: "1229857369" has only digits so we cannot separate them by characters.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of only lowercase English letters and/or digits.Given the array orders
, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi]
where customerNamei
is the name of the customer, tableNumberi
is the table customer sit at, and foodItemi
is the item customer orders.
Return the restaurant's “display table”. The “display table” is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is “Table”, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: orders = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]\r\nOutput: [["Table","Beef Burrito","Ceviche","Fried Chicken","Water"],["3","0","2","1","0"],["5","0","1","0","1"],["10","1","0","0","0"]] \r\nExplanation:\r\nThe displaying table looks like:\r\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\r\n3 ,0 ,2 ,1 ,0\r\n5 ,0 ,1 ,0 ,1\r\n10 ,1 ,0 ,0 ,0\r\nFor the table 3: David orders "Ceviche" and "Fried Chicken", and Rous orders "Ceviche".\r\nFor the table 5: Carla orders "Water" and "Ceviche".\r\nFor the table 10: Corina orders "Beef Burrito". \r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: orders = [["James","12","Fried Chicken"],["Ratesh","12","Fried Chicken"],["Amadeus","12","Fried Chicken"],["Adam","1","Canadian Waffles"],["Brianna","1","Canadian Waffles"]]\r\nOutput: [["Table","Canadian Waffles","Fried Chicken"],["1","2","0"],["12","0","3"]] \r\nExplanation: \r\nFor the table 1: Adam and Brianna order "Canadian Waffles".\r\nFor the table 12: James, Ratesh and Amadeus order "Fried Chicken".\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: orders = [["Laura","2","Bean Burrito"],["Jhon","2","Beef Burrito"],["Melissa","2","Soda"]]\r\nOutput: [["Table","Bean Burrito","Beef Burrito","Soda"],["2","1","1","1"]]\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= orders.length <= 5 * 10^4
orders[i].length == 3
1 <= customerNamei.length, foodItemi.length <= 20
customerNamei
and foodItemi
consist of lowercase and uppercase English letters and the space character.tableNumberi
is a valid integer between 1
and 500
.You are given the string croakOfFrogs
, which represents a combination of the string "croak"
from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak"
are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
\n\nA valid "croak"
means a frog is printing five letters 'c'
, 'r'
, 'o'
, 'a'
, and 'k'
sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak"
return -1
.
\n
Example 1:
\n\n\nInput: croakOfFrogs = "croakcroak"\nOutput: 1 \nExplanation: One frog yelling "croak" twice.\n\n\n
Example 2:
\n\n\nInput: croakOfFrogs = "crcoakroak"\nOutput: 2 \nExplanation: The minimum number of frogs is two. \nThe first frog could yell "crcoakroak".\nThe second frog could yell later "crcoakroak".\n\n\n
Example 3:
\n\n\nInput: croakOfFrogs = "croakcrook"\nOutput: -1\nExplanation: The given string is an invalid combination of "croak" from different frogs.\n\n\n
\n
Constraints:
\n\n1 <= croakOfFrogs.length <= 105
croakOfFrogs
is either 'c'
, 'r'
, 'o'
, 'a'
, or 'k'
.You are given three integers n
, m
and k
. Consider the following algorithm to find the maximum element of an array of positive integers:
You should build the array arr which has the following properties:
\n\narr
has exactly n
integers.1 <= arr[i] <= m
where (0 <= i < n)
.arr
, the value search_cost
is equal to k
.Return the number of ways to build the array arr
under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 2, m = 3, k = 1\nOutput: 6\nExplanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n\n\n
Example 2:
\n\n\nInput: n = 5, m = 2, k = 3\nOutput: 0\nExplanation: There are no possible arrays that satisfy the mentioned conditions.\n\n\n
Example 3:
\n\n\nInput: n = 9, m = 1, k = 1\nOutput: 1\nExplanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n\n\n
\n
Constraints:
\n\n1 <= n <= 50
1 <= m <= 100
0 <= k <= n
Given a string s
of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
\n\n\n
Example 1:
\n\n\nInput: s = "011101"\nOutput: 5 \nExplanation: \nAll possible ways of splitting s into two non-empty substrings are:\nleft = "0" and right = "11101", score = 1 + 4 = 5 \nleft = "01" and right = "1101", score = 1 + 3 = 4 \nleft = "011" and right = "101", score = 1 + 2 = 3 \nleft = "0111" and right = "01", score = 1 + 1 = 2 \nleft = "01110" and right = "1", score = 2 + 1 = 3\n\n\n
Example 2:
\n\n\nInput: s = "00111"\nOutput: 5\nExplanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5\n\n\n
Example 3:
\n\n\nInput: s = "1111"\nOutput: 3\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 500
s
consists of characters '0'
and '1'
only.There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints
.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k
cards.
Your score is the sum of the points of the cards you have taken.
\n\nGiven the integer array cardPoints
and the integer k
, return the maximum score you can obtain.
\n
Example 1:
\n\n\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\n\n\n
Example 2:
\n\n\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\n\n\n
Example 3:
\n\n\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\n\n\n
\n
Constraints:
\n\n1 <= cardPoints.length <= 105
1 <= cardPoints[i] <= 104
1 <= k <= cardPoints.length
Given a 2D integer array nums
, return all elements of nums
in diagonal order as shown in the below images.
\n
Example 1:
\n\nInput: nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,4,2,7,5,3,8,6,9]\n\n\n
Example 2:
\n\nInput: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i].length <= 105
1 <= sum(nums[i].length) <= 105
1 <= nums[i][j] <= 105
Given an integer array nums
and an integer k
, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i]
and nums[j]
, where i < j
, the condition j - i <= k
is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
\n\n\n
Example 1:
\n\n\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\n\n\n
Example 2:
\n\n\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\n\n\n
Example 3:
\n\n\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
-104 <= nums[i] <= 104
There are n
kids with candies. You are given an integer array candies
, where each candies[i]
represents the number of candies the ith
kid has, and an integer extraCandies
, denoting the number of extra candies that you have.
Return a boolean array result
of length n
, where result[i]
is true
if, after giving the ith
kid all the extraCandies
, they will have the greatest number of candies among all the kids, or false
otherwise.
Note that multiple kids can have the greatest number of candies.
\n\n\n
Example 1:
\n\n\nInput: candies = [2,3,5,1,3], extraCandies = 3\nOutput: [true,true,true,false,true] \nExplanation: If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n\n\n
Example 2:
\n\n\nInput: candies = [4,2,1,1,2], extraCandies = 1\nOutput: [true,false,false,false,false] \nExplanation: There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\n\n\n
Example 3:
\n\n\nInput: candies = [12,1,12], extraCandies = 10\nOutput: [true,false,true]\n\n\n
\n
Constraints:
\n\nn == candies.length
2 <= n <= 100
1 <= candies[i] <= 100
1 <= extraCandies <= 50
You are given an integer num
. You will apply the following steps exactly two times:
x (0 <= x <= 9)
.y (0 <= y <= 9)
. The digit y
can be equal to x
.x
in the decimal representation of num
by y
.Let a
and b
be the results of applying the operations to num
the first and second times, respectively.
Return the max difference between a
and b
.
\n
Example 1:
\n\n\nInput: num = 555\nOutput: 888\nExplanation: The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888\n\n\n
Example 2:
\n\n\nInput: num = 9\nOutput: 8\nExplanation: The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8\n\n\n
\n
Constraints:
\n\n1 <= num <= 108
You are given an integer num
. You will apply the following steps to num
two separate times:
x (0 <= x <= 9)
.y (0 <= y <= 9)
. Note y
can be equal to x
.x
in the decimal representation of num
by y
.Let a
and b
be the two results from applying the operation to num
independently.
Return the max difference between a
and b
.
Note that neither a
nor b
may have any leading zeros, and must not be 0.
\n
Example 1:
\n\n\nInput: num = 555\nOutput: 888\nExplanation: The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888\n\n\n
Example 2:
\n\n\nInput: num = 9\nOutput: 8\nExplanation: The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8\n\n\n
\n
Constraints:
\n\n1 <= num <= 108
Given two strings: s1
and s2
with the same size, check if some permutation of string s1
can break some permutation of string s2
or vice-versa. In other words s2
can break s1
or vice-versa.
A string x
can break string y
(both of size n
) if x[i] >= y[i]
(in alphabetical order) for all i
between 0
and n-1
.
\n
Example 1:
\n\n\nInput: s1 = "abc", s2 = "xya"\nOutput: true\nExplanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".\n\n\n
Example 2:
\n\n\nInput: s1 = "abe", s2 = "acd"\nOutput: false \nExplanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\n\n\n
Example 3:
\n\n\nInput: s1 = "leetcodee", s2 = "interview"\nOutput: true\n\n\n
\n
Constraints:
\n\ns1.length == n
s2.length == n
1 <= n <= 10^5
There are n
people and 40
types of hats labeled from 1
to 40
.
Given a 2D integer array hats
, where hats[i]
is a list of all hats preferred by the ith
person.
Return the number of ways that the n
people wear different hats to each other.
Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: hats = [[3,4],[4,5],[5]]\nOutput: 1\nExplanation: There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.\n\n\n
Example 2:
\n\n\nInput: hats = [[3,5,1],[3,5]]\nOutput: 4\nExplanation: There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)\n\n\n
Example 3:
\n\n\nInput: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\nOutput: 24\nExplanation: Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.\n\n\n
\n
Constraints:
\n\nn == hats.length
1 <= n <= 10
1 <= hats[i].length <= 40
1 <= hats[i][j] <= 40
hats[i]
contains a list of unique integers.There are n
people and 40
types of hats labeled from 1
to 40
.
Given a 2D integer array hats
, where hats[i]
is a list of all hats preferred by the ith
person.
Return the number of ways that n
people can wear different hats from each other.
Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: hats = [[3,4],[4,5],[5]]\nOutput: 1\nExplanation: There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.\n\n\n
Example 2:
\n\n\nInput: hats = [[3,5,1],[3,5]]\nOutput: 4\nExplanation: There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)\n\n\n
Example 3:
\n\n\nInput: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\nOutput: 24\nExplanation: Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.\n\n\n
\n
Constraints:
\n\nn == hats.length
1 <= n <= 10
1 <= hats[i].length <= 40
1 <= hats[i][j] <= 40
hats[i]
contains a list of unique integers.You are given the array paths
, where paths[i] = [cityAi, cityBi]
means there exists a direct path going from cityAi
to cityBi
. Return the destination city, that is, the city without any path outgoing to another city.
It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.
\n\n\n
Example 1:
\n\n\nInput: paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]\nOutput: "Sao Paulo" \nExplanation: Starting at "London" city you will reach "Sao Paulo" city which is the destination city. Your trip consist of: "London" -> "New York" -> "Lima" -> "Sao Paulo".\n\n\n
Example 2:
\n\n\nInput: paths = [["B","C"],["D","B"],["C","A"]]\nOutput: "A"\nExplanation: All possible trips are: \n"D" -> "B" -> "C" -> "A". \n"B" -> "C" -> "A". \n"C" -> "A". \n"A". \nClearly the destination city is "A".\n\n\n
Example 3:
\n\n\nInput: paths = [["A","Z"]]\nOutput: "Z"\n\n\n
\n
Constraints:
\n\n1 <= paths.length <= 100
paths[i].length == 2
1 <= cityAi.length, cityBi.length <= 10
cityAi != cityBi
Given an binary array nums
and an integer k
, return true
if all 1
's are at least k
places away from each other, otherwise return false
.
\n
Example 1:
\n\nInput: nums = [1,0,0,0,1,0,0,1], k = 2\nOutput: true\nExplanation: Each of the 1s are at least 2 places away from each other.\n\n\n
Example 2:
\n\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: false\nExplanation: The second 1 and third 1 are only one apart from each other.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= k <= nums.length
nums[i]
is 0
or 1
Given an array of integers nums
and an integer limit
, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit
.
\n
Example 1:
\n\n\nInput: nums = [8,2,4,7], limit = 4\nOutput: 2 \nExplanation: All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [10,1,2,4,7,2], limit = 5\nOutput: 4 \nExplanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\n\n\n
Example 3:
\n\n\nInput: nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= limit <= 109
You are given an m x n
matrix mat
that has its rows sorted in non-decreasing order and an integer k
.
You are allowed to choose exactly one element from each row to form an array.
\n\nReturn the kth
smallest array sum among all possible arrays.
\n
Example 1:
\n\n\nInput: mat = [[1,3,11],[2,4,6]], k = 5\nOutput: 7\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\n\n\n
Example 2:
\n\n\nInput: mat = [[1,3,11],[2,4,6]], k = 9\nOutput: 17\n\n\n
Example 3:
\n\n\nInput: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput: 9\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat.length[i]
1 <= m, n <= 40
1 <= mat[i][j] <= 5000
1 <= k <= min(200, nm)
mat[i]
is a non-decreasing array.You are given an integer array target
and an integer n
.
You have an empty stack with the two following operations:
\n\n"Push"
: pushes an integer to the top of the stack."Pop"
: removes the integer on the top of the stack.You also have a stream of the integers in the range [1, n]
.
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target
. You should follow the following rules:
target
, do not read new integers from the stream and do not do more operations on the stack.Return the stack operations needed to build target
following the mentioned rules. If there are multiple valid answers, return any of them.
\n
Example 1:
\n\n\nInput: target = [1,3], n = 3\nOutput: ["Push","Push","Pop","Push"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].\n\n\n
Example 2:
\n\n\nInput: target = [1,2,3], n = 3\nOutput: ["Push","Push","Push"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].\n\n\n
Example 3:
\n\n\nInput: target = [1,2], n = 4\nOutput: ["Push","Push"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.\n\n\n
\n
Constraints:
\n\n1 <= target.length <= 100
1 <= n <= 100
1 <= target[i] <= n
target
is strictly increasing.Given an array of integers arr
.
We want to select three indices i
, j
and k
where (0 <= i < j <= k < arr.length)
.
Let's define a
and b
as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]
b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
\n\nReturn the number of triplets (i
, j
and k
) Where a == b
.
\n
Example 1:
\n\n\nInput: arr = [2,3,1,6,7]\nOutput: 4\nExplanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,1,1,1]\nOutput: 10\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 300
1 <= arr[i] <= 108
Given an undirected tree consisting of n
vertices numbered from 0
to n-1
, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.
The edges of the undirected tree are given in the array edges
, where edges[i] = [ai, bi]
means that exists an edge connecting the vertices ai
and bi
. Additionally, there is a boolean array hasApple
, where hasApple[i] = true
means that vertex i
has an apple; otherwise, it does not have any apple.
\n
Example 1:
\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput: 8 \nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n\n\n
Example 2:
\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput: 6\nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n\n\n
Example 3:
\n\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai < bi <= n - 1
hasApple.length == n
Given a rectangular pizza represented as a rows x cols
matrix containing the following characters: 'A'
(an apple) and '.'
(empty cell) and given the integer k
. You have to cut the pizza into k
pieces using k-1
cuts.
For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.
\n\nReturn the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.
\n\n\n
Example 1:
\n\n\nInput: pizza = ["A..","AAA","..."], k = 3\nOutput: 3 \nExplanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\n\n\n
Example 2:
\n\n\nInput: pizza = ["A..","AA.","..."], k = 3\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: pizza = ["A..","A..","..."], k = 1\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= rows, cols <= 50
rows == pizza.length
cols == pizza[i].length
1 <= k <= 10
pizza
consists of characters 'A'
and '.'
only.The power of the string is the maximum length of a non-empty substring that contains only one unique character.
\n\nGiven a string s
, return the power of s
.
\n
Example 1:
\n\n\nInput: s = "leetcode"\nOutput: 2\nExplanation: The substring "ee" is of length 2 with the character 'e' only.\n\n\n
Example 2:
\n\n\nInput: s = "abbcccddddeeeeedcba"\nOutput: 5\nExplanation: The substring "eeeee" is of length 5 with the character 'e' only.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of only lowercase English letters.Given an integer n
, return a list of all simplified fractions between 0
and 1
(exclusive) such that the denominator is less-than-or-equal-to n
. You can return the answer in any order.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: ["1/2"]\nExplanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: ["1/2","1/3","2/3"]\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: ["1/2","1/3","1/4","2/3","3/4"]\nExplanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
Given a binary tree root
, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: root = [3,1,4,3,null,1,5]\r\nOutput: 4\r\nExplanation: Nodes in blue are good.\r\nRoot Node (3) is always a good node.\r\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\r\nNode 5 -> (3,4,5) is the maximum value in the path\r\nNode 3 -> (3,1,3) is the maximum value in the path.\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: root = [3,3,null,4,2]\r\nOutput: 3\r\nExplanation: Node 2 -> (3, 3, 2) is not good, because "3" is higher than it.\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: root = [1]\r\nOutput: 1\r\nExplanation: Root is considered as good.\r\n\r\n
\r\n
Constraints:
\r\n\r\n[1, 10^5]
.[-10^4, 10^4]
.Given an array of integers cost
and an integer target
, return the maximum integer you can paint under the following rules:
(i + 1)
is given by cost[i]
(0-indexed).target
.0
digits.Since the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return "0"
.
\n
Example 1:
\n\n\nInput: cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput: "7772"\nExplanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost("7772") = 2*3+ 3*1 = 9. You could also paint "977", but "7772" is the largest number.\nDigit cost\n 1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5\n\n\n
Example 2:
\n\n\nInput: cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput: "85"\nExplanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost("85") = 7 + 5 = 12.\n\n\n
Example 3:
\n\n\nInput: cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput: "0"\nExplanation: It is impossible to paint any integer with total cost equal to target.\n\n\n
\n
Constraints:
\n\ncost.length == 9
1 <= cost[i], target <= 5000
Given two integer arrays startTime
and endTime
and given an integer queryTime
.
The ith
student started doing their homework at the time startTime[i]
and finished it at time endTime[i]
.
Return the number of students doing their homework at time queryTime
. More formally, return the number of students where queryTime
lays in the interval [startTime[i], endTime[i]]
inclusive.
\n
Example 1:
\n\n\nInput: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput: 1\nExplanation: We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\n\n\n
Example 2:
\n\n\nInput: startTime = [4], endTime = [4], queryTime = 4\nOutput: 1\nExplanation: The only student was doing their homework at the queryTime.\n\n\n
\n
Constraints:
\n\nstartTime.length == endTime.length
1 <= startTime.length <= 100
1 <= startTime[i] <= endTime[i] <= 1000
1 <= queryTime <= 1000
Given a sentence text
(A sentence is a string of space-separated words) in the following format:
text
are separated by a single space.Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.
\n\nReturn the new text following the format shown above.
\n\n\n
Example 1:
\n\n\nInput: text = "Leetcode is cool"\nOutput: "Is cool leetcode"\nExplanation: There are 3 words, "Leetcode" of length 8, "is" of length 2 and "cool" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.\n\n\n
Example 2:
\n\n\nInput: text = "Keep calm and code on"\nOutput: "On and keep calm code"\nExplanation: Output is ordered as follows:\n"On" 2 letters.\n"and" 3 letters.\n"keep" 4 letters in case of tie order by position in original text.\n"calm" 4 letters.\n"code" 4 letters.\n\n\n
Example 3:
\n\n\nInput: text = "To be or not to be"\nOutput: "To be or to be not"\n\n\n
\n
Constraints:
\n\ntext
begins with a capital letter and then contains lowercase letters and single space between words.1 <= text.length <= 10^5
Given the array favoriteCompanies
where favoriteCompanies[i]
is the list of favorites companies for the ith
person (indexed from 0).
Return the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.
\n\n\n
Example 1:
\n\n\nInput: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]\nOutput: [0,1,4] \nExplanation: \nPerson with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\n\n\n
Example 2:
\n\n\nInput: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]\nOutput: [0,1] \nExplanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].\n\n\n
Example 3:
\n\n\nInput: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]\nOutput: [0,1,2,3]\n\n\n
\n
Constraints:
\n\n1 <= favoriteCompanies.length <= 100
1 <= favoriteCompanies[i].length <= 500
1 <= favoriteCompanies[i][j].length <= 20
favoriteCompanies[i]
are distinct.favoriteCompanies[i] != favoriteCompanies[j].
Alice is throwing n
darts on a very large wall. You are given an array darts
where darts[i] = [xi, yi]
is the position of the ith
dart that Alice threw on the wall.
Bob knows the positions of the n
darts on the wall. He wants to place a dartboard of radius r
on the wall so that the maximum number of darts that Alice throws lie on the dartboard.
Given the integer r
, return the maximum number of darts that can lie on the dartboard.
\n
Example 1:
\n\nInput: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput: 4\nExplanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n\n\n
Example 2:
\n\nInput: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput: 5\nExplanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n\n\n
\n
Constraints:
\n\n1 <= darts.length <= 100
darts[i].length == 2
-104 <= xi, yi <= 104
darts
are unique1 <= r <= 5000
Given a sentence
that consists of some words separated by a single space, and a searchWord
, check if searchWord
is a prefix of any word in sentence
.
Return the index of the word in sentence
(1-indexed) where searchWord
is a prefix of this word. If searchWord
is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1
.
A prefix of a string s
is any leading contiguous substring of s
.
\n
Example 1:
\n\n\nInput: sentence = "i love eating burger", searchWord = "burg"\nOutput: 4\nExplanation: "burg" is prefix of "burger" which is the 4th word in the sentence.\n\n\n
Example 2:
\n\n\nInput: sentence = "this problem is an easy problem", searchWord = "pro"\nOutput: 2\nExplanation: "pro" is prefix of "problem" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.\n\n\n
Example 3:
\n\n\nInput: sentence = "i am tired", searchWord = "you"\nOutput: -1\nExplanation: "you" is not a prefix of any word in the sentence.\n\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 100
1 <= searchWord.length <= 10
sentence
consists of lowercase English letters and spaces.searchWord
consists of lowercase English letters.Given a string s
and an integer k
, return the maximum number of vowel letters in any substring of s
with length k
.
Vowel letters in English are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
\n
Example 1:
\n\n\nInput: s = "abciiidef", k = 3\nOutput: 3\nExplanation: The substring "iii" contains 3 vowel letters.\n\n\n
Example 2:
\n\n\nInput: s = "aeiou", k = 2\nOutput: 2\nExplanation: Any substring of length 2 contains 2 vowels.\n\n\n
Example 3:
\n\n\nInput: s = "leetcode", k = 3\nOutput: 2\nExplanation: "lee", "eet" and "ode" contain 2 vowels.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.1 <= k <= s.length
Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.
\n\nReturn the number of pseudo-palindromic paths going from the root node to leaf nodes.
\n\n\n
Example 1:
\n\n\nInput: root = [2,3,1,3,1,null,1]\nOutput: 2 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\n\n
Example 2:
\n\n\nInput: root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput: 1 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).\n\n\n
Example 3:
\n\n\nInput: root = [9]\nOutput: 1\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 9
Given two arrays nums1
and nums2
.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
\n\nA subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5]
is a subsequence of [1,2,3,4,5]
while [1,5,3]
is not).
\n
Example 1:
\n\n\nInput: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput: 18\nExplanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.\n\n
Example 2:
\n\n\nInput: nums1 = [3,-2], nums2 = [2,-6,7]\nOutput: 21\nExplanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.\n\n
Example 3:
\n\n\nInput: nums1 = [-1,-1], nums2 = [1,1]\nOutput: -1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 500
-1000 <= nums1[i], nums2[i] <= 1000
You are given two integer arrays of equal length target
and arr
. In one step, you can select any non-empty subarray of arr
and reverse it. You are allowed to make any number of steps.
Return true
if you can make arr
equal to target
or false
otherwise.
\n
Example 1:
\n\n\nInput: target = [1,2,3,4], arr = [2,4,1,3]\nOutput: true\nExplanation: You can follow the next steps to convert arr to target:\n1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]\n2- Reverse subarray [4,2], arr becomes [1,2,4,3]\n3- Reverse subarray [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.\n\n\n
Example 2:
\n\n\nInput: target = [7], arr = [7]\nOutput: true\nExplanation: arr is equal to target without any reverses.\n\n\n
Example 3:
\n\n\nInput: target = [3,7,9], arr = [3,7,11]\nOutput: false\nExplanation: arr does not have value 9 and it can never be converted to target.\n\n\n
\n
Constraints:
\n\ntarget.length == arr.length
1 <= target.length <= 1000
1 <= target[i] <= 1000
1 <= arr[i] <= 1000
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
.
\n
Example 1:
\n\n\nInput: s = "00110110", k = 2\nOutput: true\nExplanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n\n\n
Example 2:
\n\n\nInput: s = "0110", k = 1\nOutput: true\nExplanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. \n\n\n
Example 3:
\n\n\nInput: s = "0110", k = 2\nOutput: false\nExplanation: The binary code "00" is of length 2 and does not exist in the array.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 105
s[i]
is either '0'
or '1'
.1 <= k <= 20
There are a total of numCourses
courses you have to take, labeled from 0
to numCourses - 1
. You are given an array prerequisites
where prerequisites[i] = [ai, bi]
indicates that you must take course ai
first if you want to take course bi
.
[0, 1]
indicates that you have to take course 0
before you can take course 1
.Prerequisites can also be indirect. If course a
is a prerequisite of course b
, and course b
is a prerequisite of course c
, then course a
is a prerequisite of course c
.
You are also given an array queries
where queries[j] = [uj, vj]
. For the jth
query, you should answer whether course uj
is a prerequisite of course vj
or not.
Return a boolean array answer
, where answer[j]
is the answer to the jth
query.
\n
Example 1:
\n\nInput: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput: [false,true]\nExplanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.\n\n\n
Example 2:
\n\n\nInput: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput: [false,false]\nExplanation: There are no prerequisites, and each course is independent.\n\n\n
Example 3:
\n\nInput: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput: [true,true]\n\n\n
\n
Constraints:
\n\n2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= numCourses - 1
ai != bi
[ai, bi]
are unique.1 <= queries.length <= 104
0 <= ui, vi <= numCourses - 1
ui != vi
You are given a rows x cols
matrix grid
representing a field of cherries where grid[i][j]
represents the number of cherries that you can collect from the (i, j)
cell.
You have two robots that can collect cherries for you:
\n\n(0, 0)
, and(0, cols - 1)
.Return the maximum number of cherries collection using both robots by following the rules below:
\n\n(i, j)
, robots can move to cell (i + 1, j - 1)
, (i + 1, j)
, or (i + 1, j + 1)
.grid
.\n
Example 1:
\n\nInput: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\nOutput: 24\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\nCherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\nTotal of cherries: 12 + 12 = 24.\n\n\n
Example 2:
\n\nInput: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\nOutput: 28\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\nCherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\nTotal of cherries: 17 + 11 = 28.\n\n\n
\n
Constraints:
\n\nrows == grid.length
cols == grid[i].length
2 <= rows, cols <= 70
0 <= grid[i][j] <= 100
nums
, you will choose two different indices i
and j
of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1)
.\n\n
Example 1:
\n\n\nInput: nums = [3,4,5,2]\nOutput: 12 \nExplanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \n\n\n
Example 2:
\n\n\nInput: nums = [1,5,4,5]\nOutput: 16\nExplanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\n\n\n
Example 3:
\n\n\nInput: nums = [3,7]\nOutput: 12\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 500
1 <= nums[i] <= 10^3
You are given a rectangular cake of size h x w
and two arrays of integers horizontalCuts
and verticalCuts
where:
horizontalCuts[i]
is the distance from the top of the rectangular cake to the ith
horizontal cut and similarly, andverticalCuts[j]
is the distance from the left of the rectangular cake to the jth
vertical cut.Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts
and verticalCuts
. Since the answer can be a large number, return this modulo 109 + 7
.
\n
Example 1:
\n\nInput: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput: 4 \nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.\n\n\n
Example 2:
\n\nInput: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput: 6\nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.\n\n\n
Example 3:
\n\n\nInput: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput: 9\n\n\n
\n
Constraints:
\n\n2 <= h, w <= 109
1 <= horizontalCuts.length <= min(h - 1, 105)
1 <= verticalCuts.length <= min(w - 1, 105)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
horizontalCuts
are distinct.verticalCuts
are distinct.There are n
cities numbered from 0
to n - 1
and n - 1
roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections
where connections[i] = [ai, bi]
represents a road from city ai
to city bi
.
This year, there will be a big event in the capital (city 0
), and many people want to travel to this city.
Your task consists of reorienting some roads such that each city can visit the city 0
. Return the minimum number of edges changed.
It's guaranteed that each city can reach city 0
after reorder.
\n
Example 1:
\n\nInput: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\nOutput: 3\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\n
Example 2:
\n\nInput: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\nOutput: 2\nExplanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n\n\n
Example 3:
\n\n\nInput: n = 3, connections = [[1,0],[2,0]]\nOutput: 0\n\n\n
\n
Constraints:
\n\n2 <= n <= 5 * 104
connections.length == n - 1
connections[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
Given 2n
balls of k
distinct colors. You will be given an integer array balls
of size k
where balls[i]
is the number of balls of color i
.
All the balls will be shuffled uniformly at random, then we will distribute the first n
balls to the first box and the remaining n
balls to the other box (Please read the explanation of the second example carefully).
Please note that the two boxes are considered different. For example, if we have two balls of colors a
and b
, and two boxes []
and ()
, then the distribution [a] (b)
is considered different than the distribution [b] (a)
(Please read the explanation of the first example carefully).
Return the probability that the two boxes have the same number of distinct balls. Answers within 10-5
of the actual value will be accepted as correct.
\n
Example 1:
\n\n\nInput: balls = [1,1]\nOutput: 1.00000\nExplanation: Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\n\n\n
Example 2:
\n\n\nInput: balls = [2,1,1]\nOutput: 0.66667\nExplanation: We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667\n\n\n
Example 3:
\n\n\nInput: balls = [1,2,1,2]\nOutput: 0.60000\nExplanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6\n\n\n
\n
Constraints:
\n\n1 <= balls.length <= 8
1 <= balls[i] <= 6
sum(balls)
is even.Given the array nums
consisting of 2n
elements in the form [x1,x2,...,xn,y1,y2,...,yn]
.
Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [2,5,1,3,4,7], n = 3\r\nOutput: [2,3,5,4,1,7] \r\nExplanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [1,2,3,4,4,3,2,1], n = 4\r\nOutput: [1,4,2,3,3,2,4,1]\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: nums = [1,1,2,2], n = 2\r\nOutput: [1,2,1,2]\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= n <= 500
nums.length == 2n
1 <= nums[i] <= 10^3
Given an array of integers arr
and an integer k
.
A value arr[i]
is said to be stronger than a value arr[j]
if |arr[i] - m| > |arr[j] - m|
where m
is the median of the array.
\nIf |arr[i] - m| == |arr[j] - m|
, then arr[i]
is said to be stronger than arr[j]
if arr[i] > arr[j]
.
Return a list of the strongest k
values in the array. return the answer in any arbitrary order.
Median is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2)
in the sorted list (0-indexed).
arr = [6, -3, 7, 2, 11]
, n = 5
and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11]
and the median is arr[m]
where m = ((5 - 1) / 2) = 2
. The median is 6
.arr = [-7, 22, 17, 3]
, n = 4
and the median is obtained by sorting the array arr = [-7, 3, 17, 22]
and the median is arr[m]
where m = ((4 - 1) / 2) = 1
. The median is 3
.\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\n\n\n
Example 3:
\n\n\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
-105 <= arr[i] <= 105
1 <= k <= arr.length
Given an array of integers arr
and an integer k
.
A value arr[i]
is said to be stronger than a value arr[j]
if |arr[i] - m| > |arr[j] - m|
where m
is the centre of the array.
\nIf |arr[i] - m| == |arr[j] - m|
, then arr[i]
is said to be stronger than arr[j]
if arr[i] > arr[j]
.
Return a list of the strongest k
values in the array. return the answer in any arbitrary order.
The centre is the middle value in an ordered integer list. More formally, if the length of the list is n, the centre is the element in position ((n - 1) / 2)
in the sorted list (0-indexed).
arr = [6, -3, 7, 2, 11]
, n = 5
and the centre is obtained by sorting the array arr = [-3, 2, 6, 7, 11]
and the centre is arr[m]
where m = ((5 - 1) / 2) = 2
. The centre is 6
.arr = [-7, 22, 17, 3]
, n = 4
and the centre is obtained by sorting the array arr = [-7, 3, 17, 22]
and the centre is arr[m]
where m = ((4 - 1) / 2) = 1
. The centre is 3
.\n\n
\n
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Centre is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\n\n\n
Example 2:
\n\n\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Centre is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\n\n\n
Example 3:
\n\n\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Centre is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
-105 <= arr[i] <= 105
1 <= k <= arr.length
You have a browser of one tab where you start on the homepage
and you can visit another url
, get back in the history number of steps
or move forward in the history number of steps
.
Implement the BrowserHistory
class:
BrowserHistory(string homepage)
Initializes the object with the homepage
of the browser.void visit(string url)
Visits url
from the current page. It clears up all the forward history.string back(int steps)
Move steps
back in history. If you can only return x
steps in the history and steps > x
, you will return only x
steps. Return the current url
after moving back in history at most steps
.string forward(int steps)
Move steps
forward in history. If you can only forward x
steps in the history and steps > x
, you will forward only x
steps. Return the current url
after forwarding in history at most steps
.\n
Example:
\n\n\nInput:\n["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]\n[["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]\nOutput:\n[null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]\n\nExplanation:\nBrowserHistory browserHistory = new BrowserHistory("leetcode.com");\nbrowserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"\nbrowserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"\nbrowserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"\nbrowserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"\nbrowserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"\nbrowserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"\nbrowserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"\nbrowserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.\nbrowserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"\nbrowserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"\n\n\n
\n
Constraints:
\n\n1 <= homepage.length <= 20
1 <= url.length <= 20
1 <= steps <= 100
homepage
and url
consist of '.' or lower case English letters.5000
calls will be made to visit
, back
, and forward
.There is a row of m
houses in a small city, each house must be painted with one of the n
colors (labeled from 1
to n
), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
\n\nhouses = [1,2,2,3,3,2,1,1]
contains 5
neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}]
.Given an array houses
, an m x n
matrix cost
and an integer target
where:
houses[i]
: is the color of the house i
, and 0
if the house is not painted yet.cost[i][j]
: is the cost of paint the house i
with the color j + 1
.Return the minimum cost of painting all the remaining houses in such a way that there are exactly target
neighborhoods. If it is not possible, return -1
.
\n
Example 1:
\n\n\nInput: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 9\nExplanation: Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n\n\n
Example 2:
\n\n\nInput: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 11\nExplanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.\n\n\n
Example 3:
\n\n\nInput: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput: -1\nExplanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n\n\n
\n
Constraints:
\n\nm == houses.length == cost.length
n == cost[i].length
1 <= m <= 100
1 <= n <= 20
1 <= target <= m
0 <= houses[i] <= n
1 <= cost[i][j] <= 104
You are given an integer array prices
where prices[i]
is the price of the ith
item in a shop.
There is a special discount for items in the shop. If you buy the ith
item, then you will receive a discount equivalent to prices[j]
where j
is the minimum index such that j > i
and prices[j] <= prices[i]
. Otherwise, you will not receive any discount at all.
Return an integer array answer
where answer[i]
is the final price you will pay for the ith
item of the shop, considering the special discount.
\n
Example 1:
\n\n\nInput: prices = [8,4,6,2,3]\nOutput: [4,2,4,2,3]\nExplanation: \nFor item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.\nFor items 3 and 4 you will not receive any discount at all.\n\n\n
Example 2:
\n\n\nInput: prices = [1,2,3,4,5]\nOutput: [1,2,3,4,5]\nExplanation: In this case, for all items, you will not receive any discount at all.\n\n\n
Example 3:
\n\n\nInput: prices = [10,1,1,6]\nOutput: [9,0,1,6]\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 500
1 <= prices[i] <= 1000
Implement the class SubrectangleQueries
which receives a rows x cols
rectangle as a matrix of integers in the constructor and supports two methods:
1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
newValue
in the subrectangle whose upper left coordinate is (row1,col1)
and bottom right coordinate is (row2,col2)
.2. getValue(int row, int col)
(row,col)
from the rectangle.\n
Example 1:
\n\n\nInput\n["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue","getValue"]\n[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]\nOutput\n[null,1,null,5,5,null,10,5]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n// The initial rectangle (4x3) looks like:\n// 1 2 1\n// 4 3 4\n// 3 2 1\n// 1 1 1\nsubrectangleQueries.getValue(0, 2); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 5 5 5 \nsubrectangleQueries.getValue(0, 2); // return 5\nsubrectangleQueries.getValue(3, 1); // return 5\nsubrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n// After this update the rectangle looks like:\n// 5 5 5\n// 5 5 5\n// 5 5 5\n// 10 10 10 \nsubrectangleQueries.getValue(3, 1); // return 10\nsubrectangleQueries.getValue(0, 2); // return 5\n\n\n
Example 2:
\n\n\nInput\n["SubrectangleQueries","getValue","updateSubrectangle","getValue","getValue","updateSubrectangle","getValue"]\n[[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]\nOutput\n[null,1,null,100,100,null,20]\nExplanation\nSubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\nsubrectangleQueries.getValue(0, 0); // return 1\nsubrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\nsubrectangleQueries.getValue(0, 0); // return 100\nsubrectangleQueries.getValue(2, 2); // return 100\nsubrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\nsubrectangleQueries.getValue(2, 2); // return 20\n\n\n
\n
Constraints:
\n\n500
operations considering both methods: updateSubrectangle
and getValue
.1 <= rows, cols <= 100
rows == rectangle.length
cols == rectangle[i].length
0 <= row1 <= row2 < rows
0 <= col1 <= col2 < cols
1 <= newValue, rectangle[i][j] <= 10^9
0 <= row < rows
0 <= col < cols
You are given an array of integers arr
and an integer target
.
You have to find two non-overlapping sub-arrays of arr
each with a sum equal target
. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1
if you cannot find such two sub-arrays.
\n
Example 1:
\n\n\nInput: arr = [3,2,2,4,3], target = 3\nOutput: 2\nExplanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\n\n\n
Example 2:
\n\n\nInput: arr = [7,3,4,7], target = 7\nOutput: 2\nExplanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\n\n\n
Example 3:
\n\n\nInput: arr = [4,3,2,6,2,3,4], target = 6\nOutput: -1\nExplanation: We have only one sub-array of sum = 6.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i] <= 1000
1 <= target <= 108
Given the array houses
where houses[i]
is the location of the ith
house along a street and an integer k
, allocate k
mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
\n\nThe test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n\n\n
Example 2:
\n\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n\n\n
\n
Constraints:
\n\n1 <= k <= houses.length <= 100
1 <= houses[i] <= 104
houses
are unique.Given an array nums
. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i])
.
Return the running sum of nums
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: [1,3,6,10]\nExplanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1,1]\nOutput: [1,2,3,4,5]\nExplanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].\n\n
Example 3:
\n\n\nInput: nums = [3,1,2,10,1]\nOutput: [3,4,6,16,17]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6
Given an array of integers arr
and an integer k
. Find the least number of unique integers after removing exactly k
elements.
\r\n
Example 1:
\r\n\r\n\r\nInput: arr = [5,5,4], k = 1\r\nOutput: 1\r\nExplanation: Remove the single 4, only 5 is left.\r\n\r\nExample 2:\r\n\r\n
\r\nInput: arr = [4,3,1,1,3,3,2], k = 3\r\nOutput: 2\r\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= arr.length <= 10^5
1 <= arr[i] <= 10^9
0 <= k <= arr.length
You are given an integer array bloomDay
, an integer m
and an integer k
.
You want to make m
bouquets. To make a bouquet, you need to use k
adjacent flowers from the garden.
The garden consists of n
flowers, the ith
flower will bloom in the bloomDay[i]
and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m
bouquets from the garden. If it is impossible to make m bouquets return -1
.
\n
Example 1:
\n\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput: 3\nExplanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.\n\n\n
Example 2:
\n\n\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput: -1\nExplanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\n\n\n
Example 3:
\n\n\nInput: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput: 12\nExplanation: We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.\n\n\n
\n
Constraints:
\n\nbloomDay.length == n
1 <= n <= 105
1 <= bloomDay[i] <= 109
1 <= m <= 106
1 <= k <= n
You are given a tree with n
nodes numbered from 0
to n - 1
in the form of a parent array parent
where parent[i]
is the parent of ith
node. The root of the tree is node 0
. Find the kth
ancestor of a given node.
The kth
ancestor of a tree node is the kth
node in the path from that node to the root node.
Implement the TreeAncestor
class:
TreeAncestor(int n, int[] parent)
Initializes the object with the number of nodes in the tree and the parent array.int getKthAncestor(int node, int k)
return the kth
ancestor of the given node node
. If there is no such ancestor, return -1
.\n
Example 1:
\n\nInput\n["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"]\n[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]\nOutput\n[null, 1, 0, -1]\n\nExplanation\nTreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\ntreeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\ntreeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\ntreeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n\n
\n
Constraints:
\n\n1 <= k <= n <= 5 * 104
parent.length == n
parent[0] == -1
0 <= parent[i] < n
for all 0 < i < n
0 <= node < n
5 * 104
queries.Table Activities
:
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| sell_date | date |\n| product | varchar |\n+-------------+---------+\nThere is no primary key (column with unique values) for this table. It may contain duplicates.\nEach row of this table contains the product name and the date it was sold in a market.\n\n\n
\n\n
Write a solution to find for each date the number of different products sold and their names.
\n\nThe sold products names for each date should be sorted lexicographically.
\n\nReturn the result table ordered by sell_date
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivities table:\n+------------+------------+\n| sell_date | product |\n+------------+------------+\n| 2020-05-30 | Headphone |\n| 2020-06-01 | Pencil |\n| 2020-06-02 | Mask |\n| 2020-05-30 | Basketball |\n| 2020-06-01 | Bible |\n| 2020-06-02 | Mask |\n| 2020-05-30 | T-Shirt |\n+------------+------------+\nOutput: \n+------------+----------+------------------------------+\n| sell_date | num_sold | products |\n+------------+----------+------------------------------+\n| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |\n| 2020-06-01 | 2 | Bible,Pencil |\n| 2020-06-02 | 1 | Mask |\n+------------+----------+------------------------------+\nExplanation: \nFor 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by a comma.\nFor 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by a comma.\nFor 2020-06-02, the Sold item is (Mask), we just return it.\n\n", - "likes": 1510, - "dislikes": 118, - "stats": "{\"totalAccepted\": \"281.6K\", \"totalSubmission\": \"362.9K\", \"totalAcceptedRaw\": 281610, \"totalSubmissionRaw\": 362935, \"acRate\": \"77.6%\"}", + "likes": 1572, + "dislikes": 122, + "stats": "{\"totalAccepted\": \"320K\", \"totalSubmission\": \"411.9K\", \"totalAcceptedRaw\": 320027, \"totalSubmissionRaw\": 411854, \"acRate\": \"77.7%\"}", "similarQuestions": "[{\"title\": \"Finding the Topic of Each Post\", \"titleSlug\": \"finding-the-topic-of-each-post\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -55931,9 +56003,9 @@ "questionFrontendId": "1485", "title": "Clone Binary Tree With Random Pointer", "content": null, - "likes": 424, - "dislikes": 88, - "stats": "{\"totalAccepted\": \"30.8K\", \"totalSubmission\": \"38.2K\", \"totalAcceptedRaw\": 30827, \"totalSubmissionRaw\": 38202, \"acRate\": \"80.7%\"}", + "likes": 427, + "dislikes": 90, + "stats": "{\"totalAccepted\": \"33.1K\", \"totalSubmission\": \"40.9K\", \"totalAcceptedRaw\": 33124, \"totalSubmissionRaw\": 40933, \"acRate\": \"80.9%\"}", "similarQuestions": "[{\"title\": \"Clone Graph\", \"titleSlug\": \"clone-graph\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Copy List with Random Pointer\", \"titleSlug\": \"copy-list-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone N-ary Tree\", \"titleSlug\": \"clone-n-ary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -55977,9 +56049,9 @@ "questionFrontendId": "1486", "title": "XOR Operation in an Array", "content": "
You are given an integer n
and an integer start
.
Define an array nums
where nums[i] = start + 2 * i
(0-indexed) and n == nums.length
.
Return the bitwise XOR of all elements of nums
.
\n
Example 1:
\n\n\nInput: n = 5, start = 0\nOutput: 8\nExplanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere "^" corresponds to bitwise XOR operator.\n\n\n
Example 2:
\n\n\nInput: n = 4, start = 3\nOutput: 8\nExplanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
0 <= start <= 1000
n == nums.length
Given an array of strings names
of size n
. You will create n
folders in your file system such that, at the ith
minute, you will create a folder with the name names[i]
.
Since two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k)
, where, k
is the smallest positive integer such that the obtained name remains unique.
Return an array of strings of length n
where ans[i]
is the actual name the system will assign to the ith
folder when you create it.
\n
Example 1:
\n\n\nInput: names = ["pes","fifa","gta","pes(2019)"]\nOutput: ["pes","fifa","gta","pes(2019)"]\nExplanation: Let's see how the file system creates folder names:\n"pes" --> not assigned before, remains "pes"\n"fifa" --> not assigned before, remains "fifa"\n"gta" --> not assigned before, remains "gta"\n"pes(2019)" --> not assigned before, remains "pes(2019)"\n\n\n
Example 2:
\n\n\nInput: names = ["gta","gta(1)","gta","avalon"]\nOutput: ["gta","gta(1)","gta(2)","avalon"]\nExplanation: Let's see how the file system creates folder names:\n"gta" --> not assigned before, remains "gta"\n"gta(1)" --> not assigned before, remains "gta(1)"\n"gta" --> the name is reserved, system adds (k), since "gta(1)" is also reserved, systems put k = 2. it becomes "gta(2)"\n"avalon" --> not assigned before, remains "avalon"\n\n\n
Example 3:
\n\n\nInput: names = ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]\nOutput: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]\nExplanation: When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4)".\n\n\n
\n
Constraints:
\n\n1 <= names.length <= 5 * 104
1 <= names[i].length <= 20
names[i]
consists of lowercase English letters, digits, and/or round brackets.Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth
lake, the nth
lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.
Given an integer array rains
where:
rains[i] > 0
means there will be rains over the rains[i]
lake.rains[i] == 0
means there are no rains this day and you can choose one lake this day and dry it.Return an array ans
where:
ans.length == rains.length
ans[i] == -1
if rains[i] > 0
.ans[i]
is the lake you choose to dry in the ith
day if rains[i] == 0
.If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.
\n\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
\n\n\n
Example 1:
\n\n\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.\n\n\n
Example 2:
\n\n\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\n\n\n
Example 3:
\n\n\nInput: rains = [1,2,0,1,2]\nOutput: []\nExplanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.\n\n\n
\n
Constraints:
\n\n1 <= rains.length <= 105
0 <= rains[i] <= 109
Given a weighted undirected connected graph with n
vertices numbered from 0
to n - 1
, and an array edges
where edges[i] = [ai, bi, weighti]
represents a bidirectional and weighted edge between nodes ai
and bi
. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
\n\nNote that you can return the indices of the edges in any order.
\n\n\n
Example 1:
\n\n\nInput: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput: [[0,1],[2,3,4,5]]\nExplanation: The figure above describes the graph.\nThe following figure shows all the possible MSTs:\n\n\n\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n
Example 2:
\n\n\nInput: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput: [[],[0,1,2,3]]\nExplanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
1 <= edges.length <= min(200, n * (n - 1) / 2)
edges[i].length == 3
0 <= ai < bi < n
1 <= weighti <= 1000
(ai, bi)
are distinct.You are given an array of unique integers salary
where salary[i]
is the salary of the ith
employee.
Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: salary = [4000,3000,1000,2000]\nOutput: 2500.00000\nExplanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\nAverage salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500\n\n\n
Example 2:
\n\n\nInput: salary = [1000,2000,3000]\nOutput: 2000.00000\nExplanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\nAverage salary excluding minimum and maximum salary is (2000) / 1 = 2000\n\n\n
\n
Constraints:
\n\n3 <= salary.length <= 100
1000 <= salary[i] <= 106
salary
are unique.You are given two positive integers n
and k
. A factor of an integer n
is defined as an integer i
where n % i == 0
.
Consider a list of all factors of n
sorted in ascending order, return the kth
factor in this list or return -1
if n
has less than k
factors.
\n
Example 1:
\n\n\nInput: n = 12, k = 3\nOutput: 3\nExplanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.\n\n\n
Example 2:
\n\n\nInput: n = 7, k = 2\nOutput: 7\nExplanation: Factors list is [1, 7], the 2nd factor is 7.\n\n\n
Example 3:
\n\n\nInput: n = 4, k = 4\nOutput: -1\nExplanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 1000
\n
Follow up:
\n\nCould you solve this problem in less than O(n) complexity?
\n", - "likes": 1856, - "dislikes": 303, - "stats": "{\"totalAccepted\": \"300.6K\", \"totalSubmission\": \"434.7K\", \"totalAcceptedRaw\": 300569, \"totalSubmissionRaw\": 434710, \"acRate\": \"69.1%\"}", + "likes": 1889, + "dislikes": 307, + "stats": "{\"totalAccepted\": \"326.2K\", \"totalSubmission\": \"468.8K\", \"totalAcceptedRaw\": 326172, \"totalSubmissionRaw\": 468828, \"acRate\": \"69.6%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -56253,9 +56325,9 @@ "questionFrontendId": "1493", "title": "Longest Subarray of 1's After Deleting One Element", "content": "Given a binary array nums
, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1
's in the resulting array. Return 0
if there is no such subarray.
\n
Example 1:
\n\n\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.You are given an integer n
, which indicates that there are n
courses labeled from 1
to n
. You are also given an array relations
where relations[i] = [prevCoursei, nextCoursei]
, representing a prerequisite relationship between course prevCoursei
and course nextCoursei
: course prevCoursei
has to be taken before course nextCoursei
. Also, you are given the integer k
.
In one semester, you can take at most k
courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.
Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.
\n\n\n
Example 1:
\n\nInput: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2\nOutput: 3\nExplanation: The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.\n\n\n
Example 2:
\n\nInput: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput: 4\nExplanation: The figure above represents the given graph.\nIn the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.\n\n\n
\n
Constraints:
\n\n1 <= n <= 15
1 <= k <= n
0 <= relations.length <= n * (n-1) / 2
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
[prevCoursei, nextCoursei]
are unique.Given a string path
, where path[i] = 'N'
, 'S'
, 'E'
or 'W'
, each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0)
on a 2D plane and walk on the path specified by path
.
Return true
if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false
otherwise.
\n
Example 1:
\n\nInput: path = "NES"\nOutput: false \nExplanation: Notice that the path doesn't cross any point more than once.\n\n\n
Example 2:
\n\nInput: path = "NESWW"\nOutput: true\nExplanation: Notice that the path visits the origin twice.\n\n
\n
Constraints:
\n\n1 <= path.length <= 104
path[i]
is either 'N'
, 'S'
, 'E'
, or 'W'
.Given an array of integers arr
of even length n
and an integer k
.
We want to divide the array into exactly n / 2
pairs such that the sum of each pair is divisible by k
.
Return true
If you can find a way to do that or false
otherwise.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput: true\nExplanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,3,4,5,6], k = 7\nOutput: true\nExplanation: Pairs are (1,6),(2,5) and(3,4).\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,3,4,5,6], k = 10\nOutput: false\nExplanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.\n\n\n
\n
Constraints:
\n\narr.length == n
1 <= n <= 105
n
is even.-109 <= arr[i] <= 109
1 <= k <= 105
You are given an array of integers nums
and an integer target
.
Return the number of non-empty subsequences of nums
such that the sum of the minimum and maximum element on it is less or equal to target
. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [3,5,6,7], target = 9\nOutput: 4\nExplanation: There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)\n\n\n
Example 2:
\n\n\nInput: nums = [3,3,6,8], target = 10\nOutput: 6\nExplanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]\n\n\n
Example 3:
\n\n\nInput: nums = [2,3,3,4,6,7], target = 12\nOutput: 61\nExplanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= target <= 106
You are given an array points
containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi]
such that xi < xj
for all 1 <= i < j <= points.length
. You are also given an integer k
.
Return the maximum value of the equation yi + yj + |xi - xj|
where |xi - xj| <= k
and 1 <= i < j <= points.length
.
It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k
.
\n
Example 1:
\n\n\nInput: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\nOutput: 4\nExplanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.\n\n\n
Example 2:
\n\n\nInput: points = [[0,0],[3,0],[9,2]], k = 3\nOutput: 3\nExplanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.\n\n\n
\n
Constraints:
\n\n2 <= points.length <= 105
points[i].length == 2
-108 <= xi, yi <= 108
0 <= k <= 2 * 108
xi < xj
for all 1 <= i < j <= points.length
xi
form a strictly increasing sequence.A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
\n\nGiven an array of numbers arr
, return true
if the array can be rearranged to form an arithmetic progression. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: arr = [3,5,1]\nOutput: true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,4]\nOutput: false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 1000
-106 <= arr[i] <= 106
We have a wooden plank of the length n
units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.
When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.
\n\nWhen an ant reaches one end of the plank at a time t
, it falls out of the plank immediately.
Given an integer n
and two integer arrays left
and right
, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.
\n
Example 1:
\n\nInput: n = 4, left = [4,3], right = [0,1]\nOutput: 4\nExplanation: In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).\n\n\n
Example 2:
\n\nInput: n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput: 7\nExplanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.\n\n\n
Example 3:
\n\nInput: n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput: 7\nExplanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
0 <= left.length <= n + 1
0 <= left[i] <= n
0 <= right.length <= n + 1
0 <= right[i] <= n
1 <= left.length + right.length <= n + 1
left
and right
are unique, and each value can appear only in one of the two arrays.Given an m x n
binary matrix mat
, return the number of submatrices that have all ones.
\n
Example 1:
\n\nInput: mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput: 13\nExplanation: \nThere are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.\n\n\n
Example 2:
\n\nInput: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput: 24\nExplanation: \nThere are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 150
mat[i][j]
is either 0
or 1
.You are given a string num
representing the digits of a very large integer and an integer k
. You are allowed to swap any two adjacent digits of the integer at most k
times.
Return the minimum integer you can obtain also as a string.
\n\n\n
Example 1:
\n\nInput: num = "4321", k = 4\nOutput: "1342"\nExplanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n\n\n
Example 2:
\n\n\nInput: num = "100", k = 1\nOutput: "010"\nExplanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n\n\n
Example 3:
\n\n\nInput: num = "36789", k = 1000\nOutput: "36789"\nExplanation: We can keep the number without any swaps.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 3 * 104
num
consists of only digits and does not contain leading zeros.1 <= k <= 109
Given a date
string in the form Day Month Year
, where:
Day
is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}
.Month
is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
.Year
is in the range [1900, 2100]
.Convert the date string to the format YYYY-MM-DD
, where:
YYYY
denotes the 4 digit year.MM
denotes the 2 digit month.DD
denotes the 2 digit day.\n
Example 1:
\n\n\nInput: date = "20th Oct 2052"\nOutput: "2052-10-20"\n\n\n
Example 2:
\n\n\nInput: date = "6th Jun 1933"\nOutput: "1933-06-06"\n\n\n
Example 3:
\n\n\nInput: date = "26th May 1960"\nOutput: "1960-05-26"\n\n\n
\n
Constraints:
\n\nYou are given the array nums
consisting of n
positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2
numbers.
Return the sum of the numbers from index left
to index right
(indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput: 13 \nExplanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. \n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput: 6\nExplanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput: 50\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= nums.length <= 1000
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2
You are given an integer array nums
.
In one move, you can choose one element of nums
and change it to any value.
Return the minimum difference between the largest and smallest value of nums
after performing at most three moves.
\n
Example 1:
\n\n\nInput: nums = [5,3,2,4]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 2 to 3. nums becomes [5,3,3,4].\nIn the second move, change 4 to 3. nums becomes [5,3,3,3].\nIn the third move, change 5 to 3. nums becomes [3,3,3,3].\nAfter performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.\n\n\n
Example 2:
\n\n\nInput: nums = [1,5,0,10,14]\nOutput: 1\nExplanation: We can make at most 3 moves.\nIn the first move, change 5 to 0. nums becomes [1,0,0,10,14].\nIn the second move, change 10 to 0. nums becomes [1,0,0,0,14].\nIn the third move, change 14 to 1. nums becomes [1,0,0,0,1].\nAfter performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.\nIt can be shown that there is no way to make the difference 0 in 3 moves.\n\n
Example 3:
\n\n\nInput: nums = [3,100,20]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 100 to 7. nums becomes [3,7,20].\nIn the second move, change 20 to 7. nums becomes [3,7,7].\nIn the third move, change 3 to 7. nums becomes [7,7,7].\nAfter performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
Alice and Bob take turns playing a game, with Alice starting first.
\n\nInitially, there are n
stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
\n\nGiven a positive integer n
, return true
if and only if Alice wins the game otherwise return false
, assuming both players play optimally.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: true\nExplanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
Given an array of integers nums
, return the number of good pairs.
A pair (i, j)
is called good if nums[i] == nums[j]
and i
< j
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1,1,3]\nOutput: 4\nExplanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1]\nOutput: 6\nExplanation: Each pair in the array are good.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
Given a binary string s
, return the number of substrings with all characters 1
's. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "0110111"\nOutput: 9\nExplanation: There are 9 substring in total with only 1's characters.\n"1" -> 5 times.\n"11" -> 3 times.\n"111" -> 1 time.\n\n
Example 2:
\n\n\nInput: s = "101"\nOutput: 2\nExplanation: Substring "1" is shown 2 times in s.\n\n\n
Example 3:
\n\n\nInput: s = "111111"\nOutput: 21\nExplanation: Each substring contains only 1's characters.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.You are given an undirected weighted graph of n
nodes (0-indexed), represented by an edge list where edges[i] = [a, b]
is an undirected edge connecting the nodes a
and b
with a probability of success of traversing that edge succProb[i]
.
Given two nodes start
and end
, find the path with the maximum probability of success to go from start
to end
and return its success probability.
If there is no path from start
to end
, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
\n
Example 1:
\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput: 0.25000\nExplanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\n\n\n
Example 2:
\n\n\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput: 0.30000\n\n\n
Example 3:
\n\n\nInput: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput: 0.00000\nExplanation: There is no path between 0 and 2.\n\n\n
\n
Constraints:
\n\n2 <= n <= 10^4
0 <= start, end < n
start != end
0 <= a, b < n
a != b
0 <= succProb.length == edges.length <= 2*10^4
0 <= succProb[i] <= 1
A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.
\n\nGiven an array positions
where positions[i] = [xi, yi]
is the position of the ith
customer on the map, return the minimum sum of the euclidean distances to all customers.
In other words, you need to choose the position of the service center [xcentre, ycentre]
such that the following formula is minimized:
Answers within 10-5
of the actual value will be accepted.
\n
Example 1:
\n\nInput: positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput: 4.00000\nExplanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n\n\n
Example 2:
\n\nInput: positions = [[1,1],[3,3]]\nOutput: 2.82843\nExplanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n\n\n
\n
Constraints:
\n\n1 <= positions.length <= 50
positions[i].length == 2
0 <= xi, yi <= 100
Table: Users
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| user_id | int |\n| name | varchar |\n| mail | varchar |\n+---------------+---------+\nuser_id is the primary key (column with unique values) for this table.\nThis table contains information of the users signed up in a website. Some e-mails are invalid.\n\n\n
\n\n
Write a solution to find the users who have valid emails.
\n\nA valid e-mail has a prefix name and a domain where:
\n\n'_'
, period '.'
, and/or dash '-'
. The prefix name must start with a letter.'@leetcode.com'
.Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+---------+-----------+-------------------------+\n| user_id | name | mail |\n+---------+-----------+-------------------------+\n| 1 | Winston | winston@leetcode.com |\n| 2 | Jonathan | jonathanisgreat |\n| 3 | Annabelle | bella-@leetcode.com |\n| 4 | Sally | sally.come@leetcode.com |\n| 5 | Marwan | quarz#2020@leetcode.com |\n| 6 | David | david69@gmail.com |\n| 7 | Shapiro | .shapo@leetcode.com |\n+---------+-----------+-------------------------+\nOutput: \n+---------+-----------+-------------------------+\n| user_id | name | mail |\n+---------+-----------+-------------------------+\n| 1 | Winston | winston@leetcode.com |\n| 3 | Annabelle | bella-@leetcode.com |\n| 4 | Sally | sally.come@leetcode.com |\n+---------+-----------+-------------------------+\nExplanation: \nThe mail of user 2 does not have a domain.\nThe mail of user 5 has the # sign which is not allowed.\nThe mail of user 6 does not have the leetcode domain.\nThe mail of user 7 starts with a period.\n\n", - "likes": 539, - "dislikes": 265, - "stats": "{\"totalAccepted\": \"180.1K\", \"totalSubmission\": \"409.1K\", \"totalAcceptedRaw\": 180114, \"totalSubmissionRaw\": 409088, \"acRate\": \"44.0%\"}", + "likes": 599, + "dislikes": 273, + "stats": "{\"totalAccepted\": \"217.5K\", \"totalSubmission\": \"488.8K\", \"totalAcceptedRaw\": 217470, \"totalSubmissionRaw\": 488849, \"acRate\": \"44.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -57210,9 +57285,9 @@ "questionFrontendId": "1518", "title": "Water Bottles", "content": "
There are numBottles
water bottles that are initially full of water. You can exchange numExchange
empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
\n\nGiven the two integers numBottles
and numExchange
, return the maximum number of water bottles you can drink.
\n
Example 1:
\n\nInput: numBottles = 9, numExchange = 3\nOutput: 13\nExplanation: You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.\n\n\n
Example 2:
\n\nInput: numBottles = 15, numExchange = 4\nOutput: 19\nExplanation: You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.\n\n\n
\n
Constraints:
\n\n1 <= numBottles <= 100
2 <= numExchange <= 100
You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n
nodes numbered from 0
to n - 1
and exactly n - 1
edges
. The root of the tree is the node 0
, and each node of the tree has a label which is a lower-case character given in the string labels
(i.e. The node with the number i
has the label labels[i]
).
The edges
array is given on the form edges[i] = [ai, bi]
, which means there is an edge between nodes ai
and bi
in the tree.
Return an array of size n
where ans[i]
is the number of nodes in the subtree of the ith
node which have the same label as node i
.
A subtree of a tree T
is the tree consisting of a node in T
and all of its descendant nodes.
\n
Example 1:
\n\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = "abaedcd"\nOutput: [2,1,1,1,1,1,1]\nExplanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\n\n\n
Example 2:
\n\nInput: n = 4, edges = [[0,1],[1,2],[0,3]], labels = "bbbb"\nOutput: [4,2,1,1]\nExplanation: The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\n\n\n
Example 3:
\n\nInput: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = "aabab"\nOutput: [3,2,1,1,1]\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
labels.length == n
labels
is consisting of only of lowercase English letters.Given a string s
of lowercase letters, you need to find the maximum number of non-empty substrings of s
that meet the following conditions:
s[i..j]
and s[x..y]
, either j < x
or i > y
is true.c
must also contain all occurrences of c
.Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.
\n\nNotice that you can return the substrings in any order.
\n\n\n
Example 1:
\n\n\nInput: s = "adefaddaccc"\nOutput: ["e","f","ccc"]\nExplanation: The following are all the possible substrings that meet the conditions:\n[\n "adefaddaccc"\n "adefadda",\n "ef",\n "e",\n "f",\n "ccc",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.\n\n\n
Example 2:
\n\n\nInput: s = "abbaccd"\nOutput: ["d","bb","cc"]\nExplanation: Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
contains only lowercase English letters.Winston was given the above mysterious function func
. He has an integer array arr
and an integer target
and he wants to find the values l
and r
that make the value |func(arr, l, r) - target|
minimum possible.
Return the minimum possible value of |func(arr, l, r) - target|
.
Notice that func
should be called with the values l
and r
where 0 <= l, r < arr.length
.
\n
Example 1:
\n\n\nInput: arr = [9,12,3,7,15], target = 5\nOutput: 2\nExplanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\n\n\n
Example 2:
\n\n\nInput: arr = [1000000,1000000,1000000], target = 1\nOutput: 999999\nExplanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,4,8,16], target = 0\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i] <= 106
0 <= target <= 107
Given two non-negative integers low
and high
. Return the count of odd numbers between low
and high
(inclusive).
\r\n
Example 1:
\r\n\r\n\r\nInput: low = 3, high = 7\r\nOutput: 3\r\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: low = 8, high = 10\r\nOutput: 1\r\nExplanation: The odd numbers between 8 and 10 are [9].\r\n\r\n
\r\n
Constraints:
\r\n\r\n0 <= low <= high <= 10^9
Given an array of integers arr
, return the number of subarrays with an odd sum.
Since the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\n\n\n
Example 2:
\n\n\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i] <= 100
You are given a string s
.
A split is called good if you can split s
into two non-empty strings sleft
and sright
where their concatenation is equal to s
(i.e., sleft + sright = s
) and the number of distinct letters in sleft
and sright
is the same.
Return the number of good splits you can make in s
.
\n
Example 1:
\n\n\nInput: s = "aacaba"\nOutput: 2\nExplanation: There are 5 ways to split "aacaba"
and 2 of them are good. \n("a", "acaba") Left string and right string contains 1 and 3 different letters respectively.\n("aa", "caba") Left string and right string contains 1 and 3 different letters respectively.\n("aac", "aba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aaca", "ba") Left string and right string contains 2 and 2 different letters respectively (good split).\n("aacab", "a") Left string and right string contains 3 and 1 different letters respectively.\n
\n\nExample 2:
\n\n\nInput: s = "abcd"\nOutput: 1\nExplanation: Split the string as follows ("ab", "cd").\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only lowercase English letters.You are given an integer array target
. You have an integer array initial
of the same size as target
with all elements initially zeros.
In one operation you can choose any subarray from initial
and increment each value by one.
Return the minimum number of operations to form a target
array from initial
.
The test cases are generated so that the answer fits in a 32-bit integer.
\n\n\n
Example 1:
\n\n\nInput: target = [1,2,3,2,1]\nOutput: 3\nExplanation: We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.\n\n\n
Example 2:
\n\n\nInput: target = [3,1,1,2]\nOutput: 4\nExplanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]\n\n\n
Example 3:
\n\n\nInput: target = [3,1,5,4,2]\nOutput: 7\nExplanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].\n\n\n
\n
Constraints:
\n\n1 <= target.length <= 105
1 <= target[i] <= 105
Table: Patients
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| patient_id | int |\n| patient_name | varchar |\n| conditions | varchar |\n+--------------+---------+\npatient_id is the primary key (column with unique values) for this table.\n'conditions' contains 0 or more code separated by spaces. \nThis table contains information of the patients in the hospital.\n\n\n
\n\n
Write a solution to find the patient_id, patient_name, and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with DIAB1
prefix.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nPatients table:\n+------------+--------------+--------------+\n| patient_id | patient_name | conditions |\n+------------+--------------+--------------+\n| 1 | Daniel | YFEV COUGH |\n| 2 | Alice | |\n| 3 | Bob | DIAB100 MYOP |\n| 4 | George | ACNE DIAB100 |\n| 5 | Alain | DIAB201 |\n+------------+--------------+--------------+\nOutput: \n+------------+--------------+--------------+\n| patient_id | patient_name | conditions |\n+------------+--------------+--------------+\n| 3 | Bob | DIAB100 MYOP |\n| 4 | George | ACNE DIAB100 | \n+------------+--------------+--------------+\nExplanation: Bob and George both have a condition that starts with DIAB1.\n\n", - "likes": 712, - "dislikes": 603, - "stats": "{\"totalAccepted\": \"301.1K\", \"totalSubmission\": \"759.2K\", \"totalAcceptedRaw\": 301092, \"totalSubmissionRaw\": 759233, \"acRate\": \"39.7%\"}", + "likes": 763, + "dislikes": 613, + "stats": "{\"totalAccepted\": \"344.9K\", \"totalSubmission\": \"880.9K\", \"totalAcceptedRaw\": 344899, \"totalSubmissionRaw\": 880895, \"acRate\": \"39.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -57591,9 +57669,9 @@ "questionFrontendId": "1528", "title": "Shuffle String", "content": "
You are given a string s
and an integer array indices
of the same length. The string s
will be shuffled such that the character at the ith
position moves to indices[i]
in the shuffled string.
Return the shuffled string.
\n\n\n
Example 1:
\n\nInput: s = "codeleet", indices
= [4,5,6,7,0,2,1,3]\nOutput: "leetcode"\nExplanation: As shown, "codeleet" becomes "leetcode" after shuffling.\n
\n\nExample 2:
\n\n\nInput: s = "abc", indices
= [0,1,2]\nOutput: "abc"\nExplanation: After shuffling, each character remains in its position.\n
\n\n\n
Constraints:
\n\ns.length == indices.length == n
1 <= n <= 100
s
consists of only lowercase English letters.0 <= indices[i] < n
indices
are unique.You are given a 0-indexed binary string target
of length n
. You have another binary string s
of length n
that is initially set to all zeros. You want to make s
equal to target
.
In one operation, you can pick an index i
where 0 <= i < n
and flip all bits in the inclusive range [i, n - 1]
. Flip means changing '0'
to '1'
and '1'
to '0'
.
Return the minimum number of operations needed to make s
equal to target
.
\n
Example 1:
\n\n\nInput: target = "10111"\nOutput: 3\nExplanation: Initially, s = "00000".\nChoose index i = 2: "00000" -> "00111"\nChoose index i = 0: "00111" -> "11000"\nChoose index i = 1: "11000" -> "10111"\nWe need at least 3 flip operations to form target.\n\n\n
Example 2:
\n\n\nInput: target = "101"\nOutput: 3\nExplanation: Initially, s = "000".\nChoose index i = 0: "000" -> "111"\nChoose index i = 1: "111" -> "100"\nChoose index i = 2: "100" -> "101"\nWe need at least 3 flip operations to form target.\n\n\n
Example 3:
\n\n\nInput: target = "00000"\nOutput: 0\nExplanation: We do not need any operations since the initial s already equals target.\n\n\n
\n
Constraints:
\n\nn == target.length
1 <= n <= 105
target[i]
is either '0'
or '1'
.You are given the root
of a binary tree and an integer distance
. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance
.
Return the number of good leaf node pairs in the tree.
\n\n\n
Example 1:
\n\nInput: root = [1,2,3,null,4], distance = 3\nOutput: 1\nExplanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\n\n\n
Example 2:
\n\nInput: root = [1,2,3,4,5,6,7], distance = 3\nOutput: 2\nExplanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\n\n\n
Example 3:
\n\n\nInput: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput: 1\nExplanation: The only good pair is [2,5].\n\n\n
\n
Constraints:
\n\ntree
is in the range [1, 210].
1 <= Node.val <= 100
1 <= distance <= 10
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc"
we replace "aa"
by "a2"
and replace "ccc"
by "c3"
. Thus the compressed string becomes "a2bc3"
.
Notice that in this problem, we are not adding '1'
after single characters.
Given a string s
and an integer k
. You need to delete at most k
characters from s
such that the run-length encoded version of s
has minimum length.
Find the minimum length of the run-length encoded version of s
after deleting at most k
characters.
\n
Example 1:
\n\n\nInput: s = "aaabcccd", k = 2\nOutput: 4\nExplanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.\n\n
Example 2:
\n\n\nInput: s = "aabbaa", k = 2\nOutput: 2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.\n\n\n
Example 3:
\n\n\nInput: s = "aaaaaaaaaaa", k = 0\nOutput: 3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
0 <= k <= s.length
s
contains only lowercase English letters.Given an array of integers arr
, and three integers a
, b
and c
. You need to find the number of good triplets.
A triplet (arr[i], arr[j], arr[k])
is good if the following conditions are true:
0 <= i < j < k < arr.length
|arr[i] - arr[j]| <= a
|arr[j] - arr[k]| <= b
|arr[i] - arr[k]| <= c
Where |x|
denotes the absolute value of x
.
Return the number of good triplets.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\r\nOutput: 4\r\nExplanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: arr = [1,1,2,2,3], a = 0, b = 0, c = 1\r\nOutput: 0\r\nExplanation: No triplet satisfies all conditions.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n3 <= arr.length <= 100
0 <= arr[i] <= 1000
0 <= a, b, c <= 1000
Given an integer array arr
of distinct integers and an integer k
.
A game will be played between the first two elements of the array (i.e. arr[0]
and arr[1]
). In each round of the game, we compare arr[0]
with arr[1]
, the larger integer wins and remains at position 0
, and the smaller integer moves to the end of the array. The game ends when an integer wins k
consecutive rounds.
Return the integer which will win the game.
\n\nIt is guaranteed that there will be a winner of the game.
\n\n\n
Example 1:
\n\n\nInput: arr = [2,1,3,5,4,6,7], k = 2\nOutput: 5\nExplanation: Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\n\n\n
Example 2:
\n\n\nInput: arr = [3,2,1], k = 10\nOutput: 3\nExplanation: 3 will win the first 10 rounds consecutively.\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 105
1 <= arr[i] <= 106
arr
contains distinct integers.1 <= k <= 109
Given an n x n
binary grid
, in one step you can choose two adjacent rows of the grid and swap them.
A grid is said to be valid if all the cells above the main diagonal are zeros.
\n\nReturn the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.
\n\nThe main diagonal of a grid is the diagonal that starts at cell (1, 1)
and ends at cell (n, n)
.
\n
Example 1:
\n\nInput: grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput: 3\n\n\n
Example 2:
\n\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput: -1\nExplanation: All rows are similar, swaps have no effect on the grid.\n\n\n
Example 3:
\n\nInput: grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == grid.length
== grid[i].length
1 <= n <= 200
grid[i][j]
is either 0
or 1
You are given two sorted arrays of distinct integers nums1
and nums2
.
A valid path is defined as follows:
\n\nnums1
or nums2
to traverse (from index-0).nums1
and nums2
you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).The score is defined as the sum of unique values in a valid path.
\n\nReturn the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput: 30\nExplanation: Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green [2,4,6,8,10].\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput: 109\nExplanation: Maximum sum is obtained with the path [1,3,5,100].\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput: 40\nExplanation: There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 107
nums1
and nums2
are strictly increasing.Given an array arr
of positive integers sorted in a strictly increasing order, and an integer k
.
Return the kth
positive integer that is missing from this array.
\n
Example 1:
\n\n\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j]
for 1 <= i < j <= arr.length
\n
Follow up:
\n\nCould you solve this problem in less than O(n) complexity?
\n", - "likes": 7070, - "dislikes": 498, - "stats": "{\"totalAccepted\": \"572.4K\", \"totalSubmission\": \"928.9K\", \"totalAcceptedRaw\": 572397, \"totalSubmissionRaw\": 928866, \"acRate\": \"61.6%\"}", + "likes": 7346, + "dislikes": 516, + "stats": "{\"totalAccepted\": \"654.8K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 654828, \"totalSubmissionRaw\": 1051647, \"acRate\": \"62.3%\"}", "similarQuestions": "[{\"title\": \"Append K Integers With Minimal Sum\", \"titleSlug\": \"append-k-integers-with-minimal-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -58028,9 +58109,9 @@ "questionFrontendId": "1540", "title": "Can Convert String in K Moves", "content": "Given two strings s
and t
, your goal is to convert s
into t
in k
moves or less.
During the ith
(1 <= i <= k
) move you can:
j
(1-indexed) from s
, such that 1 <= j <= s.length
and j
has not been chosen in any previous move, and shift the character at that index i
times.Shifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z'
becomes 'a'
). Shifting a character by i
means applying the shift operations i
times.
Remember that any index j
can be picked at most once.
Return true
if it's possible to convert s
into t
in no more than k
moves, otherwise return false
.
\n
Example 1:
\n\n\nInput: s = "input", t = "ouput", k = 9\nOutput: true\nExplanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.\n\n\n
Example 2:
\n\n\nInput: s = "abc", t = "bcd", k = 10\nOutput: false\nExplanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.\n\n\n
Example 3:
\n\n\nInput: s = "aab", t = "bbb", k = 27\nOutput: true\nExplanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 10^5
0 <= k <= 10^9
s
, t
contain only lowercase English letters.Given a parentheses string s
containing only the characters '('
and ')'
. A parentheses string is balanced if:
'('
must have a corresponding two consecutive right parenthesis '))'
.'('
must go before the corresponding two consecutive right parenthesis '))'
.In other words, we treat '('
as an opening parenthesis and '))'
as a closing parenthesis.
"())"
, "())(())))"
and "(())())))"
are balanced, ")()"
, "()))"
and "(()))"
are not balanced.You can insert the characters '('
and ')'
at any position of the string to balance it if needed.
Return the minimum number of insertions needed to make s
balanced.
\n
Example 1:
\n\n\nInput: s = "(()))"\nOutput: 1\nExplanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.\n\n\n
Example 2:
\n\n\nInput: s = "())"\nOutput: 0\nExplanation: The string is already balanced.\n\n\n
Example 3:
\n\n\nInput: s = "))())("\nOutput: 3\nExplanation: Add '(' to match the first '))', Add '))' to match the last '('.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of '('
and ')'
only.You are given a string s
. An awesome substring is a non-empty substring of s
such that we can make any number of swaps in order to make it a palindrome.
Return the length of the maximum length awesome substring of s
.
\n
Example 1:
\n\n\nInput: s = "3242415"\nOutput: 5\nExplanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.\n\n\n
Example 2:
\n\n\nInput: s = "12345678"\nOutput: 1\n\n\n
Example 3:
\n\n\nInput: s = "213123"\nOutput: 6\nExplanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of digits.Given a string s
of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i]
and s[i + 1]
where:
0 <= i <= s.length - 2
s[i]
is a lower-case letter and s[i + 1]
is the same letter but in upper-case or vice-versa.To make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.
\n\nReturn the string after making it good. The answer is guaranteed to be unique under the given constraints.
\n\nNotice that an empty string is also good.
\n\n\n
Example 1:
\n\n\nInput: s = "leEeetcode"\nOutput: "leetcode"\nExplanation: In the first step, either you choose i = 1 or i = 2, both will result "leEeetcode" to be reduced to "leetcode".\n\n\n
Example 2:
\n\n\nInput: s = "abBAcC"\nOutput: ""\nExplanation: We have many possible scenarios, and all lead to the same answer. For example:\n"abBAcC" --> "aAcC" --> "cC" --> ""\n"abBAcC" --> "abBA" --> "aA" --> ""\n\n\n
Example 3:
\n\n\nInput: s = "s"\nOutput: "s"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
contains only lower and upper case English letters.Given two positive integers n
and k
, the binary string Sn
is formed as follows:
S1 = "0"
Si = Si - 1 + "1" + reverse(invert(Si - 1))
for i > 1
Where +
denotes the concatenation operation, reverse(x)
returns the reversed string x
, and invert(x)
inverts all the bits in x
(0
changes to 1
and 1
changes to 0
).
For example, the first four strings in the above sequence are:
\n\nS1 = "0"
S2 = "011"
S3 = "0111001"
S4 = "011100110110001"
Return the kth
bit in Sn
. It is guaranteed that k
is valid for the given n
.
\n
Example 1:
\n\n\nInput: n = 3, k = 1\nOutput: "0"\nExplanation: S3 is "0111001".\nThe 1st bit is "0".\n\n\n
Example 2:
\n\n\nInput: n = 4, k = 11\nOutput: "1"\nExplanation: S4 is "011100110110001".\nThe 11th bit is "1".\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
1 <= k <= 2n - 1
Given an array nums
and an integer target
, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target
.
\n
Example 1:
\n\n\nInput: nums = [1,1,1,1,1], target = 2\nOutput: 2\nExplanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).\n\n\n
Example 2:
\n\n\nInput: nums = [-1,3,5,1,4,2,-9], target = 6\nOutput: 2\nExplanation: There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
0 <= target <= 106
Given a wooden stick of length n
units. The stick is labelled from 0
to n
. For example, a stick of length 6 is labelled as follows:
Given an integer array cuts
where cuts[i]
denotes a position you should perform a cut at.
You should perform the cuts in order, you can change the order of the cuts as you wish.
\n\nThe cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.
\n\nReturn the minimum total cost of the cuts.
\n\n\n
Example 1:
\n\nInput: n = 7, cuts = [1,3,4,5]\nOutput: 16\nExplanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n\n\n\nThe first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).
Example 2:
\n\n\nInput: n = 9, cuts = [5,6,1,4,2]\nOutput: 22\nExplanation: If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n\n\n
\n
Constraints:
\n\n2 <= n <= 106
1 <= cuts.length <= min(n - 1, 100)
1 <= cuts[i] <= n - 1
cuts
array are distinct.arr
, return true
if there are three consecutive odd numbers in the array. Otherwise, return false
.\n\n
Example 1:
\n\n\nInput: arr = [2,6,4,1]\nOutput: false\nExplanation: There are no three consecutive odds.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,34,3,4,5,7,23,12]\nOutput: true\nExplanation: [5,7,23] are three consecutive odds.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 1000
1 <= arr[i] <= 1000
You have an array arr
of length n
where arr[i] = (2 * i) + 1
for all valid values of i
(i.e., 0 <= i < n
).
In one operation, you can select two indices x
and y
where 0 <= x, y < n
and subtract 1
from arr[x]
and add 1
to arr[y]
(i.e., perform arr[x] -=1
and arr[y] += 1
). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.
Given an integer n
, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 2\nExplanation: arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\n\n\n
Example 2:
\n\n\nInput: n = 6\nOutput: 9\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n
empty baskets, the ith
basket is at position[i]
, Morty has m
balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.
Rick stated that magnetic force between two different balls at positions x
and y
is |x - y|
.
Given the integer array position
and the integer m
. Return the required force.
\n
Example 1:
\n\nInput: position = [1,2,3,4,7], m = 3\nOutput: 3\nExplanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n\n\n
Example 2:
\n\n\nInput: position = [5,4,3,2,1,1000000000], m = 2\nOutput: 999999999\nExplanation: We can use baskets 1 and 1000000000.\n\n\n
\n
Constraints:
\n\nn == position.length
2 <= n <= 105
1 <= position[i] <= 109
position
are distinct.2 <= m <= position.length
There are n
oranges in the kitchen and you decided to eat some of these oranges every day as follows:
n
is divisible by 2
then you can eat n / 2
oranges.n
is divisible by 3
then you can eat 2 * (n / 3)
oranges.You can only choose one of the actions per day.
\n\nGiven the integer n
, return the minimum number of days to eat n
oranges.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: 4\nExplanation: You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.\n\n\n
Example 2:
\n\n\nInput: n = 6\nOutput: 3\nExplanation: You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 109
Given an integer n
, add a dot (".") as the thousands separator and return it in string format.
\n
Example 1:
\n\n\nInput: n = 987\nOutput: "987"\n\n\n
Example 2:
\n\n\nInput: n = 1234\nOutput: "1.234"\n\n\n
\n
Constraints:
\n\n0 <= n <= 231 - 1
Given a directed acyclic graph, with n
vertices numbered from 0
to n-1
, and an array edges
where edges[i] = [fromi, toi]
represents a directed edge from node fromi
to node toi
.
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
\n\nNotice that you can return the vertices in any order.
\n\n\n
Example 1:
\n\n\nInput: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\nOutput: [0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].\n\n
Example 2:
\n\n\nInput: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\nOutput: [0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.\n\n\n
\n
Constraints:
\n\n2 <= n <= 10^5
1 <= edges.length <= min(10^5, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi < n
(fromi, toi)
are distinct.You are given an integer array nums
. You have an integer array arr
of the same length with all values set to 0
initially. You also have the following modify
function:
You want to use the modify function to convert arr
to nums
using the minimum number of calls.
Return the minimum number of function calls to make nums
from arr
.
The test cases are generated so that the answer fits in a 32-bit signed integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,5]\nOutput: 5\nExplanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).\nTotal of operations: 1 + 2 + 2 = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2]\nOutput: 3\nExplanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] -> [2, 2] (1 operation).\nTotal of operations: 2 + 1 = 3.\n\n\n
Example 3:
\n\n\nInput: nums = [4,2,5]\nOutput: 6\nExplanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
Given a 2D array of characters grid
of size m x n
, you need to find if there exists any cycle consisting of the same value in grid
.
A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.
\n\nAlso, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1)
is invalid because from (1, 2)
we visited (1, 1)
which was the last visited cell.
Return true
if any cycle of the same value exists in grid
, otherwise, return false
.
\n
Example 1:
\n\n\nInput: grid = [["a","a","a","a"],["a","b","b","a"],["a","b","b","a"],["a","a","a","a"]]\nOutput: true\nExplanation: There are two valid cycles shown in different colors in the image below:\n\n\n\n
Example 2:
\n\n\nInput: grid = [["c","c","c","a"],["c","d","c","c"],["c","c","e","c"],["f","c","c","c"]]\nOutput: true\nExplanation: There is only one valid cycle highlighted in the image below:\n\n\n\n
Example 3:
\n\n\nInput: grid = [["a","b","b"],["b","z","b"],["b","b","a"]]\nOutput: false\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 500
grid
consists only of lowercase English letters.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 sector rounds[0]
and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
\n\nNotice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
\n\n\n
Example 1:
\n\nInput: n = 4, rounds = [1,3,1,2]\nOutput: [1,2]\nExplanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\n\n
Example 2:
\n\n\nInput: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput: [2]\n\n\n
Example 3:
\n\n\nInput: n = 7, rounds = [1,3,5,7]\nOutput: [1,2,3,4,5,6,7]\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
1 <= m <= 100
rounds.length == m + 1
1 <= rounds[i] <= n
rounds[i] != rounds[i + 1]
for 0 <= i < m
There are 3n
piles of coins of varying size, you and your friends will take piles of coins as follows:
3
piles of coins (not necessarily consecutive).Given an array of integers piles
where piles[i]
is the number of coins in the ith
pile.
Return the maximum number of coins that you can have.
\n\n\n
Example 1:
\n\n\nInput: piles = [2,4,1,2,7,8]\nOutput: 9\nExplanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.\n\n\n
Example 2:
\n\n\nInput: piles = [2,4,5]\nOutput: 4\n\n\n
Example 3:
\n\n\nInput: piles = [9,8,7,6,5,1,2,3,4]\nOutput: 18\n\n\n
\n
Constraints:
\n\n3 <= piles.length <= 105
piles.length % 3 == 0
1 <= piles[i] <= 104
Given an array arr
that represents a permutation of numbers from 1
to n
.
You have a binary string of size n
that initially has all its bits set to zero. At each step i
(assuming both the binary string and arr
are 1-indexed) from 1
to n
, the bit at position arr[i]
is set to 1
.
You are also given an integer m
. Find the latest step at which there exists a group of ones of length m
. A group of ones is a contiguous substring of 1
's such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m
. If no such group exists, return -1
.
\n
Example 1:
\n\n\nInput: arr = [3,5,1,2,4], m = 1\nOutput: 4\nExplanation: \nStep 1: "00100", groups: ["1"]\nStep 2: "00101", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "11101", groups: ["111", "1"]\nStep 5: "11111", groups: ["11111"]\nThe latest step at which there exists a group of size 1 is step 4.\n\n\n
Example 2:
\n\n\nInput: arr = [3,1,5,4,2], m = 2\nOutput: -1\nExplanation: \nStep 1: "00100", groups: ["1"]\nStep 2: "10100", groups: ["1", "1"]\nStep 3: "10101", groups: ["1", "1", "1"]\nStep 4: "10111", groups: ["1", "111"]\nStep 5: "11111", groups: ["11111"]\nNo group of size 2 exists during any step.\n\n\n
\n
Constraints:
\n\nn == arr.length
1 <= m <= n <= 105
1 <= arr[i] <= n
arr
are distinct.There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue
.
In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
\n\nThe game ends when there is only one stone remaining. Alice's is initially zero.
\n\nReturn the maximum score that Alice can obtain.
\n\n\n
Example 1:
\n\n\nInput: stoneValue = [6,2,3,4,5,5]\nOutput: 18\nExplanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n\n\n
Example 2:
\n\n\nInput: stoneValue = [7,7,7,7,7,7,7]\nOutput: 28\n\n\n
Example 3:
\n\n\nInput: stoneValue = [4]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= stoneValue.length <= 500
1 <= stoneValue[i] <= 106
Given an array of positive integers arr
, find a pattern of length m
that is repeated k
or more times.
A pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.
\n\nReturn true
if there exists a pattern of length m
that is repeated k
or more times, otherwise return false
.
\n
Example 1:
\n\n\nInput: arr = [1,2,4,4,4,4], m = 1, k = 3\nOutput: true\nExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.\n\n\n
Example 2:
\n\n\nInput: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\nOutput: true\nExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,1,2,1,3], m = 2, k = 3\nOutput: false\nExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.\n\n\n
\n
Constraints:
\n\n2 <= arr.length <= 100
1 <= arr[i] <= 100
1 <= m <= 100
2 <= k <= 100
Given an array of integers nums
, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
\n\nReturn the maximum length of a subarray with positive product.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,-2,-3,4]\nOutput: 4\nExplanation: The array nums already has a positive product of 24.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,-2,-3,-4]\nOutput: 3\nExplanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.\n\n
Example 3:
\n\n\nInput: nums = [-1,-2,-3,0,1]\nOutput: 2\nExplanation: The longest subarray with positive product is [-1,-2] or [-2,-3].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
You are given an m x n
binary grid grid
where 1
represents land and 0
represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1
's.
The grid is said to be connected if we have exactly one island, otherwise is said disconnected.
\n\nIn one day, we are allowed to change any single land cell (1)
into a water cell (0)
.
Return the minimum number of days to disconnect the grid.
\n\n\n
Example 1:
\n\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n\nOutput: 2\nExplanation: We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\n\n\n
Example 2:
\n\nInput: grid = [[1,1]]\nOutput: 2\nExplanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j]
is either 0
or 1
.Given an array nums
that represents a permutation of integers from 1
to n
. We are going to construct a binary search tree (BST) by inserting the elements of nums
in order into an initially empty BST. Find the number of different ways to reorder nums
so that the constructed BST is identical to that formed from the original array nums
.
nums = [2,1,3]
, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1]
also yields the same BST but [3,2,1]
yields a different BST.Return the number of ways to reorder nums
such that the BST formed is identical to the original BST formed from nums
.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [2,1,3]\nOutput: 1\nExplanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.\n\n\n
Example 2:
\n\nInput: nums = [3,4,5,1,2]\nOutput: 5\nExplanation: The following 5 arrays will yield the same BST: \n[3,1,2,4,5]\n[3,1,4,2,5]\n[3,1,4,5,2]\n[3,4,1,2,5]\n[3,4,1,5,2]\n\n\n
Example 3:
\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: There are no other orderings of nums that will yield the same BST.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= nums.length
nums
are distinct.Given a square matrix mat
, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
\n\n\n
Example 1:
\n\nInput: mat = [[1,2,3],\n [4,5,6],\n [7,8,9]]\nOutput: 25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.\n\n\n
Example 2:
\n\n\nInput: mat = [[1,1,1,1],\n [1,1,1,1],\n [1,1,1,1],\n [1,1,1,1]]\nOutput: 8\n\n\n
Example 3:
\n\n\nInput: mat = [[5]]\nOutput: 5\n\n\n
\n
Constraints:
\n\nn == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
Given a binary string s
, you can split s
into 3 non-empty strings s1
, s2
, and s3
where s1 + s2 + s3 = s
.
Return the number of ways s
can be split such that the number of ones is the same in s1
, s2
, and s3
. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "10101"\nOutput: 4\nExplanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n"1|010|1"\n"1|01|01"\n"10|10|1"\n"10|1|01"\n\n\n
Example 2:
\n\n\nInput: s = "1001"\nOutput: 0\n\n\n
Example 3:
\n\n\nInput: s = "0000"\nOutput: 3\nExplanation: There are three ways to split s in 3 parts.\n"0|0|00"\n"0|00|0"\n"00|0|0"\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 105
s[i]
is either '0'
or '1'
.Given an integer array arr
, remove a subarray (can be empty) from arr
such that the remaining elements in arr
are non-decreasing.
Return the length of the shortest subarray to remove.
\n\nA subarray is a contiguous subsequence of the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,2,3,10,4,2,3,5]\nOutput: 3\nExplanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].\n\n\n
Example 2:
\n\n\nInput: arr = [5,4,3,2,1]\nOutput: 4\nExplanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].\n\n\n
Example 3:
\n\n\nInput: arr = [1,2,3]\nOutput: 0\nExplanation: The array is already non-decreasing. We do not need to remove any elements.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
0 <= arr[i] <= 109
You are given an array of distinct positive integers locations where locations[i]
represents the position of city i
. You are also given integers start
, finish
and fuel
representing the starting city, ending city, and the initial amount of fuel you have, respectively.
At each step, if you are at city i
, you can pick any city j
such that j != i
and 0 <= j < locations.length
and move to city j
. Moving from city i
to city j
reduces the amount of fuel you have by |locations[i] - locations[j]|
. Please notice that |x|
denotes the absolute value of x
.
Notice that fuel
cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start
and finish
).
Return the count of all possible routes from start
to finish
. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\nOutput: 4\nExplanation: The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3\n\n\n
Example 2:
\n\n\nInput: locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput: 5\nExplanation: The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\n\n\n
Example 3:
\n\n\nInput: locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput: 0\nExplanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n\n\n
\n
Constraints:
\n\n2 <= locations.length <= 100
1 <= locations[i] <= 109
locations
are distinct.0 <= start, finish < locations.length
1 <= fuel <= 200
Given a string s
containing only lowercase English letters and the '?'
character, convert all the '?'
characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?'
characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'
.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
\n\n\n
Example 1:
\n\n\nInput: s = "?zs"\nOutput: "azs"\nExplanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".\n\n\n
Example 2:
\n\n\nInput: s = "ubv?w"\nOutput: "ubvaw"\nExplanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consist of lowercase English letters and '?'
.Given two arrays of integers nums1
and nums2
, return the number of triplets formed (type 1 and type 2) under the following rules:
nums1[i]2 == nums2[j] * nums2[k]
where 0 <= i < nums1.length
and 0 <= j < k < nums2.length
.nums2[i]2 == nums1[j] * nums1[k]
where 0 <= i < nums2.length
and 0 <= j < k < nums1.length
.\n
Example 1:
\n\n\nInput: nums1 = [7,4], nums2 = [5,2,8,9]\nOutput: 1\nExplanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). \n\n\n
Example 2:
\n\n\nInput: nums1 = [1,1], nums2 = [1,1,1]\nOutput: 9\nExplanation: All Triplets are valid, because 12 = 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\n\n\n
Example 3:
\n\n\nInput: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput: 2\nExplanation: There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 105
Alice has n
balloons arranged on a rope. You are given a 0-indexed string colors
where colors[i]
is the color of the ith
balloon.
Alice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime
where neededTime[i]
is the time (in seconds) that Bob needs to remove the ith
balloon from the rope.
Return the minimum time Bob needs to make the rope colorful.
\n\n\n
Example 1:
\n\nInput: colors = "abaac", neededTime = [1,2,3,4,5]\nOutput: 3\nExplanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.\n\n
Example 2:
\n\nInput: colors = "abc", neededTime = [1,2,3]\nOutput: 0\nExplanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.\n\n\n
Example 3:
\n\nInput: colors = "aabaa", neededTime = [1,2,3,4,1]\nOutput: 2\nExplanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n\n\n
\n
Constraints:
\n\nn == colors.length == neededTime.length
1 <= n <= 105
1 <= neededTime[i] <= 104
colors
contains only lowercase English letters.Alice and Bob have an undirected graph of n
nodes and three types of edges:
Given an array edges
where edges[i] = [typei, ui, vi]
represents a bidirectional edge of type typei
between nodes ui
and vi
, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.
Return the maximum number of edges you can remove, or return -1
if Alice and Bob cannot fully traverse the graph.
\n
Example 1:
\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\nOutput: 2\nExplanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n\n\n
Example 2:
\n\n\nInput: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\nOutput: 0\nExplanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n\n\n
Example 3:
\n\n\nInput: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\nOutput: -1\nExplanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n\n
\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= edges.length <= min(105, 3 * n * (n - 1) / 2)
edges[i].length == 3
1 <= typei <= 3
1 <= ui < vi <= n
(typei, ui, vi)
are distinct.Table: Visits
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| visit_id | int |\n| customer_id | int |\n+-------------+---------+\nvisit_id is the column with unique values for this table.\nThis table contains information about the customers who visited the mall.\n\n\n
\n\n
Table: Transactions
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| transaction_id | int |\n| visit_id | int |\n| amount | int |\n+----------------+---------+\ntransaction_id is column with unique values for this table.\nThis table contains information about the transactions made during the visit_id.\n\n\n
\n\n
Write a solution to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.
\n\nReturn the result table sorted in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nVisits\n+----------+-------------+\n| visit_id | customer_id |\n+----------+-------------+\n| 1 | 23 |\n| 2 | 9 |\n| 4 | 30 |\n| 5 | 54 |\n| 6 | 96 |\n| 7 | 54 |\n| 8 | 54 |\n+----------+-------------+\nTransactions\n+----------------+----------+--------+\n| transaction_id | visit_id | amount |\n+----------------+----------+--------+\n| 2 | 5 | 310 |\n| 3 | 5 | 300 |\n| 9 | 5 | 200 |\n| 12 | 1 | 910 |\n| 13 | 2 | 970 |\n+----------------+----------+--------+\nOutput: \n+-------------+----------------+\n| customer_id | count_no_trans |\n+-------------+----------------+\n| 54 | 2 |\n| 30 | 1 |\n| 96 | 1 |\n+-------------+----------------+\nExplanation: \nCustomer with id = 23 visited the mall once and made one transaction during the visit with id = 12.\nCustomer with id = 9 visited the mall once and made one transaction during the visit with id = 13.\nCustomer with id = 30 visited the mall once and did not make any transactions.\nCustomer with id = 54 visited the mall three times. During 2 visits they did not make any transactions, and during one visit they made 3 transactions.\nCustomer with id = 96 visited the mall once and did not make any transactions.\nAs we can see, users with IDs 30 and 96 visited the mall one time without making any transactions. Also, user 54 visited the mall twice and did not make any transactions.\n\n", - "likes": 2572, - "dislikes": 358, - "stats": "{\"totalAccepted\": \"719.4K\", \"totalSubmission\": \"1.1M\", \"totalAcceptedRaw\": 719440, \"totalSubmissionRaw\": 1064050, \"acRate\": \"67.6%\"}", + "likes": 2852, + "dislikes": 393, + "stats": "{\"totalAccepted\": \"860.8K\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 860832, \"totalSubmissionRaw\": 1276897, \"acRate\": \"67.4%\"}", "similarQuestions": "[{\"title\": \"Sellers With No Sales\", \"titleSlug\": \"sellers-with-no-sales\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -59603,9 +59684,9 @@ "questionFrontendId": "1582", "title": "Special Positions in a Binary Matrix", "content": "
Given an m x n
binary matrix mat
, return the number of special positions in mat
.
A position (i, j)
is called special if mat[i][j] == 1
and all other elements in row i
and column j
are 0
(rows and columns are 0-indexed).
\n
Example 1:
\n\nInput: mat = [[1,0,0],[0,0,1],[1,0,0]]\nOutput: 1\nExplanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.\n\n\n
Example 2:
\n\nInput: mat = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\nExplanation: (0, 0), (1, 1) and (2, 2) are special positions.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j]
is either 0
or 1
.You are given a list of preferences
for n
friends, where n
is always even.
For each person i
, preferences[i]
contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0
to n-1
.
All the friends are divided into pairs. The pairings are given in a list pairs
, where pairs[i] = [xi, yi]
denotes xi
is paired with yi
and yi
is paired with xi
.
However, this pairing may cause some of the friends to be unhappy. A friend x
is unhappy if x
is paired with y
and there exists a friend u
who is paired with v
but:
x
prefers u
over y
, andu
prefers x
over v
.Return the number of unhappy friends.
\n\n\n
Example 1:
\n\n\nInput: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput: 2\nExplanation:\nFriend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.\n\n\n
Example 2:
\n\n\nInput: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput: 0\nExplanation: Both friends 0 and 1 are happy.\n\n\n
Example 3:
\n\n\nInput: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput: 4\n\n\n
\n
Constraints:
\n\n2 <= n <= 500
n
is even.preferences.length == n
preferences[i].length == n - 1
0 <= preferences[i][j] <= n - 1
preferences[i]
does not contain i
.preferences[i]
are unique.pairs.length == n/2
pairs[i].length == 2
xi != yi
0 <= xi, yi <= n - 1
You are given an array points
representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]
.
The cost of connecting two points [xi, yi]
and [xj, yj]
is the manhattan distance between them: |xi - xj| + |yi - yj|
, where |val|
denotes the absolute value of val
.
Return the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.
\n\n\n
Example 1:
\n\nInput: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput: 20\nExplanation: \n\n\n\nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\n
Example 2:
\n\n\nInput: points = [[3,12],[-2,5],[-4,1]]\nOutput: 18\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 1000
-106 <= xi, yi <= 106
(xi, yi)
are distinct.Given two strings s
and t
, transform string s
into string t
using the following operation any number of times:
s
and sort it in place so the characters are in ascending order.\n\n\t"14234"
results in "12344"
.Return true
if it is possible to transform s
into t
. Otherwise, return false
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "84532", t = "34852"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n"84532" (from index 2 to 3) -> "84352"\n"84352" (from index 0 to 2) -> "34852"\n\n\n
Example 2:
\n\n\nInput: s = "34521", t = "23415"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n"34521" -> "23451"\n"23451" -> "23415"\n\n\n
Example 3:
\n\n\nInput: s = "12345", t = "12435"\nOutput: false\n\n\n
\n
Constraints:
\n\ns.length == t.length
1 <= s.length <= 105
s
and t
consist of only digits.Table: Users
\n+--------------+---------+\n| Column Name | Type |\n+--------------+---------+\n| account | int |\n| name | varchar |\n+--------------+---------+\naccount is the primary key (column with unique values) for this table.\nEach row of this table contains the account number of each user in the bank.\nThere will be no two users having the same name in the table.\n\n\n
\n\n
Table: Transactions
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| trans_id | int |\n| account | int |\n| amount | int |\n| transacted_on | date |\n+---------------+---------+\ntrans_id is the primary key (column with unique values) for this table.\nEach row of this table contains all changes made to all accounts.\namount is positive if the user received money and negative if they transferred money.\nAll accounts start with a balance of 0.\n\n\n
\n\n
Write a solution to report the name and balance of users with a balance higher than 10000
. The balance of an account is equal to the sum of the amounts of all transactions involving that account.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+------------+--------------+\n| account | name |\n+------------+--------------+\n| 900001 | Alice |\n| 900002 | Bob |\n| 900003 | Charlie |\n+------------+--------------+\nTransactions table:\n+------------+------------+------------+---------------+\n| trans_id | account | amount | transacted_on |\n+------------+------------+------------+---------------+\n| 1 | 900001 | 7000 | 2020-08-01 |\n| 2 | 900001 | 7000 | 2020-09-01 |\n| 3 | 900001 | -3000 | 2020-09-02 |\n| 4 | 900002 | 1000 | 2020-09-12 |\n| 5 | 900003 | 6000 | 2020-08-07 |\n| 6 | 900003 | 6000 | 2020-09-07 |\n| 7 | 900003 | -4000 | 2020-09-11 |\n+------------+------------+------------+---------------+\nOutput: \n+------------+------------+\n| name | balance |\n+------------+------------+\n| Alice | 11000 |\n+------------+------------+\nExplanation: \nAlice's balance is (7000 + 7000 - 3000) = 11000.\nBob's balance is 1000.\nCharlie's balance is (6000 + 6000 - 4000) = 8000.\n\n", - "likes": 503, + "likes": 519, "dislikes": 6, - "stats": "{\"totalAccepted\": \"122.8K\", \"totalSubmission\": \"147.1K\", \"totalAcceptedRaw\": 122753, \"totalSubmissionRaw\": 147129, \"acRate\": \"83.4%\"}", + "stats": "{\"totalAccepted\": \"134.1K\", \"totalSubmission\": \"160.8K\", \"totalAcceptedRaw\": 134051, \"totalSubmissionRaw\": 160842, \"acRate\": \"83.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -59833,9 +59914,9 @@ "questionFrontendId": "1588", "title": "Sum of All Odd Length Subarrays", "content": "
Given an array of positive integers arr
, return the sum of all possible odd-length subarrays of arr
.
A subarray is a contiguous subsequence of the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\n\n
Example 2:
\n\n\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\n\n
Example 3:
\n\n\nInput: arr = [10,11,12]\nOutput: 66\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 100
1 <= arr[i] <= 1000
\n
Follow up:
\n\nCould you solve this problem in O(n) time complexity?
\n", - "likes": 3759, - "dislikes": 315, - "stats": "{\"totalAccepted\": \"218.3K\", \"totalSubmission\": \"261.8K\", \"totalAcceptedRaw\": 218256, \"totalSubmissionRaw\": 261798, \"acRate\": \"83.4%\"}", + "likes": 3801, + "dislikes": 320, + "stats": "{\"totalAccepted\": \"228.2K\", \"totalSubmission\": \"273.2K\", \"totalAcceptedRaw\": 228194, \"totalSubmissionRaw\": 273243, \"acRate\": \"83.5%\"}", "similarQuestions": "[{\"title\": \"Sum of Squares of Special Elements \", \"titleSlug\": \"sum-of-squares-of-special-elements\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -59872,9 +59953,9 @@ "questionFrontendId": "1589", "title": "Maximum Sum Obtained of Any Permutation", "content": "We have an array of integers, nums
, and an array of requests
where requests[i] = [starti, endi]
. The ith
request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]
. Both starti
and endi
are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums
.
Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput: 19\nExplanation: One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput: 11\nExplanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput: 47\nExplanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
0 <= nums[i] <= 105
1 <= requests.length <= 105
requests[i].length == 2
0 <= starti <= endi < n
Given an array of positive integers nums
, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p
. It is not allowed to remove the whole array.
Return the length of the smallest subarray that you need to remove, or -1
if it's impossible.
A subarray is defined as a contiguous block of elements in the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,4,2], p = 6\nOutput: 1\nExplanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.\n\n\n
Example 2:
\n\n\nInput: nums = [6,3,5,2], p = 9\nOutput: 2\nExplanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3], p = 3\nOutput: 0\nExplanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= p <= 109
There is a strange printer with the following two special requirements:
\n\nYou are given a m x n
matrix targetGrid
, where targetGrid[row][col]
is the color in the position (row, col)
of the grid.
Return true
if it is possible to print the matrix targetGrid
, otherwise, return false
.
\n
Example 1:
\n\nInput: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\nOutput: true\n\n\n
Example 2:
\n\nInput: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\nOutput: true\n\n\n
Example 3:
\n\n\nInput: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\nOutput: false\nExplanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n\n\n
\n
Constraints:
\n\nm == targetGrid.length
n == targetGrid[i].length
1 <= m, n <= 60
1 <= targetGrid[row][col] <= 60
You are given a string text
of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text
contains at least one word.
Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text
.
Return the string after rearranging the spaces.
\n\n\n
Example 1:
\n\n\nInput: text = " this is a sentence "\nOutput: "this is a sentence"\nExplanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\n\n\n
Example 2:
\n\n\nInput: text = " practice makes perfect"\nOutput: "practice makes perfect "\nExplanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 100
text
consists of lowercase English letters and ' '
.text
contains at least one word.Given a string s
, return the maximum number of unique substrings that the given string can be split into.
You can split string s
into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "ababccc"\nOutput: 5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\n\n\n
Example 2:
\n\n\nInput: s = "aba"\nOutput: 2\nExplanation: One way to split maximally is ['a', 'ba'].\n\n\n
Example 3:
\n\n\nInput: s = "aa"\nOutput: 1\nExplanation: It is impossible to split the string any further.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 16
s
contains only lower case English letters.
You are given a m x n
matrix grid
. Initially, you are located at the top-left corner (0, 0)
, and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0)
and ending in the bottom-right corner (m - 1, n - 1)
, find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7
. If the maximum product is negative, return -1
.
Notice that the modulo is performed after getting the maximum product.
\n\n\n
Example 1:
\n\nInput: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput: -1\nExplanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\n\n\n
Example 2:
\n\nInput: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput: 8\nExplanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\n\n\n
Example 3:
\n\nInput: grid = [[1,3],[0,-4]]\nOutput: 0\nExplanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 15
-4 <= grid[i][j] <= 4
You are given two groups of points where the first group has size1
points, the second group has size2
points, and size1 >= size2
.
The cost
of the connection between any two points are given in an size1 x size2
matrix where cost[i][j]
is the cost of connecting point i
of the first group and point j
of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.
Return the minimum cost it takes to connect the two groups.
\n\n\n
Example 1:
\n\nInput: cost = [[15, 96], [36, 2]]\nOutput: 17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.\n\n\n
Example 2:
\n\nInput: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\nOutput: 4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\n\n\n
Example 3:
\n\n\nInput: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\nOutput: 10\n\n\n
\n
Constraints:
\n\nsize1 == cost.length
size2 == cost[i].length
1 <= size1, size2 <= 12
size1 >= size2
0 <= cost[i][j] <= 100
The Leetcode file system keeps a log each time some user performs a change folder operation.
\n\nThe operations are described below:
\n\n"../"
: Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder)."./"
: Remain in the same folder."x/"
: Move to the child folder named x
(This folder is guaranteed to always exist).You are given a list of strings logs
where logs[i]
is the operation performed by the user at the ith
step.
The file system starts in the main folder, then the operations in logs
are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
\n\n\n
Example 1:
\n\n\nInput: logs = ["d1/","d2/","../","d21/","./"]\nOutput: 2\nExplanation: Use this change folder operation "../" 2 times and go back to the main folder.\n\n\n
Example 2:
\n\n\nInput: logs = ["d1/","d2/","./","d3/","../","d31/"]\nOutput: 3\n\n\n
Example 3:
\n\n\nInput: logs = ["d1/","../","../","../"]\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= logs.length <= 103
2 <= logs[i].length <= 10
logs[i]
contains lowercase English letters, digits, '.'
, and '/'
.logs[i]
follows the format described in the statement.You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost
dollars.
You are given an array customers
of length n
where customers[i]
is the number of new customers arriving just before the ith
rotation (0-indexed). This means you must rotate the wheel i
times before the customers[i]
customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost
dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.
You can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.
\n\nReturn the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1
.
\n
Example 1:
\n\nInput: customers = [8,3], boardingCost = 5, runningCost = 6\nOutput: 3\nExplanation: The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.\n\n\n
Example 2:
\n\n\nInput: customers = [10,9,6], boardingCost = 6, runningCost = 4\nOutput: 7\nExplanation:\n1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.\n\n\n
Example 3:
\n\n\nInput: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\nOutput: -1\nExplanation:\n1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.\n\n\n
\n
Constraints:
\n\nn == customers.length
1 <= n <= 105
0 <= customers[i] <= 50
1 <= boardingCost, runningCost <= 100
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
\n\nThe kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder)
, which given a person x
and the inheritance order so far, returns who should be the next person after x
in the order of inheritance.
\nSuccessor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder\n\n\n
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
\n\ncurOrder
will be ["king"]
.Successor(king, curOrder)
will return Alice, so we append to curOrder
to get ["king", "Alice"]
.Successor(Alice, curOrder)
will return Jack, so we append to curOrder
to get ["king", "Alice", "Jack"]
.Successor(Jack, curOrder)
will return Bob, so we append to curOrder
to get ["king", "Alice", "Jack", "Bob"]
.Successor(Bob, curOrder)
will return null
. Thus the order of inheritance will be ["king", "Alice", "Jack", "Bob"]
.Using the above function, we can always obtain a unique order of inheritance.
\n\nImplement the ThroneInheritance
class:
ThroneInheritance(string kingName)
Initializes an object of the ThroneInheritance
class. The name of the king is given as part of the constructor.void birth(string parentName, string childName)
Indicates that parentName
gave birth to childName
.void death(string name)
Indicates the death of name
. The death of the person doesn't affect the Successor
function nor the current inheritance order. You can treat it as just marking the person as dead.string[] getInheritanceOrder()
Returns a list representing the current order of inheritance excluding dead people.\n
Example 1:
\n\n\nInput\n["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]\n[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]\nOutput\n[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]\n\nExplanation\nThroneInheritance t= new ThroneInheritance("king"); // order: king\nt.birth("king", "andy"); // order: king > andy\nt.birth("king", "bob"); // order: king > andy > bob\nt.birth("king", "catherine"); // order: king > andy > bob > catherine\nt.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine\nt.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine\nt.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine\nt.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]\nt.death("bob"); // order: king > andy > matthew >\n\nbob> alex > asha > catherine\nt.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]\n
\n
Constraints:
\n\n1 <= kingName.length, parentName.length, childName.length, name.length <= 15
kingName
, parentName
, childName
, and name
consist of lowercase English letters only.childName
and kingName
are distinct.name
arguments of death
will be passed to either the constructor or as childName
to birth
first.birth(parentName, childName)
, it is guaranteed that parentName
is alive.105
calls will be made to birth
and death
.10
calls will be made to getInheritanceOrder
.We have n
buildings numbered from 0
to n - 1
. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.
You are given an array requests
where requests[i] = [fromi, toi]
represents an employee's request to transfer from building fromi
to building toi
.
All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3
and two employees are leaving building 0
, one is leaving building 1
, and one is leaving building 2
, there should be two employees moving to building 0
, one employee moving to building 1
, and one employee moving to building 2
.
Return the maximum number of achievable requests.
\n\n\n
Example 1:
\n\nInput: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\nOutput: 5\nExplantion: Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\n\n\n
Example 2:
\n\nInput: n = 3, requests = [[0,0],[1,2],[2,1]]\nOutput: 3\nExplantion: Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests.\n\n
Example 3:
\n\n\nInput: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
1 <= requests.length <= 16
requests[i].length == 2
0 <= fromi, toi < n
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
\n\nImplement the ParkingSystem
class:
ParkingSystem(int big, int medium, int small)
Initializes object of the ParkingSystem
class. The number of slots for each parking space are given as part of the constructor.bool addCar(int carType)
Checks whether there is a parking space of carType
for the car that wants to get into the parking lot. carType
can be of three kinds: big, medium, or small, which are represented by 1
, 2
, and 3
respectively. A car can only park in a parking space of its carType
. If there is no space available, return false
, else park the car in that size space and return true
.\n
Example 1:
\n\n\nInput\n["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]\n[[1, 1, 0], [1], [2], [3], [1]]\nOutput\n[null, true, true, false, false]\n\nExplanation\nParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\nparkingSystem.addCar(1); // return true because there is 1 available slot for a big car\nparkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\nparkingSystem.addCar(3); // return false because there is no available slot for a small car\nparkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.\n\n\n
\n
Constraints:
\n\n0 <= big, medium, small <= 1000
carType
is 1
, 2
, or 3
1000
calls will be made to addCar
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.
\n\nYou are given a list of strings keyName
and keyTime
where [keyName[i], keyTime[i]]
corresponds to a person's name and the time when their key-card was used in a single day.
Access times are given in the 24-hour time format "HH:MM", such as "23:51"
and "09:49"
.
Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.
\n\nNotice that "10:00"
- "11:00"
is considered to be within a one-hour period, while "22:51"
- "23:52"
is not considered to be within a one-hour period.
\n
Example 1:
\n\n\nInput: keyName = ["daniel","daniel","daniel","luis","luis","luis","luis"], keyTime = ["10:00","10:40","11:00","09:00","11:00","13:00","15:00"]\nOutput: ["daniel"]\nExplanation: "daniel" used the keycard 3 times in a one-hour period ("10:00","10:40", "11:00").\n\n\n
Example 2:
\n\n\nInput: keyName = ["alice","alice","alice","bob","bob","bob","bob"], keyTime = ["12:01","12:00","18:00","21:00","21:20","21:30","23:00"]\nOutput: ["bob"]\nExplanation: "bob" used the keycard 3 times in a one-hour period ("21:00","21:20", "21:30").\n\n\n
\n
Constraints:
\n\n1 <= keyName.length, keyTime.length <= 105
keyName.length == keyTime.length
keyTime[i]
is in the format "HH:MM".[keyName[i], keyTime[i]]
is unique.1 <= keyName[i].length <= 10
keyName[i] contains only lowercase English letters.
You are given two arrays rowSum
and colSum
of non-negative integers where rowSum[i]
is the sum of the elements in the ith
row and colSum[j]
is the sum of the elements of the jth
column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length
that satisfies the rowSum
and colSum
requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
\n\n\n
Example 1:
\n\n\nInput: rowSum = [3,8], colSum = [4,7]\nOutput: [[3,0],\n [1,7]]\nExplanation: \n0th row: 3 + 0 = 3 == rowSum[0]\n1st row: 1 + 7 = 8 == rowSum[1]\n0th column: 3 + 1 = 4 == colSum[0]\n1st column: 0 + 7 = 7 == colSum[1]\nThe row and column sums match, and all matrix elements are non-negative.\nAnother possible matrix is: [[1,2],\n [3,5]]\n\n\n
Example 2:
\n\n\nInput: rowSum = [5,7,10], colSum = [8,6,8]\nOutput: [[0,5,0],\n [6,1,0],\n [2,0,8]]\n\n\n
\n
Constraints:
\n\n1 <= rowSum.length, colSum.length <= 500
0 <= rowSum[i], colSum[i] <= 108
sum(rowSum) == sum(colSum)
You have k
servers numbered from 0
to k-1
that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:
ith
(0-indexed) request arrives.(i % k)th
server is available, assign the request to that server.ith
server is busy, try to assign the request to the (i+1)th
server, then the (i+2)th
server, and so on.You are given a strictly increasing array arrival
of positive integers, where arrival[i]
represents the arrival time of the ith
request, and another array load
, where load[i]
represents the load of the ith
request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.
Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.
\n\n\n
Example 1:
\n\nInput: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \nOutput: [1] \nExplanation: \nAll of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n\n\n
Example 2:
\n\n\nInput: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput: [0]\nExplanation: \nThe first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n\n\n
Example 3:
\n\n\nInput: k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput: [0,1,2]\nExplanation: Each server handles a single request, so they are all considered the busiest.\n\n\n
\n
Constraints:
\n\n1 <= k <= 105
1 <= arrival.length, load.length <= 105
arrival.length == load.length
1 <= arrival[i], load[i] <= 109
arrival
is strictly increasing.You are given an array nums
of non-negative integers. nums
is considered special if there exists a number x
such that there are exactly x
numbers in nums
that are greater than or equal to x
.
Notice that x
does not have to be an element in nums
.
Return x
if the array is special, otherwise, return -1
. It can be proven that if nums
is special, the value for x
is unique.
\n
Example 1:
\n\n\nInput: nums = [3,5]\nOutput: 2\nExplanation: There are 2 values (3 and 5) that are greater than or equal to 2.\n\n\n
Example 2:
\n\n\nInput: nums = [0,0]\nOutput: -1\nExplanation: No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.\n\n\n
Example 3:
\n\n\nInput: nums = [0,4,3,0,4]\nOutput: 3\nExplanation: There are 3 values that are greater than or equal to 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 1000
A binary tree is named Even-Odd if it meets the following conditions:
\n\n0
, its children are at level index 1
, their children are at level index 2
, etc.Given the root
of a binary tree, return true
if the binary tree is Even-Odd, otherwise return false
.
\n
Example 1:
\n\nInput: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput: true\nExplanation: The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\n\n\n
Example 2:
\n\nInput: root = [5,4,2,3,3,7]\nOutput: false\nExplanation: The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\n\n\n
Example 3:
\n\nInput: root = [5,9,1,3,5,7]\nOutput: false\nExplanation: Node values in the level 1 should be even integers.\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 106
You are given an array points
, an integer angle
, and your location
, where location = [posx, posy]
and points[i] = [xi, yi]
both denote integral coordinates on the X-Y plane.
Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx
and posy
cannot be changed. Your field of view in degrees is represented by angle
, determining how wide you can see from any given view direction. Let d
be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2]
.
\n\n
\n\nYou can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.
\n\nThere can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
\n\nReturn the maximum number of points you can see.
\n\n\n
Example 1:
\n\nInput: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput: 3\nExplanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n\n\n
Example 2:
\n\n\nInput: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput: 4\nExplanation: All points can be made visible in your field of view, including the one at your location.\n\n\n
Example 3:
\n\nInput: points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput: 1\nExplanation: You can only see one of the two points, as shown above.\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 105
points[i].length == 2
location.length == 2
0 <= angle < 360
0 <= posx, posy, xi, yi <= 100
Given an integer n
, you must transform it into 0
using the following operations any number of times:
0th
) bit in the binary representation of n
.ith
bit in the binary representation of n
if the (i-1)th
bit is set to 1
and the (i-2)th
through 0th
bits are set to 0
.Return the minimum number of operations to transform n
into 0
.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 2\nExplanation: The binary representation of 3 is "11".\n"11" -> "01" with the 2nd operation since the 0th bit is 1.\n"01" -> "00" with the 1st operation.\n\n\n
Example 2:
\n\n\nInput: n = 6\nOutput: 4\nExplanation: The binary representation of 6 is "110".\n"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n"010" -> "011" with the 1st operation.\n"011" -> "001" with the 2nd operation since the 0th bit is 1.\n"001" -> "000" with the 1st operation.\n\n\n
\n
Constraints:
\n\n0 <= n <= 109
Given a valid parentheses string s
, return the nesting depth of s
. The nesting depth is the maximum number of nested parentheses.
\n
Example 1:
\n\nInput: s = "(1+(2*3)+((8)/4))+1"
\n\nOutput: 3
\n\nExplanation:
\n\nDigit 8 is inside of 3 nested parentheses in the string.
\nExample 2:
\n\nInput: s = "(1)+((2))+(((3)))"
\n\nOutput: 3
\n\nExplanation:
\n\nDigit 3 is inside of 3 nested parentheses in the string.
\nExample 3:
\n\nInput: s = "()(())((()()))"
\n\nOutput: 3
\n\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of digits 0-9
and characters '+'
, '-'
, '*'
, '/'
, '('
, and ')'
.s
is a VPS.There is an infrastructure of n
cities with some number of roads
connecting these cities. Each roads[i] = [ai, bi]
indicates that there is a bidirectional road between cities ai
and bi
.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
\n\nThe maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
\n\nGiven the integer n
and the array roads
, return the maximal network rank of the entire infrastructure.
\n
Example 1:
\n\n\nInput: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput: 4\nExplanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.\n\n\n
Example 2:
\n\n\nInput: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput: 5\nExplanation: There are 5 roads that are connected to cities 1 or 2.\n\n\n
Example 3:
\n\n\nInput: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput: 5\nExplanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
0 <= roads.length <= n * (n - 1) / 2
roads[i].length == 2
0 <= ai, bi <= n-1
ai != bi
You are given two strings a
and b
of the same length. Choose an index and split both strings at the same index, splitting a
into two strings: aprefix
and asuffix
where a = aprefix + asuffix
, and splitting b
into two strings: bprefix
and bsuffix
where b = bprefix + bsuffix
. Check if aprefix + bsuffix
or bprefix + asuffix
forms a palindrome.
When you split a string s
into sprefix
and ssuffix
, either ssuffix
or sprefix
is allowed to be empty. For example, if s = "abc"
, then "" + "abc"
, "a" + "bc"
, "ab" + "c"
, and "abc" + ""
are valid splits.
Return true
if it is possible to form a palindrome string, otherwise return false
.
Notice that x + y
denotes the concatenation of strings x
and y
.
\n
Example 1:
\n\n\nInput: a = "x", b = "y"\nOutput: true\nExplaination: If either a or b are palindromes the answer is true since you can split in the following way:\naprefix = "", asuffix = "x"\nbprefix = "", bsuffix = "y"\nThen, aprefix + bsuffix = "" + "y" = "y", which is a palindrome.\n\n\n
Example 2:
\n\n\nInput: a = "xbdef", b = "xecab"\nOutput: false\n\n\n
Example 3:
\n\n\nInput: a = "ulacfd", b = "jizalu"\nOutput: true\nExplaination: Split them at index 3:\naprefix = "ula", asuffix = "cfd"\nbprefix = "jiz", bsuffix = "alu"\nThen, aprefix + bsuffix = "ula" + "alu" = "ulaalu", which is a palindrome.\n\n\n
\n
Constraints:
\n\n1 <= a.length, b.length <= 105
a.length == b.length
a
and b
consist of lowercase English lettersThere are n
cities numbered from 1
to n
. You are given an array edges
of size n-1
, where edges[i] = [ui, vi]
represents a bidirectional edge between cities ui
and vi
. There exists a unique path between each pair of cities. In other words, the cities form a tree.
A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.
\r\n\r\nFor each d
from 1
to n-1
, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d
.
Return an array of size n-1
where the dth
element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d
.
Notice that the distance between the two cities is the number of edges in the path between them.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: n = 4, edges = [[1,2],[2,3],[2,4]]\r\nOutput: [3,4,0]\r\nExplanation:\r\nThe subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r\nNo subtree has two nodes where the max distance between them is 3.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: n = 2, edges = [[1,2]]\r\nOutput: [1]\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: n = 3, edges = [[1,2],[2,3]]\r\nOutput: [2,1]\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n2 <= n <= 15
edges.length == n-1
edges[i].length == 2
1 <= ui, vi <= n
(ui, vi)
are distinct.Given an integer array arr
, return the mean of the remaining integers after removing the smallest 5%
and the largest 5%
of the elements.
Answers within 10-5
of the actual answer will be considered accepted.
\n
Example 1:
\n\n\nInput: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput: 2.00000\nExplanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\n\n\n
Example 2:
\n\n\nInput: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput: 4.00000\n\n\n
Example 3:
\n\n\nInput: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput: 4.77778\n\n\n
\n
Constraints:
\n\n20 <= arr.length <= 1000
arr.length
is a multiple of 20
.0 <= arr[i] <= 105
You are given an array of network towers towers
, where towers[i] = [xi, yi, qi]
denotes the ith
network tower with location (xi, yi)
and quality factor qi
. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.
You are also given an integer radius
where a tower is reachable if the distance is less than or equal to radius
. Outside that distance, the signal becomes garbled, and the tower is not reachable.
The signal quality of the ith
tower at a coordinate (x, y)
is calculated with the formula ⌊qi / (1 + d)⌋
, where d
is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.
Return the array [cx, cy]
representing the integral coordinate (cx, cy)
where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.
Note:
\n\n(x1, y1)
is lexicographically smaller than (x2, y2)
if either:\n\n\tx1 < x2
, orx1 == x2
and y1 < y2
.⌊val⌋
is the greatest integer less than or equal to val
(the floor function).\n
Example 1:
\n\nInput: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput: [2,1]\nExplanation: At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7\n- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2\n- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4\nNo other coordinate has a higher network quality.\n\n
Example 2:
\n\n\nInput: towers = [[23,11,21]], radius = 9\nOutput: [23,11]\nExplanation: Since there is only one tower, the network quality is highest right at the tower's location.\n\n\n
Example 3:
\n\n\nInput: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput: [1,2]\nExplanation: Coordinate (1, 2) has the highest network quality.\n\n\n
\n
Constraints:
\n\n1 <= towers.length <= 50
towers[i].length == 3
0 <= xi, yi, qi <= 50
1 <= radius <= 50
Given n
points on a 1-D plane, where the ith
point (from 0
to n-1
) is at x = i
, find the number of ways we can draw exactly k
non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k
line segments do not have to cover all n
points, and they are allowed to share endpoints.
Return the number of ways we can draw k
non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 4, k = 2\nOutput: 5\nExplanation: The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.\n\n\n
Example 2:
\n\n\nInput: n = 3, k = 1\nOutput: 3\nExplanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.\n\n\n
Example 3:
\n\n\nInput: n = 30, k = 7\nOutput: 796297179\nExplanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
1 <= k <= n-1
Write an API that generates fancy sequences using the append
, addAll
, and multAll
operations.
Implement the Fancy
class:
Fancy()
Initializes the object with an empty sequence.void append(val)
Appends an integer val
to the end of the sequence.void addAll(inc)
Increments all existing values in the sequence by an integer inc
.void multAll(m)
Multiplies all existing values in the sequence by an integer m
.int getIndex(idx)
Gets the current value at index idx
(0-indexed) of the sequence modulo 109 + 7
. If the index is greater or equal than the length of the sequence, return -1
.\n
Example 1:
\n\n\nInput\n["Fancy", "append", "addAll", "append", "multAll", "getIndex", "addAll", "append", "multAll", "getIndex", "getIndex", "getIndex"]\n[[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\nOutput\n[null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n\nExplanation\nFancy fancy = new Fancy();\nfancy.append(2); // fancy sequence: [2]\nfancy.addAll(3); // fancy sequence: [2+3] -> [5]\nfancy.append(7); // fancy sequence: [5, 7]\nfancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\nfancy.getIndex(0); // return 10\nfancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\nfancy.append(10); // fancy sequence: [13, 17, 10]\nfancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\nfancy.getIndex(0); // return 26\nfancy.getIndex(1); // return 34\nfancy.getIndex(2); // return 20\n\n\n
\n
Constraints:
\n\n1 <= val, inc, m <= 100
0 <= idx <= 105
105
calls total will be made to append
, addAll
, multAll
, and getIndex
.Given a string s
, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "aa"\nOutput: 0\nExplanation: The optimal substring here is an empty substring between the two 'a's
.
\n\nExample 2:
\n\n\nInput: s = "abca"\nOutput: 2\nExplanation: The optimal substring here is "bc".\n\n\n
Example 3:
\n\n\nInput: s = "cbzxy"\nOutput: -1\nExplanation: There are no characters that appear twice in s.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 300
s
contains only lowercase English letters.You are given a string s
of even length consisting of digits from 0
to 9
, and two integers a
and b
.
You can apply either of the following two operations any number of times and in any order on s
:
a
to all odd indices of s
(0-indexed). Digits post 9
are cycled back to 0
. For example, if s = "3456"
and a = 5
, s
becomes "3951"
.s
to the right by b
positions. For example, if s = "3456"
and b = 1
, s
becomes "6345"
.Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s
.
A string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, string a
has a letter that appears earlier in the alphabet than the corresponding letter in b
. For example, "0158"
is lexicographically smaller than "0190"
because the first position they differ is at the third letter, and '5'
comes before '9'
.
\n
Example 1:
\n\n\nInput: s = "5525", a = 9, b = 2\nOutput: "2050"\nExplanation: We can apply the following operations:\nStart: "5525"\nRotate: "2555"\nAdd: "2454"\nAdd: "2353"\nRotate: "5323"\nAdd: "5222"\nAdd: "5121"\nRotate: "2151"\nAdd: "2050"\u200b\u200b\u200b\u200b\u200b\nThere is no way to obtain a string that is lexicographically smaller than "2050".\n\n\n
Example 2:
\n\n\nInput: s = "74", a = 5, b = 1\nOutput: "24"\nExplanation: We can apply the following operations:\nStart: "74"\nRotate: "47"\n\u200b\u200b\u200b\u200b\u200b\u200b\u200bAdd: "42"\n\u200b\u200b\u200b\u200b\u200b\u200b\u200bRotate: "24"\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\nThere is no way to obtain a string that is lexicographically smaller than "24".\n\n\n
Example 3:
\n\n\nInput: s = "0011", a = 4, b = 2\nOutput: "0011"\nExplanation: There are no sequence of operations that will give us a lexicographically smaller string than "0011".\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 100
s.length
is even.s
consists of digits from 0
to 9
only.1 <= a <= 9
1 <= b <= s.length - 1
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.
\n\nHowever, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.
\n\nGiven two lists, scores
and ages
, where each scores[i]
and ages[i]
represents the score and age of the ith
player, respectively, return the highest overall score of all possible basketball teams.
\n
Example 1:
\n\n\nInput: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput: 34\nExplanation: You can choose all the players.\n\n\n
Example 2:
\n\n\nInput: scores = [4,5,6,5], ages = [2,1,2,1]\nOutput: 16\nExplanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\n\n\n
Example 3:
\n\n\nInput: scores = [1,2,3,5], ages = [8,9,10,1]\nOutput: 6\nExplanation: It is best to choose the first 3 players. \n\n\n
\n
Constraints:
\n\n1 <= scores.length, ages.length <= 1000
scores.length == ages.length
1 <= scores[i] <= 106
1 <= ages[i] <= 1000
We have n
cities labeled from 1
to n
. Two different cities with labels x
and y
are directly connected by a bidirectional road if and only if x
and y
share a common divisor strictly greater than some threshold
. More formally, cities with labels x
and y
have a road between them if there exists an integer z
such that all of the following are true:
x % z == 0
,y % z == 0
, andz > threshold
.Given the two integers, n
and threshold
, and an array of queries
, you must determine for each queries[i] = [ai, bi]
if cities ai
and bi
are connected directly or indirectly. (i.e. there is some path between them).
Return an array answer
, where answer.length == queries.length
and answer[i]
is true
if for the ith
query, there is a path between ai
and bi
, or answer[i]
is false
if there is no path.
\n
Example 1:
\n\nInput: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\nOutput: [false,false,true]\nExplanation: The divisors for each number:\n1: 1\n2: 1, 2\n3: 1, 3\n4: 1, 2, 4\n5: 1, 5\n6: 1, 2, 3, 6\nUsing the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\nonly ones directly connected. The result of each query:\n[1,4] 1 is not connected to 4\n[2,5] 2 is not connected to 5\n[3,6] 3 is connected to 6 through path 3--6\n\n\n
Example 2:
\n\nInput: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\nOutput: [true,true,true,true,true]\nExplanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\nall divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n\n\n
Example 3:
\n\nInput: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\nOutput: [false,false,false,false,false]\nExplanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\nPlease notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n\n\n
\n
Constraints:
\n\n2 <= n <= 104
0 <= threshold <= n
1 <= queries.length <= 105
queries[i].length == 2
1 <= ai, bi <= cities
ai != bi
A newly designed keypad was tested, where a tester pressed a sequence of n
keys, one at a time.
You are given a string keysPressed
of length n
, where keysPressed[i]
was the ith
key pressed in the testing sequence, and a sorted list releaseTimes
, where releaseTimes[i]
was the time the ith
key was released. Both arrays are 0-indexed. The 0th
key was pressed at the time 0
, and every subsequent key was pressed at the exact time the previous key was released.
The tester wants to know the key of the keypress that had the longest duration. The ith
keypress had a duration of releaseTimes[i] - releaseTimes[i - 1]
, and the 0th
keypress had a duration of releaseTimes[0]
.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.
\n\nReturn the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.
\n\n\n
Example 1:
\n\n\nInput: releaseTimes = [9,29,49,50], keysPressed = "cbcd"\nOutput: "c"\nExplanation: The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.\n\n\n
Example 2:
\n\n\nInput: releaseTimes = [12,23,36,46,62], keysPressed = "spuda"\nOutput: "a"\nExplanation: The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.\n\n
\n
Constraints:
\n\nreleaseTimes.length == n
keysPressed.length == n
2 <= n <= 1000
1 <= releaseTimes[i] <= 109
releaseTimes[i] < releaseTimes[i+1]
keysPressed
contains only lowercase English letters.A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s
is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0]
for all valid i
.
For example, these are arithmetic sequences:
\n\n\n1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9\n\n
The following sequence is not arithmetic:
\n\n\n1, 1, 2, 5, 7\n\n
You are given an array of n
integers, nums
, and two arrays of m
integers each, l
and r
, representing the m
range queries, where the ith
query is the range [l[i], r[i]]
. All the arrays are 0-indexed.
Return a list of boolean
elements answer
, where answer[i]
is true
if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]]
can be rearranged to form an arithmetic sequence, and false
otherwise.
\n
Example 1:
\n\n\nInput: nums =\n\n[4,6,5,9,3,7]
, l =[0,0,2]
, r =[2,3,5]
\nOutput:[true,false,true]
\nExplanation:\nIn the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2nd query, the subarray is[5,9,3,7]. This
can be rearranged as[3,5,7,9]
, which is an arithmetic sequence.
Example 2:
\n\n\nInput: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput: [false,true,false,false,true,true]\n\n\n
\n
Constraints:
\n\nn == nums.length
m == l.length
m == r.length
2 <= n <= 500
1 <= m <= 500
0 <= l[i] < r[i] < n
-105 <= nums[i] <= 105
You are a hiker preparing for an upcoming hike. You are given heights
, a 2D array of size rows x columns
, where heights[row][col]
represents the height of cell (row, col)
. You are situated in the top-left cell, (0, 0)
, and you hope to travel to the bottom-right cell, (rows-1, columns-1)
(i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.
A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.
\n\nReturn the minimum effort required to travel from the top-left cell to the bottom-right cell.
\n\n\n
Example 1:
\n\n\nInput: heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput: 2\nExplanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\n\n\n
Example 2:
\n\n\nInput: heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput: 1\nExplanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\n\n\n
Example 3:
\n\nInput: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput: 0\nExplanation: This route does not require any effort.\n\n\n
\n
Constraints:
\n\nrows == heights.length
columns == heights[i].length
1 <= rows, columns <= 100
1 <= heights[i][j] <= 106
Given an m x n
matrix
, return a new matrix answer
where answer[row][col]
is the rank of matrix[row][col]
.
The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:
\n\n1
.p
and q
are in the same row or column, then:\n\tp < q
then rank(p) < rank(q)
p == q
then rank(p) == rank(q)
p > q
then rank(p) > rank(q)
The test cases are generated so that answer
is unique under the given rules.
\n
Example 1:
\n\nInput: matrix = [[1,2],[3,4]]\nOutput: [[1,2],[2,3]]\nExplanation:\nThe rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\n\n\n
Example 2:
\n\nInput: matrix = [[7,7],[7,7]]\nOutput: [[1,1],[1,1]]\n\n\n
Example 3:
\n\nInput: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\nOutput: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 500
-109 <= matrix[row][col] <= 109
Table: Users
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| user_id | int |\n| user_name | varchar |\n+-------------+---------+\nuser_id is the primary key (column with unique values) for this table.\nEach row of this table contains the name and the id of a user.\n\n\n
\n\n
Table: Register
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| contest_id | int |\n| user_id | int |\n+-------------+---------+\n(contest_id, user_id) is the primary key (combination of columns with unique values) for this table.\nEach row of this table contains the id of a user and the contest they registered into.\n\n\n
\n\n
Write a solution to find the percentage of the users registered in each contest rounded to two decimals.
\n\nReturn the result table ordered by percentage
in descending order. In case of a tie, order it by contest_id
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+---------+-----------+\n| user_id | user_name |\n+---------+-----------+\n| 6 | Alice |\n| 2 | Bob |\n| 7 | Alex |\n+---------+-----------+\nRegister table:\n+------------+---------+\n| contest_id | user_id |\n+------------+---------+\n| 215 | 6 |\n| 209 | 2 |\n| 208 | 2 |\n| 210 | 6 |\n| 208 | 6 |\n| 209 | 7 |\n| 209 | 6 |\n| 215 | 7 |\n| 208 | 7 |\n| 210 | 2 |\n| 207 | 2 |\n| 210 | 7 |\n+------------+---------+\nOutput: \n+------------+------------+\n| contest_id | percentage |\n+------------+------------+\n| 208 | 100.0 |\n| 209 | 100.0 |\n| 210 | 100.0 |\n| 215 | 66.67 |\n| 207 | 33.33 |\n+------------+------------+\nExplanation: \nAll the users registered in contests 208, 209, and 210. The percentage is 100% and we sort them in the answer table by contest_id in ascending order.\nAlice and Alex registered in contest 215 and the percentage is ((2/3) * 100) = 66.67%\nBob registered in contest 207 and the percentage is ((1/3) * 100) = 33.33%\n\n", - "likes": 845, - "dislikes": 90, - "stats": "{\"totalAccepted\": \"317.7K\", \"totalSubmission\": \"543.1K\", \"totalAcceptedRaw\": 317668, \"totalSubmissionRaw\": 543092, \"acRate\": \"58.5%\"}", + "likes": 947, + "dislikes": 97, + "stats": "{\"totalAccepted\": \"387.2K\", \"totalSubmission\": \"657.1K\", \"totalAcceptedRaw\": 387160, \"totalSubmissionRaw\": 657067, \"acRate\": \"58.9%\"}", "similarQuestions": "[{\"title\": \"Queries Quality and Percentage\", \"titleSlug\": \"queries-quality-and-percentage\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -61609,9 +61690,9 @@ "questionFrontendId": "1634", "title": "Add Two Polynomials Represented as Linked Lists", "content": null, - "likes": 170, + "likes": 171, "dislikes": 14, - "stats": "{\"totalAccepted\": \"15.6K\", \"totalSubmission\": \"25.7K\", \"totalAcceptedRaw\": 15588, \"totalSubmissionRaw\": 25727, \"acRate\": \"60.6%\"}", + "stats": "{\"totalAccepted\": \"15.8K\", \"totalSubmission\": \"26.1K\", \"totalAcceptedRaw\": 15823, \"totalSubmissionRaw\": 26062, \"acRate\": \"60.7%\"}", "similarQuestions": "[{\"title\": \"Add Two Numbers\", \"titleSlug\": \"add-two-numbers\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Merge Two Sorted Lists\", \"titleSlug\": \"merge-two-sorted-lists\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Add Two Numbers II\", \"titleSlug\": \"add-two-numbers-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -61650,9 +61731,9 @@ "questionFrontendId": "1635", "title": "Hopper Company Queries I", "content": null, - "likes": 114, - "dislikes": 35, - "stats": "{\"totalAccepted\": \"9.5K\", \"totalSubmission\": \"19.8K\", \"totalAcceptedRaw\": 9512, \"totalSubmissionRaw\": 19801, \"acRate\": \"48.0%\"}", + "likes": 115, + "dislikes": 36, + "stats": "{\"totalAccepted\": \"10.1K\", \"totalSubmission\": \"20.9K\", \"totalAcceptedRaw\": 10120, \"totalSubmissionRaw\": 20893, \"acRate\": \"48.4%\"}", "similarQuestions": "[{\"title\": \"Trips and Users\", \"titleSlug\": \"trips-and-users\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries II\", \"titleSlug\": \"hopper-company-queries-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Hopper Company Queries III\", \"titleSlug\": \"hopper-company-queries-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Number of Times a Driver Was a Passenger\", \"titleSlug\": \"number-of-times-a-driver-was-a-passenger\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -61681,9 +61762,9 @@ "questionFrontendId": "1636", "title": "Sort Array by Increasing Frequency", "content": "
Given an array of integers nums
, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1,2,2,2,3]\nOutput: [3,1,1,2,2,2]\nExplanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,1,3,2]\nOutput: [1,3,3,2,2]\nExplanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.\n\n\n
Example 3:
\n\n\nInput: nums = [-1,1,-6,4,5,-6,1,4,1]\nOutput: [5,-1,4,4,-6,-6,1,1,1]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
-100 <= nums[i] <= 100
Given n
points
on a 2D plane where points[i] = [xi, yi]
, Return the widest vertical area between two points such that no points are inside the area.
A vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.
\n\nNote that points on the edge of a vertical area are not considered included in the area.
\n\n\n
Example 1:
\n\nInput: points = [[8,7],[9,9],[7,4],[9,7]]\nOutput: 1\nExplanation: Both the red and the blue area are optimal.\n\n\n
Example 2:
\n\n\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput: 3\n\n\n
\n
Constraints:
\n\nn == points.length
2 <= n <= 105
points[i].length == 2
0 <= xi, yi <= 109
Given two strings s
and t
, find the number of ways you can choose a non-empty substring of s
and replace a single character by a different character such that the resulting substring is a substring of t
. In other words, find the number of substrings in s
that differ from some substring in t
by exactly one character.
For example, the underlined substrings in "computer"
and "computation"
only differ by the 'e'
/'a'
, so this is a valid way.
Return the number of substrings that satisfy the condition above.
\n\nA substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "aba", t = "baba"\nOutput: 6\nExplanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\n("aba", "baba")\nThe underlined portions are the substrings that are chosen from s and t.\n\n\u200b\u200bExample 2:\n\n
\nInput: s = "ab", t = "bb"\nOutput: 3\nExplanation: The following are the pairs of substrings from s and t that differ by 1 character:\n("ab", "bb")\n("ab", "bb")\n("ab", "bb")\n\u200b\u200b\u200b\u200bThe underlined portions are the substrings that are chosen from s and t.\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 100
s
and t
consist of lowercase English letters only.You are given a list of strings of the same length words
and a string target
.
Your task is to form target
using the given words
under the following rules:
target
should be formed from left to right.ith
character (0-indexed) of target
, you can choose the kth
character of the jth
string in words
if target[i] = words[j][k]
.kth
character of the jth
string of words
, you can no longer use the xth
character of any string in words
where x <= k
. In other words, all characters to the left of or at index k
become unusuable for every string.target
.Notice that you can use multiple characters from the same string in words
provided the conditions above are met.
Return the number of ways to form target
from words
. Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: words = ["acca","bbbb","caca"], target = "aba"\nOutput: 6\nExplanation: There are 6 ways to form target.\n"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")\n"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")\n"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")\n"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")\n"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")\n"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")\n\n\n
Example 2:
\n\n\nInput: words = ["abba","baab"], target = "bab"\nOutput: 4\nExplanation: There are 4 ways to form target.\n"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")\n"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")\n"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")\n"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 1000
words
have the same length.1 <= target.length <= 1000
words[i]
and target
contain only lowercase English letters.You are given an array of distinct integers arr
and an array of integer arrays pieces
, where the integers in pieces
are distinct. Your goal is to form arr
by concatenating the arrays in pieces
in any order. However, you are not allowed to reorder the integers in each array pieces[i]
.
Return true
if it is possible to form the array arr
from pieces
. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: arr = [15,88], pieces = [[88],[15]]\nOutput: true\nExplanation: Concatenate [15] then [88]\n\n\n
Example 2:
\n\n\nInput: arr = [49,18,16], pieces = [[16,18,49]]\nOutput: false\nExplanation: Even though the numbers match, we cannot reorder pieces[0].\n\n\n
Example 3:
\n\n\nInput: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput: true\nExplanation: Concatenate [91] then [4,64] then [78]\n\n\n
\n
Constraints:
\n\n1 <= pieces.length <= arr.length <= 100
sum(pieces[i].length) == arr.length
1 <= pieces[i].length <= arr.length
1 <= arr[i], pieces[i][j] <= 100
arr
are distinct.pieces
are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).Given an integer n
, return the number of strings of length n
that consist only of vowels (a
, e
, i
, o
, u
) and are lexicographically sorted.
A string s
is lexicographically sorted if for all valid i
, s[i]
is the same as or comes before s[i+1]
in the alphabet.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 5\nExplanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"].
\n
\n\nExample 2:
\n\n\nInput: n = 2\nOutput: 15\nExplanation: The 15 sorted strings that consist of vowels only are\n["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].\nNote that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.\n\n\n
Example 3:
\n\n\nInput: n = 33\nOutput: 66045\n\n\n
\n
Constraints:
\n\n1 <= n <= 50
You are given an integer array heights
representing the heights of buildings, some bricks
, and some ladders
.
You start your journey from building 0
and move to the next building by possibly using bricks or ladders.
While moving from building i
to building i+1
(0-indexed),
(h[i+1] - h[i])
bricks.Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.
\n\n\n
Example 1:
\n\nInput: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\nOutput: 4\nExplanation: Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.\n\n\n
Example 2:
\n\n\nInput: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\nOutput: 7\n\n\n
Example 3:
\n\n\nInput: heights = [14,3,19,3], bricks = 17, ladders = 0\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= heights.length <= 105
1 <= heights[i] <= 106
0 <= bricks <= 109
0 <= ladders <= heights.length
Bob is standing at cell (0, 0)
, and he wants to reach destination
: (row, column)
. He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination
.
The instructions are represented as a string, where each character is either:
\n\n'H'
, meaning move horizontally (go right), or'V'
, meaning move vertically (go down).Multiple instructions will lead Bob to destination
. For example, if destination
is (2, 3)
, both "HHHVV"
and "HVHVH"
are valid instructions.
However, Bob is very picky. Bob has a lucky number k
, and he wants the kth
lexicographically smallest instructions that will lead him to destination
. k
is 1-indexed.
Given an integer array destination
and an integer k
, return the kth
lexicographically smallest instructions that will take Bob to destination
.
\n
Example 1:
\n\n\nInput: destination = [2,3], k = 1\nOutput: "HHHVV"\nExplanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].\n\n\n
Example 2:
\n\n\nInput: destination = [2,3], k = 2\nOutput: "HHVHV"\n\n\n
Example 3:
\n\n\nInput: destination = [2,3], k = 3\nOutput: "HHVVH"\n\n\n
\n
Constraints:
\n\ndestination.length == 2
1 <= row, column <= 15
1 <= k <= nCr(row + column, row)
, where nCr(a, b)
denotes a
choose b
\u200b\u200b\u200b\u200b\u200b.You are given an integer n
. A 0-indexed integer array nums
of length n + 1
is generated in the following way:
nums[0] = 0
nums[1] = 1
nums[2 * i] = nums[i]
when 2 <= 2 * i <= n
nums[2 * i + 1] = nums[i] + nums[i + 1]
when 2 <= 2 * i + 1 <= n
Return the maximum integer in the array nums
\u200b\u200b\u200b.
\n
Example 1:
\n\n\nInput: n = 7\nOutput: 3\nExplanation: According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 1\nExplanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.\n\n\n
Example 3:
\n\n\nInput: n = 3\nOutput: 2\nExplanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.\n\n\n
\n
Constraints:
\n\n0 <= n <= 100
A string s
is called good if there are no two different characters in s
that have the same frequency.
Given a string s
, return the minimum number of characters you need to delete to make s
good.
The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab"
, the frequency of 'a'
is 2
, while the frequency of 'b'
is 1
.
\n
Example 1:
\n\n\nInput: s = "aab"\nOutput: 0\nExplanation: s
is already good.\n
\n\nExample 2:
\n\n\nInput: s = "aaabbbcc"\nOutput: 2\nExplanation: You can delete two 'b's resulting in the good string "aaabcc".\nAnother way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".\n\n
Example 3:
\n\n\nInput: s = "ceabaacb"\nOutput: 2\nExplanation: You can delete both 'c's resulting in the good string "eabaab".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
contains only lowercase English letters.You have an inventory
of different colored balls, and there is a customer that wants orders
balls of any color.
The customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory
. For example, if you own 6
yellow balls, the customer would pay 6
for the first yellow ball. After the transaction, there are only 5
yellow balls left, so the next yellow ball is then valued at 5
(i.e., the value of the balls decreases as you sell more to the customer).
You are given an integer array, inventory
, where inventory[i]
represents the number of balls of the ith
color that you initially own. You are also given an integer orders
, which represents the total number of balls that the customer wants. You can sell the balls in any order.
Return the maximum total value that you can attain after selling orders
colored balls. As the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: inventory = [2,5], orders = 4\nOutput: 14\nExplanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.\n\n\n
Example 2:
\n\n\nInput: inventory = [3,5], orders = 6\nOutput: 19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.\n\n\n
\n
Constraints:
\n\n1 <= inventory.length <= 105
1 <= inventory[i] <= 109
1 <= orders <= min(sum(inventory[i]), 109)
Given an integer array instructions
, you are asked to create a sorted array from the elements in instructions
. You start with an empty container nums
. For each element from left to right in instructions
, insert it into nums
. The cost of each insertion is the minimum of the following:
nums
that are strictly less than instructions[i]
.nums
that are strictly greater than instructions[i]
.For example, if inserting element 3
into nums = [1,2,3,5]
, the cost of insertion is min(2, 1)
(elements 1
and 2
are less than 3
, element 5
is greater than 3
) and nums
will become [1,2,3,3,5]
.
Return the total cost to insert all elements from instructions
into nums
. Since the answer may be large, return it modulo 109 + 7
\r\n
Example 1:
\r\n\r\n\r\nInput: instructions = [1,5,6,2]\r\nOutput: 1\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 5 with cost min(1, 0) = 0, now nums = [1,5].\r\nInsert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\r\nInsert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\r\nThe total cost is 0 + 0 + 0 + 1 = 1.\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: instructions = [1,2,3,6,5,4]\r\nOutput: 3\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 2 with cost min(1, 0) = 0, now nums = [1,2].\r\nInsert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\r\nInsert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\r\nInsert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\r\nInsert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\r\nThe total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: instructions = [1,3,3,3,2,4,2,1,2]\r\nOutput: 4\r\nExplanation: Begin with nums = [].\r\nInsert 1 with cost min(0, 0) = 0, now nums = [1].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\r\nInsert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\r\nInsert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\r\nInsert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\r\n\u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\r\n\u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\r\n\u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\r\nThe total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= instructions.length <= 105
1 <= instructions[i] <= 105
You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code
of length of n
and a key k
.
To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.
\n\nk > 0
, replace the ith
number with the sum of the next k
numbers.k < 0
, replace the ith
number with the sum of the previous k
numbers.k == 0
, replace the ith
number with 0
.As code
is circular, the next element of code[n-1]
is code[0]
, and the previous element of code[0]
is code[n-1]
.
Given the circular array code
and an integer key k
, return the decrypted code to defuse the bomb!
\n
Example 1:
\n\n\nInput: code = [5,7,1,4], k = 3\nOutput: [12,10,16,13]\nExplanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.\n\n\n
Example 2:
\n\n\nInput: code = [1,2,3,4], k = 0\nOutput: [0,0,0,0]\nExplanation: When k is zero, the numbers are replaced by 0. \n\n\n
Example 3:
\n\n\nInput: code = [2,4,9,3], k = -2\nOutput: [12,5,6,13]\nExplanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.\n\n\n
\n
Constraints:
\n\nn == code.length
1 <= n <= 100
1 <= code[i] <= 100
-(n - 1) <= k <= n - 1
You are given a string s
consisting only of characters 'a'
and 'b'
\u200b\u200b\u200b\u200b.
You can delete any number of characters in s
to make s
balanced. s
is balanced if there is no pair of indices (i,j)
such that i < j
and s[i] = 'b'
and s[j]= 'a'
.
Return the minimum number of deletions needed to make s
balanced.
\n
Example 1:
\n\n\nInput: s = "aababbab"\nOutput: 2\nExplanation: You can either:\nDelete the characters at 0-indexed positions 2 and 6 ("aababbab" -> "aaabbb"), or\nDelete the characters at 0-indexed positions 3 and 6 ("aababbab" -> "aabbbb").\n\n\n
Example 2:
\n\n\nInput: s = "bbaaaaabb"\nOutput: 2\nExplanation: The only solution is to delete the first two characters.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is 'a'
or 'b'
\u200b\u200b.A certain bug's home is on the x-axis at position x
. Help them get there from position 0
.
The bug jumps according to the following rules:
\n\na
positions forward (to the right).b
positions backward (to the left).forbidden
positions.The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.
\n\nGiven an array of integers forbidden
, where forbidden[i]
means that the bug cannot jump to the position forbidden[i]
, and integers a
, b
, and x
, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x
, return -1.
\n
Example 1:
\n\n\nInput: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput: 3\nExplanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.\n\n\n
Example 2:
\n\n\nInput: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput: -1\n\n\n
Example 3:
\n\n\nInput: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput: 2\nExplanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.\n\n\n
\n
Constraints:
\n\n1 <= forbidden.length <= 1000
1 <= a, b, forbidden[i] <= 2000
0 <= x <= 2000
forbidden
are distinct.x
is not forbidden.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:
ith
customer gets exactly quantity[i]
integers,ith
customer gets are all equal, andReturn true
if it is possible to distribute nums
according to the above conditions.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4], quantity = [2]\nOutput: false\nExplanation: The 0th customer cannot be given two different integers.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,3], quantity = [2]\nOutput: true\nExplanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,2,2], quantity = [2,2]\nOutput: true\nExplanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
1 <= nums[i] <= 1000
m == quantity.length
1 <= m <= 10
1 <= quantity[i] <= 105
50
unique values in nums
.There is a stream of n
(idKey, value)
pairs arriving in an arbitrary order, where idKey
is an integer between 1
and n
and value
is a string. No two pairs have the same id
.
Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.
\n\nImplement the OrderedStream
class:
OrderedStream(int n)
Constructs the stream to take n
values.String[] insert(int idKey, String value)
Inserts the pair (idKey, value)
into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.\n
Example:
\n\n\nInput\n["OrderedStream", "insert", "insert", "insert", "insert", "insert"]\n[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]\nOutput\n[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]\n\nExplanation\n// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].\nOrderedStream os = new OrderedStream(5);\nos.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].\nos.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].\nos.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].\nos.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].\nos.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].\n// Concatentating all the chunks returned:\n// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]\n// The resulting order is the same as the order above.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
1 <= id <= n
value.length == 5
value
consists only of lowercase letters.insert
will have a unique id.
n
calls will be made to insert
.Two strings are considered close if you can attain one from the other using the following operations:
\n\nabcde -> aecdb
aacabb -> bbcbaa
(all a
's turn into b
's, and all b
's turn into a
's)You can use the operations on either string as many times as necessary.
\n\nGiven two strings, word1
and word2
, return true
if word1
and word2
are close, and false
otherwise.
\n
Example 1:
\n\n\nInput: word1 = "abc", word2 = "bca"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: "abc" -> "acb"\nApply Operation 1: "acb" -> "bca"\n\n\n
Example 2:
\n\n\nInput: word1 = "a", word2 = "aa"\nOutput: false\nExplanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n\n\n
Example 3:
\n\n\nInput: word1 = "cabbba", word2 = "abbccc"\nOutput: true\nExplanation: You can attain word2 from word1 in 3 operations.\nApply Operation 1: "cabbba" -> "caabbb"\nApply Operation 2: "caabbb" -> "baaccc"\nApply Operation 2: "baaccc" -> "abbccc"\n\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 105
word1
and word2
contain only lowercase English letters.You are given an integer array nums
and an integer x
. In one operation, you can either remove the leftmost or the rightmost element from the array nums
and subtract its value from x
. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x
to exactly 0
if it is possible, otherwise, return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,1,4,2,3], x = 5\nOutput: 2\nExplanation: The optimal solution is to remove the last two elements to reduce x to zero.\n\n\n
Example 2:
\n\n\nInput: nums = [5,6,7,8,9], x = 4\nOutput: -1\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,20,1,1,3], x = 10\nOutput: 5\nExplanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 104
1 <= x <= 109
You are given four integers, m
, n
, introvertsCount
, and extrovertsCount
. You have an m x n
grid, and there are two types of people: introverts and extroverts. There are introvertsCount
introverts and extrovertsCount
extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.
\n\nThe happiness of each person is calculated as follows:
\n\n120
happiness and lose 30
happiness for each neighbor (introvert or extrovert).40
happiness and gain 20
happiness for each neighbor (introvert or extrovert).Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
\n\nThe grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
\n\n\n
Example 1:
\n\nInput: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\nOutput: 240\nExplanation: Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\n\n\n
Example 2:
\n\n\nInput: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\nOutput: 260\nExplanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.\n\n\n
Example 3:
\n\n\nInput: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\nOutput: 240\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 5
0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
Table: Activity
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| machine_id | int |\n| process_id | int |\n| activity_type | enum |\n| timestamp | float |\n+----------------+---------+\nThe table shows the user activities for a factory website.\n(machine_id, process_id, activity_type) is the primary key (combination of columns with unique values) of this table.\nmachine_id is the ID of a machine.\nprocess_id is the ID of a process running on the machine with ID machine_id.\nactivity_type is an ENUM (category) of type ('start', 'end').\ntimestamp is a float representing the current time in seconds.\n'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp.\nThe 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair.\nIt is guaranteed that each (machine_id, process_id) pair has a 'start' and 'end' timestamp.\n\n\n
\n\n
There is a factory website that has several machines each running the same number of processes. Write a solution to find the average time each machine takes to complete a process.
\n\nThe time to complete a process is the 'end' timestamp
minus the 'start' timestamp
. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.
The resulting table should have the machine_id
along with the average time as processing_time
, which should be rounded to 3 decimal places.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nActivity table:\n+------------+------------+---------------+-----------+\n| machine_id | process_id | activity_type | timestamp |\n+------------+------------+---------------+-----------+\n| 0 | 0 | start | 0.712 |\n| 0 | 0 | end | 1.520 |\n| 0 | 1 | start | 3.140 |\n| 0 | 1 | end | 4.120 |\n| 1 | 0 | start | 0.550 |\n| 1 | 0 | end | 1.550 |\n| 1 | 1 | start | 0.430 |\n| 1 | 1 | end | 1.420 |\n| 2 | 0 | start | 4.100 |\n| 2 | 0 | end | 4.512 |\n| 2 | 1 | start | 2.500 |\n| 2 | 1 | end | 5.000 |\n+------------+------------+---------------+-----------+\nOutput: \n+------------+-----------------+\n| machine_id | processing_time |\n+------------+-----------------+\n| 0 | 0.894 |\n| 1 | 0.995 |\n| 2 | 1.456 |\n+------------+-----------------+\nExplanation: \nThere are 3 machines running 2 processes each.\nMachine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894\nMachine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995\nMachine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456\n\n", - "likes": 1744, - "dislikes": 174, - "stats": "{\"totalAccepted\": \"467.9K\", \"totalSubmission\": \"679.6K\", \"totalAcceptedRaw\": 467876, \"totalSubmissionRaw\": 679617, \"acRate\": \"68.8%\"}", + "likes": 1957, + "dislikes": 192, + "stats": "{\"totalAccepted\": \"571.7K\", \"totalSubmission\": \"832.4K\", \"totalAcceptedRaw\": 571713, \"totalSubmissionRaw\": 832414, \"acRate\": \"68.7%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -62715,9 +62796,9 @@ "questionFrontendId": "1662", "title": "Check If Two String Arrays are Equivalent", "content": "
Given two string arrays word1
and word2
, return true
if the two arrays represent the same string, and false
otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
\n\n\n
Example 1:
\n\n\nInput: word1 = ["ab", "c"], word2 = ["a", "bc"]\nOutput: true\nExplanation:\nword1 represents string "ab" + "c" -> "abc"\nword2 represents string "a" + "bc" -> "abc"\nThe strings are the same, so return true.\n\n
Example 2:
\n\n\nInput: word1 = ["a", "cb"], word2 = ["ab", "c"]\nOutput: false\n\n\n
Example 3:
\n\n\nInput: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]\nOutput: true\n\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 103
1 <= word1[i].length, word2[i].length <= 103
1 <= sum(word1[i].length), sum(word2[i].length) <= 103
word1[i]
and word2[i]
consist of lowercase letters.The numeric value of a lowercase character is defined as its position (1-indexed)
in the alphabet, so the numeric value of a
is 1
, the numeric value of b
is 2
, the numeric value of c
is 3
, and so on.
The numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string "abe"
is equal to 1 + 2 + 5 = 8
.
You are given two integers n
and k
. Return the lexicographically smallest string with length equal to n
and numeric value equal to k
.
Note that a string x
is lexicographically smaller than string y
if x
comes before y
in dictionary order, that is, either x
is a prefix of y
, or if i
is the first position such that x[i] != y[i]
, then x[i]
comes before y[i]
in alphabetic order.
\n
Example 1:
\n\n\nInput: n = 3, k = 27\nOutput: "aay"\nExplanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.\n\n\n
Example 2:
\n\n\nInput: n = 5, k = 73\nOutput: "aaszz"\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
n <= k <= 26 * n
You are given an integer array nums
. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.
For example, if nums = [6,1,7,4,1]
:
1
results in nums = [6,7,4,1]
.2
results in nums = [6,1,4,1]
.4
results in nums = [6,1,7,4]
.An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.
\n\nReturn the number of indices that you could choose such that after the removal, nums
is fair.
\n
Example 1:
\n\n\nInput: nums = [2,1,6,4]\nOutput: 1\nExplanation:\nRemove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can remove any index and the remaining array is fair.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: You cannot make a fair array after removing any index.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 104
You are given an array tasks
where tasks[i] = [actuali, minimumi]
:
actuali
is the actual amount of energy you spend to finish the ith
task.minimumi
is the minimum amount of energy you require to begin the ith
task.For example, if the task is [10, 12]
and your current energy is 11
, you cannot start this task. However, if your current energy is 13
, you can complete this task, and your energy will be 3
after finishing it.
You can finish the tasks in any order you like.
\n\nReturn the minimum initial amount of energy you will need to finish all the tasks.
\n\n\n
Example 1:
\n\n\nInput: tasks = [[1,2],[2,4],[4,8]]\nOutput: 8\nExplanation:\nStarting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n\n
Example 2:
\n\n\nInput: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput: 32\nExplanation:\nStarting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.\n\n
Example 3:
\n\n\nInput: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput: 27\nExplanation:\nStarting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.\n\n\n
\n
Constraints:
\n\n1 <= tasks.length <= 105
1 <= actual\u200bi <= minimumi <= 104
Table: Users
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| user_id | int |\n| name | varchar |\n+----------------+---------+\nuser_id is the primary key (column with unique values) for this table.\nThis table contains the ID and the name of the user. The name consists of only lowercase and uppercase characters.\n\n\n
\n\n
Write a solution to fix the names so that only the first character is uppercase and the rest are lowercase.
\n\nReturn the result table ordered by user_id
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nUsers table:\n+---------+-------+\n| user_id | name |\n+---------+-------+\n| 1 | aLice |\n| 2 | bOB |\n+---------+-------+\nOutput: \n+---------+-------+\n| user_id | name |\n+---------+-------+\n| 1 | Alice |\n| 2 | Bob |\n+---------+-------+\n\n", - "likes": 935, - "dislikes": 121, - "stats": "{\"totalAccepted\": \"310.5K\", \"totalSubmission\": \"507.6K\", \"totalAcceptedRaw\": 310460, \"totalSubmissionRaw\": 507618, \"acRate\": \"61.2%\"}", + "likes": 976, + "dislikes": 127, + "stats": "{\"totalAccepted\": \"356.2K\", \"totalSubmission\": \"584.7K\", \"totalAcceptedRaw\": 356245, \"totalSubmissionRaw\": 584684, \"acRate\": \"60.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -62928,9 +63009,9 @@ "questionFrontendId": "1668", "title": "Maximum Repeating Substring", "content": "
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 value is 0
.
Given strings sequence
and word
, return the maximum k
-repeating value of word
in sequence
.
\n
Example 1:
\n\n\nInput: sequence = "ababc", word = "ab"\nOutput: 2\nExplanation: "abab" is a substring in "ababc".\n\n\n
Example 2:
\n\n\nInput: sequence = "ababc", word = "ba"\nOutput: 1\nExplanation: "ba" is a substring in "ababc". "baba" is not a substring in "ababc".\n\n\n
Example 3:
\n\n\nInput: sequence = "ababc", word = "ac"\nOutput: 0\nExplanation: "ac" is not a substring in "ababc". \n\n\n
\n
Constraints:
\n\n1 <= sequence.length <= 100
1 <= word.length <= 100
sequence
and word
contains only lowercase English letters.You are given two linked lists: list1
and list2
of sizes n
and m
respectively.
Remove list1
's nodes from the ath
node to the bth
node, and put list2
in their place.
The blue edges and nodes in the following figure indicate the result:
\nBuild the result list and return its head.
\n\n\n
Example 1:
\n\nInput: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput: [10,1,13,1000000,1000001,1000002,5]\nExplanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.\n\n\n
Example 2:
\n\nInput: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput: [0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation: The blue edges and nodes in the above figure indicate the result.\n\n\n
\n
Constraints:
\n\n3 <= list1.length <= 104
1 <= a <= b < list1.length - 1
1 <= list2.length <= 104
Design a queue that supports push
and pop
operations in the front, middle, and back.
Implement the FrontMiddleBack
class:
FrontMiddleBack()
Initializes the queue.void pushFront(int val)
Adds val
to the front of the queue.void pushMiddle(int val)
Adds val
to the middle of the queue.void pushBack(int val)
Adds val
to the back of the queue.int popFront()
Removes the front element of the queue and returns it. If the queue is empty, return -1
.int popMiddle()
Removes the middle element of the queue and returns it. If the queue is empty, return -1
.int popBack()
Removes the back element of the queue and returns it. If the queue is empty, return -1
.Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:
\n\n6
into the middle of [1, 2, 3, 4, 5]
results in [1, 2, 6, 3, 4, 5]
.[1, 2, 3, 4, 5, 6]
returns 3
and results in [1, 2, 4, 5, 6]
.\n
Example 1:
\n\n\nInput:\n["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]\n[[], [1], [2], [3], [4], [], [], [], [], []]\nOutput:\n[null, null, null, null, null, 1, 3, 4, 2, -1]\n\nExplanation:\nFrontMiddleBackQueue q = new FrontMiddleBackQueue();\nq.pushFront(1); // [1]\nq.pushBack(2); // [1, 2]\nq.pushMiddle(3); // [1, 3, 2]\nq.pushMiddle(4); // [1, 4, 3, 2]\nq.popFront(); // return 1 -> [4, 3, 2]\nq.popMiddle(); // return 3 -> [4, 2]\nq.popMiddle(); // return 4 -> [2]\nq.popBack(); // return 2 -> []\nq.popFront(); // return -1 -> [] (The queue is empty)\n\n\n
\n
Constraints:
\n\n1 <= val <= 109
1000
calls will be made to pushFront
, pushMiddle
, pushBack
, popFront
, popMiddle
, and popBack
.You may recall that an array arr
is a mountain array if and only if:
arr.length >= 3
i
(0-indexed) with 0 < i < arr.length - 1
such that:\n\tarr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given an integer array nums
\u200b\u200b\u200b, return the minimum number of elements to remove to make nums\u200b\u200b\u200b
a mountain array.
\n
Example 1:
\n\n\nInput: nums = [1,3,1]\nOutput: 0\nExplanation: The array itself is a mountain array so we do not need to remove any elements.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,1,5,6,2,3,1]\nOutput: 3\nExplanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 1000
1 <= nums[i] <= 109
nums
.You are given an m x n
integer grid accounts
where accounts[i][j]
is the amount of money the i\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b
customer has in the j\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth
\u200b\u200b\u200b\u200b bank. Return the wealth that the richest customer has.
A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.
\n\n\n
Example 1:
\n\n\nInput: accounts = [[1,2,3],[3,2,1]]\nOutput: 6\nExplanation:\n\n\n1st customer has wealth = 1 + 2 + 3 = 6\n
2nd customer has wealth = 3 + 2 + 1 = 6\n
Both customers are considered the richest with a wealth of 6 each, so return 6.\n
Example 2:
\n\n\nInput: accounts = [[1,5],[7,3],[3,5]]\nOutput: 10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.\n\n
Example 3:
\n\n\nInput: accounts = [[2,8,7],[7,1,3],[1,9,5]]\nOutput: 17\n\n\n
\n
Constraints:
\n\nm == accounts.length
n == accounts[i].length
1 <= m, n <= 50
1 <= accounts[i][j] <= 100
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.
\n\nWe define that a subsequence a
is more competitive than a subsequence b
(of the same length) if in the first position where a
and b
differ, subsequence a
has a number less than the corresponding number in b
. For example, [1,3,4]
is more competitive than [1,3,5]
because the first position they differ is at the final number, and 4
is less than 5
.
\n
Example 1:
\n\n\nInput: nums = [3,5,2,6], k = 2\nOutput: [2,6]\nExplanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,3,3,5,4,9,6], k = 4\nOutput: [2,3,3,4]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
1 <= k <= nums.length
You are given an integer array nums
of even length n
and an integer limit
. In one move, you can replace any integer from nums
with another integer between 1
and limit
, inclusive.
The array nums
is complementary if for all indices i
(0-indexed), nums[i] + nums[n - 1 - i]
equals the same number. For example, the array [1,2,3,4]
is complementary because for all indices i
, nums[i] + nums[n - 1 - i] = 5
.
Return the minimum number of moves required to make nums
complementary.
\n
Example 1:
\n\n\nInput: nums = [1,2,4,3], limit = 4\nOutput: 1\nExplanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,2,1], limit = 2\nOutput: 2\nExplanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,1,2], limit = 2\nOutput: 0\nExplanation: nums is already complementary.\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 105
1 <= nums[i] <= limit <= 105
n
is even.You are given an array nums
of n
positive integers.
You can perform two types of operations on any element of the array any number of times:
\n\n2
.\n\n\t[1,2,3,4]
, then you can do this operation on the last element, and the array will be [1,2,3,2].
2
.\n\t[1,2,3,4]
, then you can do this operation on the first element, and the array will be [2,2,3,4].
The deviation of the array is the maximum difference between any two elements in the array.
\n\nReturn the minimum deviation the array can have after performing some number of operations.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n\n\n
Example 2:
\n\n\nInput: nums = [4,1,5,20,3]\nOutput: 3\nExplanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n\n\n
Example 3:
\n\n\nInput: nums = [2,10,8]\nOutput: 3\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 5 * 104
1 <= nums[i] <= 109
You own a Goal Parser that can interpret a string command
. The command
consists of an alphabet of "G"
, "()"
and/or "(al)"
in some order. The Goal Parser will interpret "G"
as the string "G"
, "()"
as the string "o"
, and "(al)"
as the string "al"
. The interpreted strings are then concatenated in the original order.
Given the string command
, return the Goal Parser's interpretation of command
.
\n
Example 1:
\n\n\nInput: command = "G()(al)"\nOutput: "Goal"\nExplanation: The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is "Goal".\n\n\n
Example 2:
\n\n\nInput: command = "G()()()()(al)"\nOutput: "Gooooal"\n\n\n
Example 3:
\n\n\nInput: command = "(al)G(al)()()G"\nOutput: "alGalooG"\n\n\n
\n
Constraints:
\n\n1 <= command.length <= 100
command
consists of "G"
, "()"
, and/or "(al)"
in some order.You are given an integer array nums
and an integer k
.
In one operation, you can pick two numbers from the array whose sum equals k
and remove them from the array.
Return the maximum number of operations you can perform on the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4], k = 5\nOutput: 2\nExplanation: Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.\n\n
Example 2:
\n\n\nInput: nums = [3,1,3,4,3], k = 6\nOutput: 1\nExplanation: Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
Given an integer n
, return the decimal value of the binary string formed by concatenating the binary representations of 1
to n
in order, modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 1\nExplanation: "1" in binary corresponds to the decimal value 1. \n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: 27\nExplanation: In binary, 1, 2, and 3 corresponds to "1", "10", and "11".\nAfter concatenating them, we have "11011", which corresponds to the decimal value 27.\n\n\n
Example 3:
\n\n\nInput: n = 12\nOutput: 505379714\nExplanation: The concatenation results in "1101110010111011110001001101010111100".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given an integer array nums
\u200b\u200b\u200b and an integer k
. You are asked to distribute this array into k
subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
\n\nReturn the minimum possible sum of incompatibilities of the k
subsets after distributing the array optimally, or return -1
if it is not possible.
A subset is a group integers that appear in the array with no particular order.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,4], k = 2\nOutput: 4\nExplanation: The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n\n
Example 2:
\n\n\nInput: nums = [6,3,8,1,3,1,2,2], k = 4\nOutput: 6\nExplanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n\n\n
Example 3:
\n\n\nInput: nums = [5,3,3,6,3,3], k = 3\nOutput: -1\nExplanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 16
nums.length
is divisible by k
1 <= nums[i] <= nums.length
Table: Tweets
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| tweet_id | int |\n| content | varchar |\n+----------------+---------+\ntweet_id is the primary key (column with unique values) for this table.\ncontent consists of characters on an American Keyboard, and no other special characters.\nThis table contains all the tweets in a social media app.\n\n\n
\n\n
Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTweets table:\n+----------+-----------------------------------+\n| tweet_id | content |\n+----------+-----------------------------------+\n| 1 | Let us Code |\n| 2 | More than fifteen chars are here! |\n+----------+-----------------------------------+\nOutput: \n+----------+\n| tweet_id |\n+----------+\n| 2 |\n+----------+\nExplanation: \nTweet 1 has length = 11. It is a valid tweet.\nTweet 2 has length = 33. It is an invalid tweet.\n\n", - "likes": 1161, - "dislikes": 376, - "stats": "{\"totalAccepted\": \"889.7K\", \"totalSubmission\": \"1M\", \"totalAcceptedRaw\": 889747, \"totalSubmissionRaw\": 1038405, \"acRate\": \"85.7%\"}", + "content": "
Table: Tweets
\n+----------------+---------+\n| Column Name | Type |\n+----------------+---------+\n| tweet_id | int |\n| content | varchar |\n+----------------+---------+\ntweet_id is the primary key (column with unique values) for this table.\ncontent consists of alphanumeric characters, '!', or ' ' and no other special characters.\nThis table contains all the tweets in a social media app.\n\n\n
\n\n
Write a solution to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is strictly greater than 15
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTweets table:\n+----------+-----------------------------------+\n| tweet_id | content |\n+----------+-----------------------------------+\n| 1 | Let us Code |\n| 2 | More than fifteen chars are here! |\n+----------+-----------------------------------+\nOutput: \n+----------+\n| tweet_id |\n+----------+\n| 2 |\n+----------+\nExplanation: \nTweet 1 has length = 11. It is a valid tweet.\nTweet 2 has length = 33. It is an invalid tweet.\n\n", + "likes": 1266, + "dislikes": 378, + "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"1.3M\", \"totalAcceptedRaw\": 1071479, \"totalSubmissionRaw\": 1252855, \"acRate\": \"85.5%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -63534,9 +63615,9 @@ "questionFrontendId": "1684", "title": "Count the Number of Consistent Strings", "content": "
You are given a string allowed
consisting of distinct characters and an array of strings words
. A string is consistent if all characters in the string appear in the string allowed
.
Return the number of consistent strings in the array words
.
\n
Example 1:
\n\n\nInput: allowed = "ab", words = ["ad","bd","aaab","baa","badab"]\nOutput: 2\nExplanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'.\n\n\n
Example 2:
\n\n\nInput: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]\nOutput: 7\nExplanation: All strings are consistent.\n\n\n
Example 3:
\n\n\nInput: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]\nOutput: 4\nExplanation: Strings "cc", "acd", "ac", and "d" are consistent.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 104
1 <= allowed.length <= 26
1 <= words[i].length <= 10
allowed
are distinct.words[i]
and allowed
contain only lowercase English letters.You are given an integer array nums
sorted in non-decreasing order.
Build and return an integer array result
with the same length as nums
such that result[i]
is equal to the summation of absolute differences between nums[i]
and all the other elements in the array.
In other words, result[i]
is equal to sum(|nums[i]-nums[j]|)
where 0 <= j < nums.length
and j != i
(0-indexed).
\n
Example 1:
\n\n\nInput: nums = [2,3,5]\nOutput: [4,3,5]\nExplanation: Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,6,8,10]\nOutput: [24,15,13,15,21]\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= nums[i + 1] <= 104
Alice and Bob take turns playing a game, with Alice starting first.
\n\nThere are n
stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.
You are given two integer arrays of length n
, aliceValues
and bobValues
. Each aliceValues[i]
and bobValues[i]
represents how Alice and Bob, respectively, value the ith
stone.
The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.
\n\nDetermine the result of the game, and:
\n\n1
.-1
.0
.\n
Example 1:
\n\n\nInput: aliceValues = [1,3], bobValues = [2,1]\nOutput: 1\nExplanation:\nIf Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.\n\n\n
Example 2:
\n\n\nInput: aliceValues = [1,2], bobValues = [3,1]\nOutput: 0\nExplanation:\nIf Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.\n\n\n
Example 3:
\n\n\nInput: aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput: -1\nExplanation:\nRegardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.\n\n\n
\n
Constraints:
\n\nn == aliceValues.length == bobValues.length
1 <= n <= 105
1 <= aliceValues[i], bobValues[i] <= 100
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.
\n\nYou are given an array boxes
, where boxes[i] = [ports\u200b\u200bi\u200b, weighti]
, and three integers portsCount
, maxBoxes
, and maxWeight
.
ports\u200b\u200bi
is the port where you need to deliver the ith
box and weightsi
is the weight of the ith
box.portsCount
is the number of ports.maxBoxes
and maxWeight
are the respective box and weight limits of the ship.The boxes need to be delivered in the order they are given. The ship will follow these steps:
\n\nboxes
queue, not violating the maxBoxes
and maxWeight
constraints.The ship must end at storage after all the boxes have been delivered.
\n\nReturn the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.
\n\n\n
Example 1:
\n\n\nInput: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput: 4\nExplanation: The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n\n\n
Example 2:
\n\n\nInput: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput: 6\nExplanation: The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\n\n
Example 3:
\n\n\nInput: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput: 6\nExplanation: The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n\n\n
\n
Constraints:
\n\n1 <= boxes.length <= 105
1 <= portsCount, maxBoxes, maxWeight <= 105
1 <= ports\u200b\u200bi <= portsCount
1 <= weightsi <= maxWeight
You are given an integer n
, the number of teams in a tournament that has strange rules:
n / 2
matches are played, and n / 2
teams advance to the next round.(n - 1) / 2
matches are played, and (n - 1) / 2 + 1
teams advance to the next round.Return the number of matches played in the tournament until a winner is decided.
\n\n\n
Example 1:
\n\n\nInput: n = 7\nOutput: 6\nExplanation: Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.\n\n\n
Example 2:
\n\n\nInput: n = 14\nOutput: 13\nExplanation: Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.\n\n\n
\n
Constraints:
\n\n1 <= n <= 200
A decimal number is called deci-binary if each of its digits is either 0
or 1
without any leading zeros. For example, 101
and 1100
are deci-binary, while 112
and 3001
are not.
Given a string n
that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n
.
\n
Example 1:
\n\n\nInput: n = "32"\nOutput: 3\nExplanation: 10 + 11 + 11 = 32\n\n\n
Example 2:
\n\n\nInput: n = "82734"\nOutput: 8\n\n\n
Example 3:
\n\n\nInput: n = "27346209830709182346"\nOutput: 9\n\n\n
\n
Constraints:
\n\n1 <= n.length <= 105
n
consists of only digits.n
does not contain any leading zeros and represents a positive integer.Alice and Bob take turns playing a game, with Alice starting first.
\n\nThere are n
stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.
\n\nGiven an array of integers stones
where stones[i]
represents the value of the ith
stone from the left, return the difference in Alice and Bob's score if they both play optimally.
\n
Example 1:
\n\n\nInput: stones = [5,3,1,4,2]\nOutput: 6\nExplanation: \n- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6.\n\n\n
Example 2:
\n\n\nInput: stones = [7,90,5,1,100,10,10,2]\nOutput: 122\n\n
\n
Constraints:
\n\nn == stones.length
2 <= n <= 1000
1 <= stones[i] <= 1000
Given n
cuboids
where the dimensions of the ith
cuboid is cuboids[i] = [widthi, lengthi, heighti]
(0-indexed). Choose a subset of cuboids
and place them on each other.
You can place cuboid i
on cuboid j
if widthi <= widthj
and lengthi <= lengthj
and heighti <= heightj
. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.
Return the maximum height of the stacked cuboids
.
\n
Example 1:
\n\n\nInput: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\nOutput: 190\nExplanation:\nCuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.\n\n\n
Example 2:
\n\n\nInput: cuboids = [[38,25,45],[76,35,3]]\nOutput: 76\nExplanation:\nYou can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\n\n\n
Example 3:
\n\n\nInput: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\nOutput: 102\nExplanation:\nAfter rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.\n\n\n
\n
Constraints:
\n\nn == cuboids.length
1 <= n <= 100
1 <= widthi, lengthi, heighti <= 100
Table: DailySales
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| date_id | date |\n| make_name | varchar |\n| lead_id | int |\n| partner_id | int |\n+-------------+---------+\nThere is no primary key (column with unique values) for this table. It may contain duplicates.\nThis table contains the date and the name of the product sold and the IDs of the lead and partner it was sold to.\nThe name consists of only lowercase English letters.\n\n\n
\n\n
For each date_id
and make_name
, find the number of distinct lead_id
's and distinct partner_id
's.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nDailySales table:\n+-----------+-----------+---------+------------+\n| date_id | make_name | lead_id | partner_id |\n+-----------+-----------+---------+------------+\n| 2020-12-8 | toyota | 0 | 1 |\n| 2020-12-8 | toyota | 1 | 0 |\n| 2020-12-8 | toyota | 1 | 2 |\n| 2020-12-7 | toyota | 0 | 2 |\n| 2020-12-7 | toyota | 0 | 1 |\n| 2020-12-8 | honda | 1 | 2 |\n| 2020-12-8 | honda | 2 | 1 |\n| 2020-12-7 | honda | 0 | 1 |\n| 2020-12-7 | honda | 1 | 2 |\n| 2020-12-7 | honda | 2 | 1 |\n+-----------+-----------+---------+------------+\nOutput: \n+-----------+-----------+--------------+-----------------+\n| date_id | make_name | unique_leads | unique_partners |\n+-----------+-----------+--------------+-----------------+\n| 2020-12-8 | toyota | 2 | 3 |\n| 2020-12-7 | toyota | 1 | 2 |\n| 2020-12-8 | honda | 2 | 2 |\n| 2020-12-7 | honda | 3 | 2 |\n+-----------+-----------+--------------+-----------------+\nExplanation: \nFor 2020-12-8, toyota gets leads = [0, 1] and partners = [0, 1, 2] while honda gets leads = [1, 2] and partners = [1, 2].\nFor 2020-12-7, toyota gets leads = [0] and partners = [1, 2] while honda gets leads = [0, 1, 2] and partners = [1, 2].\n\n", - "likes": 580, - "dislikes": 33, - "stats": "{\"totalAccepted\": \"151.1K\", \"totalSubmission\": \"174.5K\", \"totalAcceptedRaw\": 151107, \"totalSubmissionRaw\": 174468, \"acRate\": \"86.6%\"}", + "likes": 595, + "dislikes": 34, + "stats": "{\"totalAccepted\": \"165.9K\", \"totalSubmission\": \"191.5K\", \"totalAcceptedRaw\": 165879, \"totalSubmissionRaw\": 191489, \"acRate\": \"86.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -63935,9 +64016,9 @@ "questionFrontendId": "1694", "title": "Reformat Phone Number", "content": "
You are given a phone number as a string number
. number
consists of digits, spaces ' '
, and/or dashes '-'
.
You would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:
\n\nThe blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.
\n\nReturn the phone number after formatting.
\n\n\n
Example 1:
\n\n\nInput: number = "1-23-45 6"\nOutput: "123-456"\nExplanation: The digits are "123456".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is "456".\nJoining the blocks gives "123-456".\n\n\n
Example 2:
\n\n\nInput: number = "123 4-567"\nOutput: "123-45-67"\nExplanation: The digits are "1234567".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is "123".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are "45" and "67".\nJoining the blocks gives "123-45-67".\n\n\n
Example 3:
\n\n\nInput: number = "123 4-5678"\nOutput: "123-456-78"\nExplanation: The digits are "12345678".\nStep 1: The 1st block is "123".\nStep 2: The 2nd block is "456".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is "78".\nJoining the blocks gives "123-456-78".\n\n\n
\n
Constraints:
\n\n2 <= number.length <= 100
number
consists of digits and the characters '-'
and ' '
.number
.You are given an array of positive integers nums
and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.
Return the maximum score you can get by erasing exactly one subarray.
\n\nAn array b
is called to be a subarray of a
if it forms a contiguous subsequence of a
, that is, if it is equal to a[l],a[l+1],...,a[r]
for some (l,r)
.
\n
Example 1:
\n\n\nInput: nums = [4,2,4,5,6]\nOutput: 17\nExplanation: The optimal subarray here is [2,4,5,6].\n\n\n
Example 2:
\n\n\nInput: nums = [5,2,1,2,5,2,1,2,5]\nOutput: 8\nExplanation: The optimal subarray here is [5,2,1] or [1,2,5].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 104
You are given a 0-indexed integer array nums
and an integer k
.
You are initially standing at index 0
. In one move, you can jump at most k
steps forward without going outside the boundaries of the array. That is, you can jump from index i
to any index in the range [i + 1, min(n - 1, i + k)]
inclusive.
You want to reach the last index of the array (index n - 1
). Your score is the sum of all nums[j]
for each index j
you visited in the array.
Return the maximum score you can get.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\n\n\n
Example 2:
\n\n\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\n\n\n
Example 3:
\n\n\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n\n\n
\n
Constraints:
\n\n1 <= nums.length, k <= 105
-104 <= nums[i] <= 104
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 each queries[j]
whether there is a path between pj
and qj
such that each edge on the path has a distance strictly less than limitj
.
Return a boolean array answer
, where answer.length == queries.length
and the jth
value of answer
is true
if there is a path for queries[j]
is true
, and false
otherwise.
\n
Example 1:
\n\nInput: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\nOutput: [false,true]\nExplanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\n\n\n
Example 2:
\n\nInput: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\nOutput: [true,false]\nExplanation: The above figure shows the given graph.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
1 <= edgeList.length, queries.length <= 105
edgeList[i].length == 3
queries[j].length == 3
0 <= ui, vi, pj, qj <= n - 1
ui != vi
pj != qj
1 <= disi, limitj <= 109
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0
and 1
respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:
\n\nThis continues until none of the queue students want to take the top sandwich and are thus unable to eat.
\n\nYou are given two integer arrays students
and sandwiches
where sandwiches[i]
is the type of the i\u200b\u200b\u200b\u200b\u200b\u200bth
sandwich in the stack (i = 0
is the top of the stack) and students[j]
is the preference of the j\u200b\u200b\u200b\u200b\u200b\u200bth
student in the initial queue (j = 0
is the front of the queue). Return the number of students that are unable to eat.
\n
Example 1:
\n\n\nInput: students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput: 0 \nExplanation:\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.\n\n\n
Example 2:
\n\n\nInput: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= students.length, sandwiches.length <= 100
students.length == sandwiches.length
sandwiches[i]
is 0
or 1
.students[i]
is 0
or 1
.There is a restaurant with a single chef. You are given an array customers
, where customers[i] = [arrivali, timei]:
arrivali
is the arrival time of the ith
customer. The arrival times are sorted in non-decreasing order.timei
is the time needed to prepare the order of the ith
customer.When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.
\n\nReturn the average waiting time of all customers. Solutions within 10-5
from the actual answer are considered accepted.
\n
Example 1:
\n\n\nInput: customers = [[1,2],[2,5],[4,3]]\nOutput: 5.00000\nExplanation:\n1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.\n\n\n
Example 2:
\n\n\nInput: customers = [[5,2],[5,4],[10,3],[20,1]]\nOutput: 3.25000\nExplanation:\n1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.\n\n\n
\n
Constraints:
\n\n1 <= customers.length <= 105
1 <= arrivali, timei <= 104
arrivali <= arrivali+1
You are given a binary string binary
consisting of only 0
's or 1
's. You can apply each of the following operations any number of times:
"00"
, you can replace it with "10"
.\n\n\t"00010" -> "10010
""10"
, you can replace it with "01"
.\n\t"00010" -> "00001"
Return the maximum binary string you can obtain after any number of operations. Binary string x
is greater than binary string y
if x
's decimal representation is greater than y
's decimal representation.
\n
Example 1:
\n\n\nInput: binary = "000110"\nOutput: "111011"\nExplanation: A valid transformation sequence can be:\n"000110" -> "000101" \n"000101" -> "100101" \n"100101" -> "110101" \n"110101" -> "110011" \n"110011" -> "111011"\n\n\n
Example 2:
\n\n\nInput: binary = "01"\nOutput: "01"\nExplanation: "01" cannot be transformed any further.\n\n\n
\n
Constraints:
\n\n1 <= binary.length <= 105
binary
consist of '0'
and '1'
.You are given an integer array, nums
, and an integer k
. nums
comprises of only 0
's and 1
's. In one move, you can choose two adjacent indices and swap their values.
Return the minimum number of moves required so that nums
has k
consecutive 1
's.
\n
Example 1:
\n\n\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: 1\nExplanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\n\n\n
Example 2:
\n\n\nInput: nums = [1,0,0,0,0,0,1,1], k = 3\nOutput: 5\nExplanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,0,1], k = 2\nOutput: 0\nExplanation: nums already has 2 consecutive 1's.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is 0
or 1
.1 <= k <= sum(nums)
You are given a string s
of even length. Split this string into two halves of equal lengths, and let a
be the first half and b
be the second half.
Two strings are alike if they have the same number of vowels ('a'
, 'e'
, 'i'
, 'o'
, 'u'
, 'A'
, 'E'
, 'I'
, 'O'
, 'U'
). Notice that s
contains uppercase and lowercase letters.
Return true
if a
and b
are alike. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: s = "book"\nOutput: true\nExplanation: a = "bo" and b = "ok". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\n\n\n
Example 2:
\n\n\nInput: s = "textbook"\nOutput: false\nExplanation: a = "text" and b = "book". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 1000
s.length
is even.s
consists of uppercase and lowercase letters.There is a special kind of apple tree that grows apples every day for n
days. On the ith
day, the tree grows apples[i]
apples that will rot after days[i]
days, that is on day i + days[i]
the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0
and days[i] == 0
.
You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n
days.
Given two integer arrays days
and apples
of length n
, return the maximum number of apples you can eat.
\n
Example 1:
\n\n\nInput: apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput: 7\nExplanation: You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.\n\n\n
Example 2:
\n\n\nInput: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput: 5\nExplanation: You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.\n\n\n
\n
Constraints:
\n\nn == apples.length == days.length
1 <= n <= 2 * 104
0 <= apples[i], days[i] <= 2 * 104
days[i] = 0
if and only if apples[i] = 0
.You have a 2-D grid
of size m x n
representing a box, and you have n
balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
\n\n1
.-1
.We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box.
\n\nReturn an array answer
of size n
where answer[i]
is the column that the ball falls out of at the bottom after dropping the ball from the ith
column at the top, or -1
if the ball gets stuck in the box.
\n
Example 1:
\n\n\nInput: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput: [1,-1,-1,-1,-1]\nExplanation: This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\n\n\n
Example 2:
\n\n\nInput: grid = [[-1]]\nOutput: [-1]\nExplanation: The ball gets stuck against the left wall.\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput: [0,1,2,3,4,-1]\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 100
grid[i][j]
is 1
or -1
.You are given an array nums
consisting of non-negative integers. You are also given a queries
array, where queries[i] = [xi, mi]
.
The answer to the ith
query is the maximum bitwise XOR
value of xi
and any element of nums
that does not exceed mi
. In other words, the answer is max(nums[j] XOR xi)
for all j
such that nums[j] <= mi
. If all elements in nums
are larger than mi
, then the answer is -1
.
Return an integer array answer
where answer.length == queries.length
and answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\nOutput: [3,3,7]\nExplanation:\n1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.\n\n\n
Example 2:
\n\n\nInput: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\nOutput: [15,-1,5]\n\n\n
\n
Constraints:
\n\n1 <= nums.length, queries.length <= 105
queries[i].length == 2
0 <= nums[j], xi, mi <= 109
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes
, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]
:
numberOfBoxesi
is the number of boxes of type i
.numberOfUnitsPerBoxi
is the number of units in each box of the type i
.You are also given an integer truckSize
, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize
.
Return the maximum total number of units that can be put on the truck.
\n\n\n
Example 1:
\n\n\nInput: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\nOutput: 8\nExplanation: There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.\n\n\n
Example 2:
\n\n\nInput: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\nOutput: 91\n\n\n
\n
Constraints:
\n\n1 <= boxTypes.length <= 1000
1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
1 <= truckSize <= 106
A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.
\n\nYou can pick any two different foods to make a good meal.
\n\nGiven an array of integers deliciousness
where deliciousness[i]
is the deliciousness of the i\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b
\u200b\u200b\u200b\u200b item of food, return the number of different good meals you can make from this list modulo 109 + 7
.
Note that items with different indices are considered different even if they have the same deliciousness value.
\n\n\n
Example 1:
\n\n\nInput: deliciousness = [1,3,5,7,9]\nOutput: 4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.\n\n\n
Example 2:
\n\n\nInput: deliciousness = [1,1,1,3,3,3,7]\nOutput: 15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n\n
\n
Constraints:
\n\n1 <= deliciousness.length <= 105
0 <= deliciousness[i] <= 220
A split of an integer array is good if:
\n\nleft
, mid
, right
respectively from left to right.left
is less than or equal to the sum of the elements in mid
, and the sum of the elements in mid
is less than or equal to the sum of the elements in right
.Given nums
, an array of non-negative integers, return the number of good ways to split nums
. As the number may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [1,1,1]\nOutput: 1\nExplanation: The only good way to split nums is [1] [1] [1].\n\n
Example 2:
\n\n\nInput: nums = [1,2,2,2,5,0]\nOutput: 3\nExplanation: There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: There is no good way to split nums.\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
0 <= nums[i] <= 104
You are given an array target
that consists of distinct integers and another integer array arr
that can have duplicates.
In one operation, you can insert any integer at any position in arr
. For example, if arr = [1,4,1,2]
, you can add 3
in the middle and make it [1,4,3,1,2]
. Note that you can insert the integer at the very beginning or end of the array.
Return the minimum number of operations needed to make target
a subsequence of arr
.
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4]
is a subsequence of [4,2,3,7,2,1,4]
(the underlined elements), while [2,4,2]
is not.
\n
Example 1:
\n\n\nInput: target = [5,1,3],\n\narr
= [9,4,2,3,4]\nOutput: 2\nExplanation: You can add 5 and 1 in such a way that makesarr
= [5,9,4,1,2,3,4], then target will be a subsequence ofarr
.\n
Example 2:
\n\n\nInput: target = [6,4,8,1,3,2], arr
= [4,7,6,2,3,8,6,1]\nOutput: 3\n
\n\n\n
Constraints:
\n\n1 <= target.length, arr.length <= 105
1 <= target[i], arr[i] <= 109
target
contains no duplicates.Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.
\n\nHe starts by putting in $1
on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1
more than the day before. On every subsequent Monday, he will put in $1
more than the previous Monday.
Given n
, return the total amount of money he will have in the Leetcode bank at the end of the nth
day.
\n
Example 1:
\n\n\nInput: n = 4\nOutput: 10\nExplanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: 37\nExplanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\n\n\n
Example 3:
\n\n\nInput: n = 20\nOutput: 96\nExplanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You are given a string s
and two integers x
and y
. You can perform two types of operations any number of times.
"ab"
and gain x
points.\n\n\t"ab"
from "cabxbae"
it becomes "cxbae"
."ba"
and gain y
points.\n\t"ba"
from "cabxbae"
it becomes "cabxe"
.Return the maximum points you can gain after applying the above operations on s
.
\n
Example 1:
\n\n\nInput: s = "cdbcbbaaabab", x = 4, y = 5\nOutput: 19\nExplanation:\n- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.\n- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.\n- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.\n- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.\n\n
Example 2:
\n\n\nInput: s = "aabbaaxybbaabb", x = 5, y = 4\nOutput: 20\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
1 <= x, y <= 104
s
consists of lowercase English letters.Given an integer n
, find a sequence that satisfies all of the following:
1
occurs once in the sequence.2
and n
occurs twice in the sequence.i
between 2
and n
, the distance between the two occurrences of i
is exactly i
.The distance between two numbers on the sequence, a[i]
and a[j]
, is the absolute difference of their indices, |j - i|
.
Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
\n\nA sequence a
is lexicographically larger than a sequence b
(of the same length) if in the first position where a
and b
differ, sequence a
has a number greater than the corresponding number in b
. For example, [0,1,9,0]
is lexicographically larger than [0,1,5,6]
because the first position they differ is at the third number, and 9
is greater than 5
.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: [3,1,2,3,2]\nExplanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: [5,3,1,4,3,5,2,4,2]\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
Given an integer n
, find a sequence with elements in the range [1, n]
that satisfies all of the following:
1
occurs once in the sequence.2
and n
occurs twice in the sequence.i
between 2
and n
, the distance between the two occurrences of i
is exactly i
.The distance between two numbers on the sequence, a[i]
and a[j]
, is the absolute difference of their indices, |j - i|
.
Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.
\n\nA sequence a
is lexicographically larger than a sequence b
(of the same length) if in the first position where a
and b
differ, sequence a
has a number greater than the corresponding number in b
. For example, [0,1,9,0]
is lexicographically larger than [0,1,5,6]
because the first position they differ is at the third number, and 9
is greater than 5
.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: [3,1,2,3,2]\nExplanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: [5,3,1,4,3,5,2,4,2]\n\n\n
\n
Constraints:
\n\n1 <= n <= 20
You are given an array pairs
, where pairs[i] = [xi, yi]
, and:
xi < yi
Let ways
be the number of rooted trees that satisfy the following conditions:
pairs
.[xi, yi]
exists in pairs
if and only if xi
is an ancestor of yi
or yi
is an ancestor of xi
.Two ways are considered to be different if there is at least one node that has different parents in both ways.
\n\nReturn:
\n\n0
if ways == 0
1
if ways == 1
2
if ways > 1
A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.
\n\nAn ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
\n\n\n
Example 1:
\n\nInput: pairs = [[1,2],[2,3]]\nOutput: 1\nExplanation: There is exactly one valid rooted tree, which is shown in the above figure.\n\n\n
Example 2:
\n\nInput: pairs = [[1,2],[2,3],[1,3]]\nOutput: 2\nExplanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\n\n\n
Example 3:
\n\n\nInput: pairs = [[1,2],[2,3],[2,4],[1,5]]\nOutput: 0\nExplanation: There are no valid rooted trees.\n\n
\n
Constraints:
\n\n1 <= pairs.length <= 105
1 <= xi < yi <= 500
pairs
are unique.There is a hidden integer array arr
that consists of n
non-negative integers.
It was encoded into another integer array encoded
of length n - 1
, such that encoded[i] = arr[i] XOR arr[i + 1]
. For example, if arr = [1,0,2,1]
, then encoded = [1,2,3]
.
You are given the encoded
array. You are also given an integer first
, that is the first element of arr
, i.e. arr[0]
.
Return the original array arr
. It can be proved that the answer exists and is unique.
\n
Example 1:
\n\n\nInput: encoded = [1,2,3], first = 1\nOutput: [1,0,2,1]\nExplanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]\n\n\n
Example 2:
\n\n\nInput: encoded = [6,2,7,3], first = 4\nOutput: [4,2,0,7,4]\n\n\n
\n
Constraints:
\n\n2 <= n <= 104
encoded.length == n - 1
0 <= encoded[i] <= 105
0 <= first <= 105
You are given the head
of a linked list, and an integer k
.
Return the head of the linked list after swapping the values of the kth
node from the beginning and the kth
node from the end (the list is 1-indexed).
\n
Example 1:
\n\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\n\n\n
Example 2:
\n\n\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n\n\n
\n
Constraints:
\n\nn
.1 <= k <= n <= 105
0 <= Node.val <= 100
You are given two integer arrays, source
and target
, both of length n
. You are also given an array allowedSwaps
where each allowedSwaps[i] = [ai, bi]
indicates that you are allowed to swap the elements at index ai
and index bi
(0-indexed) of array source
. Note that you can swap elements at a specific pair of indices multiple times and in any order.
The Hamming distance of two arrays of the same length, source
and target
, is the number of positions where the elements are different. Formally, it is the number of indices i
for 0 <= i <= n-1
where source[i] != target[i]
(0-indexed).
Return the minimum Hamming distance of source
and target
after performing any amount of swap operations on array source
.
\n
Example 1:
\n\n\nInput: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput: 1\nExplanation: source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.\n\n\n
Example 2:
\n\n\nInput: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput: 2\nExplanation: There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.\n\n\n
Example 3:
\n\n\nInput: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput: 0\n\n\n
\n
Constraints:
\n\nn == source.length == target.length
1 <= n <= 105
1 <= source[i], target[i] <= 105
0 <= allowedSwaps.length <= 105
allowedSwaps[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
You are given an integer array jobs
, where jobs[i]
is the amount of time it takes to complete the ith
job.
There are k
workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.
Return the minimum possible maximum working time of any assignment.
\n\n\n
Example 1:
\n\n\nInput: jobs = [3,2,3], k = 3\nOutput: 3\nExplanation: By assigning each person one job, the maximum time is 3.\n\n\n
Example 2:
\n\n\nInput: jobs = [1,2,4,7,8], k = 2\nOutput: 11\nExplanation: Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.\n\n
\n
Constraints:
\n\n1 <= k <= jobs.length <= 12
1 <= jobs[i] <= 107
You are given an array rectangles
where rectangles[i] = [li, wi]
represents the ith
rectangle of length li
and width wi
.
You can cut the ith
rectangle to form a square with a side length of k
if both k <= li
and k <= wi
. For example, if you have a rectangle [4,6]
, you can cut it to get a square with a side length of at most 4
.
Let maxLen
be the side length of the largest square you can obtain from any of the given rectangles.
Return the number of rectangles that can make a square with a side length of maxLen
.
\r\n
Example 1:
\r\n\r\n\r\nInput: rectangles = [[5,8],[3,9],[5,12],[16,5]]\r\nOutput: 3\r\nExplanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].\r\nThe largest possible square is of length 5, and you can get it out of 3 rectangles.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: rectangles = [[2,3],[3,7],[4,3],[3,7]]\r\nOutput: 3\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= rectangles.length <= 1000
rectangles[i].length == 2
1 <= li, wi <= 109
li != wi
Given an array nums
of distinct positive integers, return the number of tuples (a, b, c, d)
such that a * b = c * d
where a
, b
, c
, and d
are elements of nums
, and a != b != c != d
.
\n
Example 1:
\n\n\nInput: nums = [2,3,4,6]\nOutput: 8\nExplanation: There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,4,5,10]\nOutput: 16\nExplanation: There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 104
nums
are distinct.You are given a binary matrix matrix
of size m x n
, and you are allowed to rearrange the columns of the matrix
in any order.
Return the area of the largest submatrix within matrix
where every element of the submatrix is 1
after reordering the columns optimally.
\n
Example 1:
\n\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput: 4\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.\n\n\n
Example 2:
\n\nInput: matrix = [[1,0,1,0,1]]\nOutput: 3\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.\n\n\n
Example 3:
\n\n\nInput: matrix = [[1,1,0],[1,0,1]]\nOutput: 2\nExplanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m * n <= 105
matrix[i][j]
is either 0
or 1
.A game is played by a cat and a mouse named Cat and Mouse.
\n\nThe environment is represented by a grid
of size rows x cols
, where each element is a wall, floor, player (Cat, Mouse), or food.
'C'
(Cat),'M'
(Mouse).'.'
and can be walked on.'#'
and cannot be walked on.'F'
and can be walked on.'C'
, 'M'
, and 'F'
in grid
.Mouse and Cat play according to the following rules:
\n\ngrid
.catJump, mouseJump
are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.The game can end in 4 ways:
\n\nGiven a rows x cols
matrix grid
and two integers catJump
and mouseJump
, return true
if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false
.
\n
Example 1:
\n\nInput: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2\nOutput: true\nExplanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\n\n\n
Example 2:
\n\nInput: grid = ["M.C...F"], catJump = 1, mouseJump = 4\nOutput: true\n\n\n
Example 3:
\n\n\nInput: grid = ["M.C...F"], catJump = 1, mouseJump = 3\nOutput: false\n\n\n
\n
Constraints:
\n\nrows == grid.length
cols = grid[i].length
1 <= rows, cols <= 8
grid[i][j]
consist only of characters 'C'
, 'M'
, 'F'
, '.'
, and '#'
.'C'
, 'M'
, and 'F'
in grid
.1 <= catJump, mouseJump <= 8
Table: Followers
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| user_id | int |\n| follower_id | int |\n+-------------+------+\n(user_id, follower_id) is the primary key (combination of columns with unique values) for this table.\nThis table contains the IDs of a user and a follower in a social media app where the follower follows the user.\n\n
\n\n
Write a solution that will, for each user, return the number of followers.
\n\nReturn the result table ordered by user_id
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nFollowers table:\n+---------+-------------+\n| user_id | follower_id |\n+---------+-------------+\n| 0 | 1 |\n| 1 | 0 |\n| 2 | 0 |\n| 2 | 1 |\n+---------+-------------+\nOutput: \n+---------+----------------+\n| user_id | followers_count|\n+---------+----------------+\n| 0 | 1 |\n| 1 | 1 |\n| 2 | 2 |\n+---------+----------------+\nExplanation: \nThe followers of 0 are {1}\nThe followers of 1 are {0}\nThe followers of 2 are {0,1}\n\n", - "likes": 627, - "dislikes": 32, - "stats": "{\"totalAccepted\": \"297.7K\", \"totalSubmission\": \"428.9K\", \"totalAcceptedRaw\": 297685, \"totalSubmissionRaw\": 428928, \"acRate\": \"69.4%\"}", + "likes": 668, + "dislikes": 39, + "stats": "{\"totalAccepted\": \"352.5K\", \"totalSubmission\": \"506.7K\", \"totalAcceptedRaw\": 352513, \"totalSubmissionRaw\": 506727, \"acRate\": \"69.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -65291,9 +65375,9 @@ "questionFrontendId": "1730", "title": "Shortest Path to Get Food", "content": null, - "likes": 705, + "likes": 706, "dislikes": 41, - "stats": "{\"totalAccepted\": \"76.2K\", \"totalSubmission\": \"135.1K\", \"totalAcceptedRaw\": 76174, \"totalSubmissionRaw\": 135136, \"acRate\": \"56.4%\"}", + "stats": "{\"totalAccepted\": \"78.8K\", \"totalSubmission\": \"139K\", \"totalAcceptedRaw\": 78797, \"totalSubmissionRaw\": 139003, \"acRate\": \"56.7%\"}", "similarQuestions": "[{\"title\": \"01 Matrix\", \"titleSlug\": \"01-matrix\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Shortest Path in a Grid with Obstacles Elimination\", \"titleSlug\": \"shortest-path-in-a-grid-with-obstacles-elimination\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Amount of Time for Binary Tree to Be Infected\", \"titleSlug\": \"amount-of-time-for-binary-tree-to-be-infected\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -65333,9 +65417,9 @@ "questionFrontendId": "1731", "title": "The Number of Employees Which Report to Each Employee", "content": "
Table: Employees
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| employee_id | int |\n| name | varchar |\n| reports_to | int |\n| age | int |\n+-------------+----------+\nemployee_id is the column with unique values for this table.\nThis table contains information about the employees and the id of the manager they report to. Some employees do not report to anyone (reports_to is null). \n\n\n
\n\n
For this problem, we will consider a manager an employee who has at least 1 other employee reporting to them.
\n\nWrite a solution to report the ids and the names of all managers, the number of employees who report directly to them, and the average age of the reports rounded to the nearest integer.
\n\nReturn the result table ordered by employee_id
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+-------------+---------+------------+-----+\n| employee_id | name | reports_to | age |\n+-------------+---------+------------+-----+\n| 9 | Hercy | null | 43 |\n| 6 | Alice | 9 | 41 |\n| 4 | Bob | 9 | 36 |\n| 2 | Winston | null | 37 |\n+-------------+---------+------------+-----+\nOutput: \n+-------------+-------+---------------+-------------+\n| employee_id | name | reports_count | average_age |\n+-------------+-------+---------------+-------------+\n| 9 | Hercy | 2 | 39 |\n+-------------+-------+---------------+-------------+\nExplanation: Hercy has 2 people report directly to him, Alice and Bob. Their average age is (41+36)/2 = 38.5, which is 39 after rounding it to the nearest integer.\n\n\n
Example 2:
\n\n\nInput: \nEmployees table:\n+-------------+---------+------------+-----+ \n| employee_id | name | reports_to | age |\n|-------------|---------|------------|-----|\n| 1 | Michael | null | 45 |\n| 2 | Alice | 1 | 38 |\n| 3 | Bob | 1 | 42 |\n| 4 | Charlie | 2 | 34 |\n| 5 | David | 2 | 40 |\n| 6 | Eve | 3 | 37 |\n| 7 | Frank | null | 50 |\n| 8 | Grace | null | 48 |\n+-------------+---------+------------+-----+ \nOutput: \n+-------------+---------+---------------+-------------+\n| employee_id | name | reports_count | average_age |\n| ----------- | ------- | ------------- | ----------- |\n| 1 | Michael | 2 | 40 |\n| 2 | Alice | 2 | 37 |\n| 3 | Bob | 1 | 37 |\n+-------------+---------+---------------+-------------+\n\n\n", - "likes": 649, - "dislikes": 85, - "stats": "{\"totalAccepted\": \"224.9K\", \"totalSubmission\": \"438.5K\", \"totalAcceptedRaw\": 224923, \"totalSubmissionRaw\": 438494, \"acRate\": \"51.3%\"}", + "likes": 715, + "dislikes": 89, + "stats": "{\"totalAccepted\": \"274.7K\", \"totalSubmission\": \"526.6K\", \"totalAcceptedRaw\": 274692, \"totalSubmissionRaw\": 526631, \"acRate\": \"52.2%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -65364,9 +65448,9 @@ "questionFrontendId": "1732", "title": "Find the Highest Altitude", "content": "
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
\u200b\u200b\u200b\u200b\u200b\u200b and i + 1
for all (0 <= i < n)
. Return the highest altitude of a point.
\n
Example 1:
\n\n\nInput: gain = [-5,1,5,0,-7]\nOutput: 1\nExplanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\n\n\n
Example 2:
\n\n\nInput: gain = [-4,-3,-2,-1,4,3,2]\nOutput: 0\nExplanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n\n\n
\n
Constraints:
\n\nn == gain.length
1 <= n <= 100
-100 <= gain[i] <= 100
On a social network consisting of m
users and some friendships between users, two users can communicate with each other if they know a common language.
You are given an integer n
, an array languages
, and an array friendships
where:
n
languages numbered 1
through n
,languages[i]
is the set of languages the i\u200b\u200b\u200b\u200b\u200b\u200bth
\u200b\u200b\u200b\u200b user knows, andfriendships[i] = [u\u200b\u200b\u200b\u200b\u200b\u200bi\u200b\u200b\u200b, v\u200b\u200b\u200b\u200b\u200b\u200bi]
denotes a friendship between the users u\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bi
\u200b\u200b\u200b\u200b\u200b and vi
.You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.
\nNote that friendships are not transitive, meaning ifx
is a friend of y
and y
is a friend of z
, this doesn't guarantee that x
is a friend of z
.\n\n
Example 1:
\n\n\nInput: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\nOutput: 1\nExplanation: You can either teach user 1 the second language or user 2 the first language.\n\n\n
Example 2:
\n\n\nInput: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\nOutput: 2\nExplanation: Teach the third language to users 1 and 3, yielding two users to teach.\n\n\n
\n
Constraints:
\n\n2 <= n <= 500
languages.length == m
1 <= m <= 500
1 <= languages[i].length <= n
1 <= languages[i][j] <= n
1 <= u\u200b\u200b\u200b\u200b\u200b\u200bi < v\u200b\u200b\u200b\u200b\u200b\u200bi <= languages.length
1 <= friendships.length <= 500
(u\u200b\u200b\u200b\u200b\u200bi, v\u200b\u200b\u200b\u200b\u200b\u200bi)
are uniquelanguages[i]
contains only unique valuesThere is an integer array perm
that is a permutation of the first n
positive integers, where n
is always odd.
It was encoded into another integer array encoded
of length n - 1
, such that encoded[i] = perm[i] XOR perm[i + 1]
. For example, if perm = [1,3,2]
, then encoded = [2,1]
.
Given the encoded
array, return the original array perm
. It is guaranteed that the answer exists and is unique.
\n
Example 1:
\n\n\nInput: encoded = [3,1]\nOutput: [1,2,3]\nExplanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\n\n\n
Example 2:
\n\n\nInput: encoded = [6,5,4,6]\nOutput: [2,4,1,5,3]\n\n\n
\n
Constraints:
\n\n3 <= n < 105
n
is odd.encoded.length == n - 1
You are given a 2D integer array, queries
. For each queries[i]
, where queries[i] = [ni, ki]
, find the number of different ways you can place positive integers into an array of size ni
such that the product of the integers is ki
. As the number of ways may be too large, the answer to the ith
query is the number of ways modulo 109 + 7
.
Return an integer array answer
where answer.length == queries.length
, and answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: queries = [[2,6],[5,1],[73,660]]\nOutput: [4,1,50734910]\nExplanation: Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\n\n\n
Example 2:
\n\n\nInput: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput: [1,2,3,10,5]\n\n\n
\n
Constraints:
\n\n1 <= queries.length <= 104
1 <= ni, ki <= 104
You are given a string time
in the form of hh:mm
, where some of the digits in the string are hidden (represented by ?
).
The valid times are those inclusively between 00:00
and 23:59
.
Return the latest valid time you can get from time
by replacing the hidden digits.
\n
Example 1:
\n\n\nInput: time = "2?:?0"\nOutput: "23:50"\nExplanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\n\n\n
Example 2:
\n\n\nInput: time = "0?:3?"\nOutput: "09:39"\n\n\n
Example 3:
\n\n\nInput: time = "1?:22"\nOutput: "19:22"\n\n\n
\n
Constraints:
\n\ntime
is in the format hh:mm
.You are given two strings a
and b
that consist of lowercase letters. In one operation, you can change any character in a
or b
to any lowercase letter.
Your goal is to satisfy one of the following three conditions:
\n\na
is strictly less than every letter in b
in the alphabet.b
is strictly less than every letter in a
in the alphabet.a
and b
consist of only one distinct letter.Return the minimum number of operations needed to achieve your goal.
\n\n\n
Example 1:
\n\n\nInput: a = "aba", b = "caa"\nOutput: 2\nExplanation: Consider the best way to make each condition true:\n1) Change b to "ccc" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to "bbb" and b to "aaa" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to "aaa" and b to "aaa" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).\n\n\n
Example 2:
\n\n\nInput: a = "dabadd", b = "cda"\nOutput: 3\nExplanation: The best way is to make condition 1 true by changing b to "eee".\n\n\n
\n
Constraints:
\n\n1 <= a.length, b.length <= 105
a
and b
consist only of lowercase letters.You are given a 2D matrix
of size m x n
, consisting of non-negative integers. You are also given an integer k
.
The value of coordinate (a, b)
of the matrix is the XOR of all matrix[i][j]
where 0 <= i <= a < m
and 0 <= j <= b < n
(0-indexed).
Find the kth
largest value (1-indexed) of all the coordinates of matrix
.
\n
Example 1:
\n\n\nInput: matrix = [[5,2],[1,6]], k = 1\nOutput: 7\nExplanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.\n\n\n
Example 2:
\n\n\nInput: matrix = [[5,2],[1,6]], k = 2\nOutput: 5\nExplanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.\n\n\n
Example 3:
\n\n\nInput: matrix = [[5,2],[1,6]], k = 3\nOutput: 4\nExplanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
0 <= matrix[i][j] <= 106
1 <= k <= m * n
You have a cubic storeroom where the width, length, and height of the room are all equal to n
units. You are asked to place n
boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:
x
is placed on top of the box y
, then each side of the four vertical sides of the box y
must either be adjacent to another box or to a wall.Given an integer n
, return the minimum possible number of boxes touching the floor.
\n
Example 1:
\n\n\nInput: n = 3\nOutput: 3\nExplanation: The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\n
Example 2:
\n\n\nInput: n = 4\nOutput: 3\nExplanation: The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\n\n\n
Example 3:
\n\n\nInput: n = 10\nOutput: 6\nExplanation: The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.\n\n
\n
Constraints:
\n\n1 <= n <= 109
Table: Employees
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| emp_id | int |\n| event_day | date |\n| in_time | int |\n| out_time | int |\n+-------------+------+\n(emp_id, event_day, in_time) is the primary key (combinations of columns with unique values) of this table.\nThe table shows the employees' entries and exits in an office.\nevent_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office.\nin_time and out_time are between 1 and 1440.\nIt is guaranteed that no two events on the same day intersect in time, and in_time < out_time.\n\n\n
\n\n
Write a solution to calculate the total time in minutes spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time - in_time
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+--------+------------+---------+----------+\n| emp_id | event_day | in_time | out_time |\n+--------+------------+---------+----------+\n| 1 | 2020-11-28 | 4 | 32 |\n| 1 | 2020-11-28 | 55 | 200 |\n| 1 | 2020-12-03 | 1 | 42 |\n| 2 | 2020-11-28 | 3 | 33 |\n| 2 | 2020-12-09 | 47 | 74 |\n+--------+------------+---------+----------+\nOutput: \n+------------+--------+------------+\n| day | emp_id | total_time |\n+------------+--------+------------+\n| 2020-11-28 | 1 | 173 |\n| 2020-11-28 | 2 | 30 |\n| 2020-12-03 | 1 | 41 |\n| 2020-12-09 | 2 | 27 |\n+------------+--------+------------+\nExplanation: \nEmployee 1 has three events: two on day 2020-11-28 with a total of (32 - 4) + (200 - 55) = 173, and one on day 2020-12-03 with a total of (42 - 1) = 41.\nEmployee 2 has two events: one on day 2020-11-28 with a total of (33 - 3) = 30, and one on day 2020-12-09 with a total of (74 - 47) = 27.\n\n", - "likes": 743, - "dislikes": 22, - "stats": "{\"totalAccepted\": \"163K\", \"totalSubmission\": \"187.4K\", \"totalAcceptedRaw\": 162987, \"totalSubmissionRaw\": 187445, \"acRate\": \"87.0%\"}", + "likes": 765, + "dislikes": 23, + "stats": "{\"totalAccepted\": \"178.5K\", \"totalSubmission\": \"205.6K\", \"totalAcceptedRaw\": 178522, \"totalSubmissionRaw\": 205587, \"acRate\": \"86.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -65756,13 +65840,13 @@ "questionFrontendId": "1742", "title": "Maximum Number of Balls in a Box", "content": "
You are working in a ball factory where you have n
balls numbered from lowLimit
up to highLimit
inclusive (i.e., n == highLimit - lowLimit + 1
), and an infinite number of boxes numbered from 1
to infinity
.
Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321
will be put in the box number 3 + 2 + 1 = 6
and the ball number 10
will be put in the box number 1 + 0 = 1
.
Given two integers lowLimit
and highLimit
, return the number of balls in the box with the most balls.
\n
Example 1:
\n\n\nInput: lowLimit = 1, highLimit = 10\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.\n\n
Example 2:
\n\n\nInput: lowLimit = 5, highLimit = 15\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.\n\n\n
Example 3:
\n\n\nInput: lowLimit = 19, highLimit = 28\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.\n\n\n
\n
Constraints:
\n\n1 <= lowLimit <= highLimit <= 105
There is an integer array nums
that consists of n
unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums
.
You are given a 2D integer array adjacentPairs
of size n - 1
where each adjacentPairs[i] = [ui, vi]
indicates that the elements ui
and vi
are adjacent in nums
.
It is guaranteed that every adjacent pair of elements nums[i]
and nums[i+1]
will exist in adjacentPairs
, either as [nums[i], nums[i+1]]
or [nums[i+1], nums[i]]
. The pairs can appear in any order.
Return the original array nums
. If there are multiple solutions, return any of them.
\n
Example 1:
\n\n\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\nOutput: [1,2,3,4]\nExplanation: This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.\n\n\n
Example 2:
\n\n\nInput: adjacentPairs = [[4,-2],[1,4],[-3,1]]\nOutput: [-2,4,1,-3]\nExplanation: There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.\n\n\n
Example 3:
\n\n\nInput: adjacentPairs = [[100000,-100000]]\nOutput: [100000,-100000]\n\n\n
\n
Constraints:
\n\nnums.length == n
adjacentPairs.length == n - 1
adjacentPairs[i].length == 2
2 <= n <= 105
-105 <= nums[i], ui, vi <= 105
nums
that has adjacentPairs
as its pairs.You are given a (0-indexed) array of positive integers candiesCount
where candiesCount[i]
represents the number of candies of the ith
type you have. You are also given a 2D array queries
where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]
.
You play a game with the following rules:
\n\n0
.i
unless you have eaten all candies of type i - 1
.Construct a boolean array answer
such that answer.length == queries.length
and answer[i]
is true
if you can eat a candy of type favoriteTypei
on day favoriteDayi
without eating more than dailyCapi
candies on any day, and false
otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.
Return the constructed array answer
.
\n
Example 1:
\n\n\nInput: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]\nOutput: [true,false,true]\nExplanation:\n1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.\n2- You can eat at most 4 candies each day.\n If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.\n On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.\n3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.\n\n\n
Example 2:
\n\n\nInput: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]\nOutput: [false,true,true,false,false]\n\n\n
\n
Constraints:
\n\n1 <= candiesCount.length <= 105
1 <= candiesCount[i] <= 105
1 <= queries.length <= 105
queries[i].length == 3
0 <= favoriteTypei < candiesCount.length
0 <= favoriteDayi <= 109
1 <= dailyCapi <= 109
Given a string s
, return true
if it is possible to split the string s
into three non-empty palindromic substrings. Otherwise, return false
.\u200b\u200b\u200b\u200b\u200b
A string is said to be palindrome if it the same string when reversed.
\n\n\n
Example 1:
\n\n\nInput: s = "abcbdd"\nOutput: true\nExplanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes.\n\n\n
Example 2:
\n\n\nInput: s = "bcbddxy"\nOutput: false\nExplanation: s cannot be split into 3 palindromes.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 2000
s
\u200b\u200b\u200b\u200b\u200b\u200b consists only of lowercase English letters.You are given an integer array nums
. The unique elements of an array are the elements that appear exactly once in the array.
Return the sum of all the unique elements of nums
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,2]\nOutput: 4\nExplanation: The unique elements are [1,3], and the sum is 4.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: There are no unique elements, and the sum is 0.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 15\nExplanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given an integer array nums
. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr]
is abs(numsl + numsl+1 + ... + numsr-1 + numsr)
.
Return the maximum absolute sum of any (possibly empty) subarray of nums
.
Note that abs(x)
is defined as follows:
x
is a negative integer, then abs(x) = -x
.x
is a non-negative integer, then abs(x) = x
.\n
Example 1:
\n\n\nInput: nums = [1,-3,2,3,-4]\nOutput: 5\nExplanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [2,-5,1,-4,3,-2]\nOutput: 8\nExplanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-104 <= nums[i] <= 104
Given a string s
consisting only of characters 'a'
, 'b'
, and 'c'
. You are asked to apply the following algorithm on the string any number of times:
s
where all the characters in the prefix are equal.s
where all the characters in this suffix are equal.Return the minimum length of s
after performing the above operation any number of times (possibly zero times).
\n
Example 1:
\n\n\nInput: s = "ca"\nOutput: 2\nExplanation: You can't remove any characters, so the string stays as is.\n\n\n
Example 2:
\n\n\nInput: s = "cabaabac"\nOutput: 0\nExplanation: An optimal sequence of operations is:\n- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".\n- Take prefix = "a" and suffix = "a" and remove them, s = "baab".\n- Take prefix = "b" and suffix = "b" and remove them, s = "aa".\n- Take prefix = "a" and suffix = "a" and remove them, s = "".\n\n
Example 3:
\n\n\nInput: s = "aabccabba"\nOutput: 3\nExplanation: An optimal sequence of operations is:\n- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".\n- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
only consists of characters 'a'
, 'b'
, and 'c'
.You are given an array of events
where events[i] = [startDayi, endDayi, valuei]
. The ith
event starts at startDayi
and ends at endDayi
, and if you attend this event, you will receive a value of valuei
. You are also given an integer k
which represents the maximum number of events you can attend.
You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.
\n\nReturn the maximum sum of values that you can receive by attending events.
\n\n\n
Example 1:
\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput: 7\nExplanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n\n
Example 2:
\n\n\nInput: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput: 10\nExplanation: Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n\n
Example 3:
\n\n\nInput: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput: 9\nExplanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n\n
\n
Constraints:
\n\n1 <= k <= events.length
1 <= k * events.length <= 106
1 <= startDayi <= endDayi <= 109
1 <= valuei <= 106
Given an array nums
, return true
if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false
.
There may be duplicates in the original array.
\n\nNote: An array A
rotated by x
positions results in an array B
of the same length such that A[i] == B[(i+x) % A.length]
, where %
is the modulo operation.
\n
Example 1:
\n\n\nInput: nums = [3,4,5,1,2]\nOutput: true\nExplanation: [1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2].\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,3,4]\nOutput: false\nExplanation: There is no sorted array once rotated that can make nums.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: true\nExplanation: [1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n\n\n
\n\n
\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
Given an array nums
, return true
if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false
.
There may be duplicates in the original array.
\n\nNote: An array A
rotated by x
positions results in an array B
of the same length such that B[i] == A[(i+x) % A.length]
for every valid index i
.
\n
Example 1:
\n\n\nInput: nums = [3,4,5,1,2]\nOutput: true\nExplanation: [1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the element of value 3: [3,4,5,1,2].\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,3,4]\nOutput: false\nExplanation: There is no sorted array once rotated that can make nums.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: true\nExplanation: [1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n\n\n
\n\n
\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are playing a solitaire game with three piles of stones of sizes a
\u200b\u200b\u200b\u200b\u200b\u200b, b
,\u200b\u200b\u200b\u200b\u200b\u200b and c
\u200b\u200b\u200b\u200b\u200b\u200b 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 are no more available moves).
Given three integers a
\u200b\u200b\u200b\u200b\u200b, b
,\u200b\u200b\u200b\u200b\u200b and c
\u200b\u200b\u200b\u200b\u200b, return the maximum score you can get.
\n
Example 1:
\n\n\nInput: a = 2, b = 4, c = 6\nOutput: 6\nExplanation: The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.\n\n\n
Example 2:
\n\n\nInput: a = 4, b = 4, c = 6\nOutput: 7\nExplanation: The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.\n\n\n
Example 3:
\n\n\nInput: a = 1, b = 8, c = 8\nOutput: 8\nExplanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.\n\n\n
\n
Constraints:
\n\n1 <= a, b, c <= 105
You are given two strings word1
and word2
. You want to construct a string merge
in the following way: while either word1
or word2
are non-empty, choose one of the following options:
word1
is non-empty, append the first character in word1
to merge
and delete it from word1
.\n\n\tword1 = "abc"
and merge = "dv"
, then after choosing this operation, word1 = "bc"
and merge = "dva"
.word2
is non-empty, append the first character in word2
to merge
and delete it from word2
.\n\tword2 = "abc"
and merge = ""
, then after choosing this operation, word2 = "bc"
and merge = "a"
.Return the lexicographically largest merge
you can construct.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
. For example, "abcd"
is lexicographically larger than "abcc"
because the first position they differ is at the fourth character, and d
is greater than c
.
\n
Example 1:
\n\n\nInput: word1 = "cabaa", word2 = "bcaaa"\nOutput: "cbcabaaaaa"\nExplanation: One way to get the lexicographically largest merge is:\n- Take from word1: merge = "c", word1 = "abaa", word2 = "bcaaa"\n- Take from word2: merge = "cb", word1 = "abaa", word2 = "caaa"\n- Take from word2: merge = "cbc", word1 = "abaa", word2 = "aaa"\n- Take from word1: merge = "cbca", word1 = "baa", word2 = "aaa"\n- Take from word1: merge = "cbcab", word1 = "aa", word2 = "aaa"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.\n\n\n
Example 2:
\n\n\nInput: word1 = "abcabc", word2 = "abdcaba"\nOutput: "abdcabcabcaba"\n\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 3000
word1
and word2
consist only of lowercase English letters.You are given an integer array nums
and an integer goal
.
You want to choose a subsequence of nums
such that the sum of its elements is the closest possible to goal
. That is, if the sum of the subsequence's elements is sum
, then you want to minimize the absolute difference abs(sum - goal)
.
Return the minimum possible value of abs(sum - goal)
.
Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.
\n\n\n
Example 1:
\n\n\nInput: nums = [5,-7,3,5], goal = 6\nOutput: 0\nExplanation: Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.\n\n\n
Example 2:
\n\n\nInput: nums = [7,-9,15,-2], goal = -5\nOutput: 1\nExplanation: Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3], goal = -7\nOutput: 7\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 40
-107 <= nums[i] <= 107
-109 <= goal <= 109
For Python 3 users, the SortedList
class from the sortedcontainers
library provides an efficient way to implement an MRU (Most Recently Used) queue. Unlike a standard list, SortedList
is based on a balanced binary search tree (such as a red-black tree or B-tree), allowing for $O(\\log n)$ insertions, deletions, and indexing.
Table: Products
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| product_id | int |\n| low_fats | enum |\n| recyclable | enum |\n+-------------+---------+\nproduct_id is the primary key (column with unique values) for this table.\nlow_fats is an ENUM (category) of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.\nrecyclable is an ENUM (category) of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.\n\n
\n\n
Write a solution to find the ids of products that are both low fat and recyclable.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProducts table:\n+-------------+----------+------------+\n| product_id | low_fats | recyclable |\n+-------------+----------+------------+\n| 0 | Y | N |\n| 1 | Y | Y |\n| 2 | N | Y |\n| 3 | Y | Y |\n| 4 | N | N |\n+-------------+----------+------------+\nOutput: \n+-------------+\n| product_id |\n+-------------+\n| 1 |\n| 3 |\n+-------------+\nExplanation: Only products 1 and 3 are both low fat and recyclable.\n\n", - "likes": 2682, - "dislikes": 119, - "stats": "{\"totalAccepted\": \"1.6M\", \"totalSubmission\": \"1.8M\", \"totalAcceptedRaw\": 1621264, \"totalSubmissionRaw\": 1813669, \"acRate\": \"89.4%\"}", + "likes": 2865, + "dislikes": 124, + "stats": "{\"totalAccepted\": \"1.9M\", \"totalSubmission\": \"2.1M\", \"totalAcceptedRaw\": 1888705, \"totalSubmissionRaw\": 2115672, \"acRate\": \"89.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -66359,9 +66449,9 @@ "questionFrontendId": "1758", "title": "Minimum Changes To Make Alternating Binary String", "content": "
You are given a string s
consisting only of the characters '0'
and '1'
. In one operation, you can change any '0'
to '1'
or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string "010"
is alternating, while the string "0100"
is not.
Return the minimum number of operations needed to make s
alternating.
\n
Example 1:
\n\n\nInput: s = "0100"\nOutput: 1\nExplanation: If you change the last character to '1', s will be "0101", which is alternating.\n\n\n
Example 2:
\n\n\nInput: s = "10"\nOutput: 0\nExplanation: s is already alternating.\n\n\n
Example 3:
\n\n\nInput: s = "1111"\nOutput: 2\nExplanation: You need two operations to reach "0101" or "1010".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s[i]
is either '0'
or '1'
.Given a string s
, return the number of homogenous substrings of s
. Since the answer may be too large, return it modulo 109 + 7
.
A string is homogenous if all the characters of the string are the same.
\n\nA substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "abbcccaa"\nOutput: 13\nExplanation: The homogenous substrings are listed as below:\n"a" appears 3 times.\n"aa" appears 1 time.\n"b" appears 2 times.\n"bb" appears 1 time.\n"c" appears 3 times.\n"cc" appears 2 times.\n"ccc" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\n\n
Example 2:
\n\n\nInput: s = "xy"\nOutput: 2\nExplanation: The homogenous substrings are "x" and "y".\n\n
Example 3:
\n\n\nInput: s = "zzzzz"\nOutput: 15\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase letters.You are given an integer array nums
where the ith
bag contains nums[i]
balls. You are also given an integer maxOperations
.
You can perform the following operation at most maxOperations
times:
5
balls can become two new bags of 1
and 4
balls, or two new bags of 2
and 3
balls.Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.
\n\nReturn the minimum possible penalty after performing the operations.
\n\n\n
Example 1:
\n\n\nInput: nums = [9], maxOperations = 2\nOutput: 3\nExplanation: \n- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,8,2], maxOperations = 4\nOutput: 2\nExplanation:\n- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= maxOperations, nums[i] <= 109
You are given an undirected graph. You are given an integer n
which is the number of nodes in the graph and an array edges
, where each edges[i] = [ui, vi]
indicates that there is an undirected edge between ui
and vi
.
A connected trio is a set of three nodes where there is an edge between every pair of them.
\n\nThe degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.
\n\nReturn the minimum degree of a connected trio in the graph, or -1
if the graph has no connected trios.
\n
Example 1:
\n\nInput: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput: 3\nExplanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n\n\n
Example 2:
\n\nInput: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput: 0\nExplanation: There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.\n\n\n
\n
Constraints:
\n\n2 <= n <= 400
edges[i].length == 2
1 <= edges.length <= n * (n-1) / 2
1 <= ui, vi <= n
ui != vi
A string s
is nice if, for every letter of the alphabet that s
contains, it appears both in uppercase and lowercase. For example, "abABB"
is nice because 'A'
and 'a'
appear, and 'B'
and 'b'
appear. However, "abA"
is not because 'b'
appears, but 'B'
does not.
Given a string s
, return the longest substring of s
that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.
\n
Example 1:
\n\n\nInput: s = "YazaAay"\nOutput: "aAa"\nExplanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n"aAa" is the longest nice substring.\n\n\n
Example 2:
\n\n\nInput: s = "Bb"\nOutput: "Bb"\nExplanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n\n\n
Example 3:
\n\n\nInput: s = "c"\nOutput: ""\nExplanation: There are no nice substrings.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of uppercase and lowercase English letters.You are given a 2D integer array groups
of length n
. You are also given an integer array nums
.
You are asked if you can choose n
disjoint subarrays from the array nums
such that the ith
subarray is equal to groups[i]
(0-indexed), and if i > 0
, the (i-1)th
subarray appears before the ith
subarray in nums
(i.e. the subarrays must be in the same order as groups
).
Return true
if you can do this task, and false
otherwise.
Note that the subarrays are disjoint if and only if there is no index k
such that nums[k]
belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
\n
Example 1:
\n\n\nInput: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput: true\nExplanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.\n\n\n
Example 2:
\n\n\nInput: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput: false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].\n\n\n
Example 3:
\n\n\nInput: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput: false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).\n\n\n
\n
Constraints:
\n\ngroups.length == n
1 <= n <= 103
1 <= groups[i].length, sum(groups[i].length) <= 103
1 <= nums.length <= 103
-107 <= groups[i][j], nums[k] <= 107
You are given an integer matrix isWater
of size m x n
that represents a map of land and water cells.
isWater[i][j] == 0
, cell (i, j)
is a land cell.isWater[i][j] == 1
, cell (i, j)
is a water cell.You must assign each cell a height in a way that follows these rules:
\n\n0
.1
. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).Find an assignment of heights such that the maximum height in the matrix is maximized.
\n\nReturn an integer matrix height
of size m x n
where height[i][j]
is cell (i, j)
's height. If there are multiple solutions, return any of them.
\n
Example 1:
\n\n\nInput: isWater = [[0,1],[0,0]]\nOutput: [[1,0],[2,1]]\nExplanation: The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.\n\n\n
Example 2:
\n\n\nInput: isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput: [[1,1,0],[0,1,1],[1,2,2]]\nExplanation: A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n\n\n
\n
Constraints:
\n\nm == isWater.length
n == isWater[i].length
1 <= m, n <= 1000
isWater[i][j]
is 0
or 1
.\n
Note: This question is the same as 542: https://leetcode.com/problems/01-matrix/
\n", - "likes": 1423, - "dislikes": 101, - "stats": "{\"totalAccepted\": \"137.3K\", \"totalSubmission\": \"182.9K\", \"totalAcceptedRaw\": 137295, \"totalSubmissionRaw\": 182865, \"acRate\": \"75.1%\"}", + "likes": 1470, + "dislikes": 107, + "stats": "{\"totalAccepted\": \"144K\", \"totalSubmission\": \"191.7K\", \"totalAcceptedRaw\": 144007, \"totalSubmissionRaw\": 191742, \"acRate\": \"75.1%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -66661,9 +66751,9 @@ "questionFrontendId": "1766", "title": "Tree of Coprimes", "content": "There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n
nodes numbered from 0
to n - 1
and exactly n - 1
edges. Each node has a value associated with it, and the root of the tree is node 0
.
To represent this tree, you are given an integer array nums
and a 2D array edges
. Each nums[i]
represents the ith
node's value, and each edges[j] = [uj, vj]
represents an edge between nodes uj
and vj
in the tree.
Two values x
and y
are coprime if gcd(x, y) == 1
where gcd(x, y)
is the greatest common divisor of x
and y
.
An ancestor of a node i
is any other node on the shortest path from node i
to the root. A node is not considered an ancestor of itself.
Return an array ans
of size n
, where ans[i]
is the closest ancestor to node i
such that nums[i]
and nums[ans[i]]
are coprime, or -1
if there is no such ancestor.
\n
Example 1:
\n\n\nInput: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput: [-1,0,0,1]\nExplanation: In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.\n\n\n
Example 2:
\n\n\nInput: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput: [-1,0,-1,0,0,0,-1]\n\n\n
\n
Constraints:
\n\nnums.length == n
1 <= nums[i] <= 50
1 <= n <= 105
edges.length == n - 1
edges[j].length == 2
0 <= uj, vj < n
uj != vj
You are given two strings word1
and word2
. Merge the strings by adding letters in alternating order, starting with word1
. If a string is longer than the other, append the additional letters onto the end of the merged string.
Return the merged string.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: word1 = "abc", word2 = "pqr"\r\nOutput: "apbqcr"\r\nExplanation: The merged string will be merged as so:\r\nword1: a b c\r\nword2: p q r\r\nmerged: a p b q c r\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: word1 = "ab", word2 = "pqrs"\r\nOutput: "apbqrs"\r\nExplanation: Notice that as word2 is longer, "rs" is appended to the end.\r\nword1: a b \r\nword2: p q r s\r\nmerged: a p b q r s\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: word1 = "abcd", word2 = "pq"\r\nOutput: "apbqcd"\r\nExplanation: Notice that as word1 is longer, "cd" is appended to the end.\r\nword1: a b c d\r\nword2: p q \r\nmerged: a p b q c d\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= word1.length, word2.length <= 100
word1
and word2
consist of lowercase English letters.You have n
boxes. You are given a binary string boxes
of length n
, where boxes[i]
is '0'
if the ith
box is empty, and '1'
if it contains one ball.
In one operation, you can move one ball from a box to an adjacent box. Box i
is adjacent to box j
if abs(i - j) == 1
. Note that after doing so, there may be more than one ball in some boxes.
Return an array answer
of size n
, where answer[i]
is the minimum number of operations needed to move all the balls to the ith
box.
Each answer[i]
is calculated considering the initial state of the boxes.
\n
Example 1:
\n\n\nInput: boxes = "110"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n\n\n
Example 2:
\n\n\nInput: boxes = "001011"\nOutput: [11,8,5,4,3,4]\n\n
\n
Constraints:
\n\nn == boxes.length
1 <= n <= 2000
boxes[i]
is either '0'
or '1'
.You are given two 0-indexed integer arrays nums
and multipliers
of size n
and m
respectively, where n >= m
.
You begin with a score of 0
. You want to perform exactly m
operations. On the ith
operation (0-indexed) you will:
x
from either the start or the end of the array nums
.multipliers[i] * x
to your score.\n multipliers[0]
corresponds to the first operation, multipliers[1]
to the second operation, and so on.x
from nums
.Return the maximum score after performing m
operations.
\n
Example 1:
\n\n\nInput: nums = [1,2,3], multipliers = [3,2,1]\nOutput: 14\nExplanation: An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.\n\n
Example 2:
\n\n\nInput: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\nOutput: 102\nExplanation: An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.\n\n\n
\n
Constraints:
\n\nn == nums.length
m == multipliers.length
1 <= m <= 300
m <= n <= 105
-1000 <= nums[i], multipliers[i] <= 1000
You are given two strings, word1
and word2
. You want to construct a string in the following manner:
subsequence1
from word1
.subsequence2
from word2
.subsequence1 + subsequence2
, to make the string.Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0
.
A subsequence of a string s
is a string that can be made by deleting some (possibly none) characters from s
without changing the order of the remaining characters.
A palindrome is a string that reads the same forward as well as backward.
\n\n\n
Example 1:
\n\n\nInput: word1 = "cacb", word2 = "cbba"\nOutput: 5\nExplanation: Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome.\n\n
Example 2:
\n\n\nInput: word1 = "ab", word2 = "ab"\nOutput: 3\nExplanation: Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome.\n\n
Example 3:
\n\n\nInput: word1 = "aa", word2 = "bb"\nOutput: 0\nExplanation: You cannot construct a palindrome from the described method, so return 0.\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 1000
word1
and word2
consist of lowercase English letters.You are given an array items
, where each items[i] = [typei, colori, namei]
describes the type, color, and name of the ith
item. You are also given a rule represented by two strings, ruleKey
and ruleValue
.
The ith
item is said to match the rule if one of the following is true:
ruleKey == "type"
and ruleValue == typei
.ruleKey == "color"
and ruleValue == colori
.ruleKey == "name"
and ruleValue == namei
.Return the number of items that match the given rule.
\n\n\n
Example 1:
\n\n\nInput: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"\nOutput: 1\nExplanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].\n\n\n
Example 2:
\n\n\nInput: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"\nOutput: 2\nExplanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.\n\n
\n
Constraints:
\n\n1 <= items.length <= 104
1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10
ruleKey
is equal to either "type"
, "color"
, or "name"
.You would like to make dessert and are preparing to buy the ingredients. You have n
ice cream base flavors and m
types of toppings to choose from. You must follow these rules when making your dessert:
You are given three inputs:
\n\nbaseCosts
, an integer array of length n
, where each baseCosts[i]
represents the price of the ith
ice cream base flavor.toppingCosts
, an integer array of length m
, where each toppingCosts[i]
is the price of one of the ith
topping.target
, an integer representing your target price for dessert.You want to make a dessert with a total cost as close to target
as possible.
Return the closest possible cost of the dessert to target
. If there are multiple, return the lower one.
\n
Example 1:
\n\n\nInput: baseCosts = [1,7], toppingCosts = [3,4], target = 10\nOutput: 10\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.\n\n\n
Example 2:
\n\n\nInput: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\nOutput: 17\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.\n\n\n
Example 3:
\n\n\nInput: baseCosts = [3,10], toppingCosts = [2,5], target = 9\nOutput: 8\nExplanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.\n\n\n
\n
Constraints:
\n\nn == baseCosts.length
m == toppingCosts.length
1 <= n, m <= 10
1 <= baseCosts[i], toppingCosts[i] <= 104
1 <= target <= 104
You are given two arrays of integers nums1
and nums2
, possibly of different lengths. The values in the arrays are between 1
and 6
, inclusive.
In one operation, you can change any integer's value in any of the arrays to any value between 1
and 6
, inclusive.
Return the minimum number of operations required to make the sum of values in nums1
equal to the sum of values in nums2
. Return -1
\u200b\u200b\u200b\u200b\u200b if it is not possible to make the sum of the two arrays equal.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput: -1\nExplanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\n\n\n
Example 3:
\n\n\nInput: nums1 = [6,6], nums2 = [1]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[i] <= 6
There are n
cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars
of length n
, where cars[i] = [positioni, speedi]
represents:
positioni
is the distance between the ith
car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1
.speedi
is the initial speed of the ith
car in meters per second.For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.
\n\nReturn an array answer
, where answer[i]
is the time, in seconds, at which the ith
car collides with the next car, or -1
if the car does not collide with the next car. Answers within 10-5
of the actual answers are accepted.
\n
Example 1:
\n\n\nInput: cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput: [1.00000,-1.00000,3.00000,-1.00000]\nExplanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n\n\n
Example 2:
\n\n\nInput: cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput: [2.00000,1.00000,1.50000,-1.00000]\n\n\n
\n
Constraints:
\n\n1 <= cars.length <= 105
1 <= positioni, speedi <= 106
positioni < positioni+1
You are given two integers, x
and y
, which represent your current location on a Cartesian grid: (x, y)
. You are also given an array points
where each points[i] = [ai, bi]
represents that a point exists at (ai, bi)
. A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.
Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1
.
The Manhattan distance between two points (x1, y1)
and (x2, y2)
is abs(x1 - x2) + abs(y1 - y2)
.
\n
Example 1:
\n\n\nInput: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\nOutput: 2\nExplanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.\n\n
Example 2:
\n\n\nInput: x = 3, y = 4, points = [[3,4]]\nOutput: 0\nExplanation: The answer is allowed to be on the same location as your current location.\n\n
Example 3:
\n\n\nInput: x = 3, y = 4, points = [[2,3]]\nOutput: -1\nExplanation: There are no valid points.\n\n
\n
Constraints:
\n\n1 <= points.length <= 104
points[i].length == 2
1 <= x, y, ai, bi <= 104
Given an integer n
, return true
if it is possible to represent n
as the sum of distinct powers of three. Otherwise, return false
.
An integer y
is a power of three if there exists an integer x
such that y == 3x
.
\n
Example 1:
\n\n\nInput: n = 12\nOutput: true\nExplanation: 12 = 31 + 32\n\n\n
Example 2:
\n\n\nInput: n = 91\nOutput: true\nExplanation: 91 = 30 + 32 + 34\n\n\n
Example 3:
\n\n\nInput: n = 21\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= n <= 107
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.
\n\n"abaacc"
is 3 - 1 = 2
.Given a string s
, return the sum of beauty of all of its substrings.
\n
Example 1:
\n\n\nInput: s = "aabcb"\nOutput: 5\nExplanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.\n\n
Example 2:
\n\n\nInput: s = "aabcbaa"\nOutput: 17\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of only lowercase English letters.You are given an undirected graph defined by an integer n
, the number of nodes, and a 2D integer array edges
, the edges in the graph, where edges[i] = [ui, vi]
indicates that there is an undirected edge between ui
and vi
. You are also given an integer array queries
.
Let incident(a, b)
be defined as the number of edges that are connected to either node a
or b
.
The answer to the jth
query is the number of pairs of nodes (a, b)
that satisfy both of the following conditions:
a < b
incident(a, b) > queries[j]
Return an array answers
such that answers.length == queries.length
and answers[j]
is the answer of the jth
query.
Note that there can be multiple edges between the same two nodes.
\n\n\n
Example 1:
\n\nInput: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput: [6,5]\nExplanation: The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\n\n\n
Example 2:
\n\n\nInput: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput: [10,10,9,8,6]\n\n\n
\n
Constraints:
\n\n2 <= n <= 2 * 104
1 <= edges.length <= 105
1 <= ui, vi <= n
ui != vi
1 <= queries.length <= 20
0 <= queries[j] < edges.length
Given a binary string s
\u200b\u200b\u200b\u200b\u200bwithout leading zeros, return true
\u200b\u200b\u200b if s
contains at most one contiguous segment of ones. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: s = "1001"\nOutput: false\nExplanation: The ones do not form a contiguous segment.\n\n\n
Example 2:
\n\n\nInput: s = "110"\nOutput: true\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s[i]
\u200b\u200b\u200b\u200b is either '0'
or '1'
.s[0]
is '1'
.You are given an integer array nums
and two integers limit
and goal
. The array nums
has an interesting property that abs(nums[i]) <= limit
.
Return the minimum number of elements you need to add to make the sum of the array equal to goal
. The array must maintain its property that abs(nums[i]) <= limit
.
Note that abs(x)
equals x
if x >= 0
, and -x
otherwise.
\n
Example 1:
\n\n\nInput: nums = [1,-1,1], limit = 3, goal = -4\nOutput: 2\nExplanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.\n\n\n
Example 2:
\n\n\nInput: nums = [1,-10,9,1], limit = 100, goal = 0\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= limit <= 106
-limit <= nums[i] <= limit
-109 <= goal <= 109
There is an undirected weighted connected graph. You are given a positive integer n
which denotes that the graph has n
nodes labeled from 1
to n
, and an array edges
where each edges[i] = [ui, vi, weighti]
denotes that there is an edge between nodes ui
and vi
with weight equal to weighti
.
A path from node start
to node end
is a sequence of nodes [z0, z1, z2, ..., zk]
such that z0 = start
and zk = end
and there is an edge between zi
and zi+1
where 0 <= i <= k-1
.
The distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x)
denote the shortest distance of a path between node n
and node x
. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1)
where 0 <= i <= k-1
.
Return the number of restricted paths from node 1
to node n
. Since that number may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput: 3\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue.
The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5\n
\n\nExample 2:
\n\nInput: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput: 1\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue.
The only restricted path is 1 --> 3 --> 7.\n
\n\n\n
Constraints:
\n\n1 <= n <= 2 * 104
n - 1 <= edges.length <= 4 * 104
edges[i].length == 3
1 <= ui, vi <= n
ui != vi
1 <= weighti <= 105
You are given an array nums
\u200b\u200b\u200b and an integer k
\u200b\u200b\u200b\u200b\u200b. The XOR of a segment [left, right]
where left <= right
is the XOR
of all the elements with indices between left
and right
, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right]
.
Return the minimum number of elements to change in the array such that the XOR
of all segments of size k
\u200b\u200b\u200b\u200b\u200b\u200b is equal to zero.
\n
Example 1:
\n\n\nInput: nums = [1,2,0,3,0], k = 1\nOutput: 3\nExplanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n\n\n
Example 2:
\n\n\nInput: nums = [3,4,5,2,1,7,3,4,7], k = 3\nOutput: 3\nExplanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,4,1,2,5,1,2,6], k = 3\nOutput: 3\nExplanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 2000
\u200b\u200b\u200b\u200b\u200b\u200b0 <= nums[i] < 210
Table: Employee
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| employee_id | int |\n| department_id | int |\n| primary_flag | varchar |\n+---------------+---------+\n(employee_id, department_id) is the primary key (combination of columns with unique values) for this table.\nemployee_id is the id of the employee.\ndepartment_id is the id of the department to which the employee belongs.\nprimary_flag is an ENUM (category) of type ('Y', 'N'). If the flag is 'Y', the department is the primary department for the employee. If the flag is 'N', the department is not the primary.\n\n\n
\n\n
Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is 'N'
.
Write a solution to report all the employees with their primary department. For employees who belong to one department, report their only department.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployee table:\n+-------------+---------------+--------------+\n| employee_id | department_id | primary_flag |\n+-------------+---------------+--------------+\n| 1 | 1 | N |\n| 2 | 1 | Y |\n| 2 | 2 | N |\n| 3 | 3 | N |\n| 4 | 2 | N |\n| 4 | 3 | Y |\n| 4 | 4 | N |\n+-------------+---------------+--------------+\nOutput: \n+-------------+---------------+\n| employee_id | department_id |\n+-------------+---------------+\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 3 |\n| 4 | 3 |\n+-------------+---------------+\nExplanation: \n- The Primary department for employee 1 is 1.\n- The Primary department for employee 2 is 1.\n- The Primary department for employee 3 is 3.\n- The Primary department for employee 4 is 3.\n\n", - "likes": 611, - "dislikes": 238, - "stats": "{\"totalAccepted\": \"204.6K\", \"totalSubmission\": \"294.3K\", \"totalAcceptedRaw\": 204616, \"totalSubmissionRaw\": 294257, \"acRate\": \"69.5%\"}", + "likes": 678, + "dislikes": 246, + "stats": "{\"totalAccepted\": \"252.3K\", \"totalSubmission\": \"352.2K\", \"totalAcceptedRaw\": 252302, \"totalSubmissionRaw\": 352237, \"acRate\": \"71.6%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -67537,9 +67633,9 @@ "questionFrontendId": "1790", "title": "Check if One String Swap Can Make Strings Equal", "content": "
You are given two strings s1
and s2
of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true
if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: s1 = "bank", s2 = "kanb"\nOutput: true\nExplanation: For example, swap the first character with the last character of s2 to make "bank".\n\n\n
Example 2:
\n\n\nInput: s1 = "attack", s2 = "defend"\nOutput: false\nExplanation: It is impossible to make them equal with one string swap.\n\n\n
Example 3:
\n\n\nInput: s1 = "kelb", s2 = "kelb"\nOutput: true\nExplanation: The two strings are already equal, so no string swap operation is required.\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 100
s1.length == s2.length
s1
and s2
consist of only lowercase English letters.There is an undirected star graph consisting of n
nodes labeled from 1
to n
. A star graph is a graph where there is one center node and exactly n - 1
edges that connect the center node with every other node.
You are given a 2D integer array edges
where each edges[i] = [ui, vi]
indicates that there is an edge between the nodes ui
and vi
. Return the center of the given star graph.
\n
Example 1:
\n\nInput: edges = [[1,2],[2,3],[4,2]]\nOutput: 2\nExplanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.\n\n\n
Example 2:
\n\n\nInput: edges = [[1,2],[5,1],[1,3],[1,4]]\nOutput: 1\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
edges
represent a valid star graph.There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes
, where classes[i] = [passi, totali]
. You know beforehand that in the ith
class, there are totali
total students, but only passi
number of students will pass the exam.
You are also given an integer extraStudents
. There are another extraStudents
brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents
students to a class in a way that maximizes the average pass ratio across all the classes.
The pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.
\n\nReturn the maximum possible average pass ratio after assigning the extraStudents
students. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: classes = [[1,2],[3,5],[2,2]], extraStudents
= 2\nOutput: 0.78333\nExplanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\n
\n\nExample 2:
\n\n\nInput: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents
= 4\nOutput: 0.53485\n
\n\n\n
Constraints:
\n\n1 <= classes.length <= 105
classes[i].length == 2
1 <= passi <= totali <= 105
1 <= extraStudents <= 105
You are given an array of integers nums
(0-indexed) and an integer k
.
The score of a subarray (i, j)
is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)
. A good subarray is a subarray where i <= k <= j
.
Return the maximum possible score of a good subarray.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nExplanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n\n\n
Example 2:
\n\n\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\nExplanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 2 * 104
0 <= k < nums.length
Table: Products
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| product_id | int |\n| store1 | int |\n| store2 | int |\n| store3 | int |\n+-------------+---------+\nproduct_id is the primary key (column with unique values) for this table.\nEach row in this table indicates the product's price in 3 different stores: store1, store2, and store3.\nIf the product is not available in a store, the price will be null in that store's column.\n\n\n
\n\n
Write a solution to rearrange the Products
table so that each row has (product_id, store, price)
. If a product is not available in a store, do not include a row with that product_id
and store
combination in the result table.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nProducts table:\n+------------+--------+--------+--------+\n| product_id | store1 | store2 | store3 |\n+------------+--------+--------+--------+\n| 0 | 95 | 100 | 105 |\n| 1 | 70 | null | 80 |\n+------------+--------+--------+--------+\nOutput: \n+------------+--------+-------+\n| product_id | store | price |\n+------------+--------+-------+\n| 0 | store1 | 95 |\n| 0 | store2 | 100 |\n| 0 | store3 | 105 |\n| 1 | store1 | 70 |\n| 1 | store3 | 80 |\n+------------+--------+-------+\nExplanation: \nProduct 0 is available in all three stores with prices 95, 100, and 105 respectively.\nProduct 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.\n\n", - "likes": 892, - "dislikes": 57, - "stats": "{\"totalAccepted\": \"152.8K\", \"totalSubmission\": \"178.7K\", \"totalAcceptedRaw\": 152819, \"totalSubmissionRaw\": 178657, \"acRate\": \"85.5%\"}", + "likes": 914, + "dislikes": 60, + "stats": "{\"totalAccepted\": \"166K\", \"totalSubmission\": \"193.9K\", \"totalAcceptedRaw\": 166044, \"totalSubmissionRaw\": 193913, \"acRate\": \"85.6%\"}", "similarQuestions": "[{\"title\": \"Product's Price for Each Store\", \"titleSlug\": \"products-price-for-each-store\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Dynamic Unpivoting of a Table\", \"titleSlug\": \"dynamic-unpivoting-of-a-table\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -67768,9 +67864,9 @@ "questionFrontendId": "1796", "title": "Second Largest Digit in a String", "content": "
Given an alphanumeric string s
, return the second largest numerical digit that appears in s
, or -1
if it does not exist.
An alphanumeric string is a string consisting of lowercase English letters and digits.
\n\n\n
Example 1:
\n\n\nInput: s = "dfa12321afd"\nOutput: 2\nExplanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\n\n\n
Example 2:
\n\n\nInput: s = "abc1111"\nOutput: -1\nExplanation: The digits that appear in s are [1]. There is no second largest digit. \n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
s
consists of only lowercase English letters and digits.There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive
seconds after the currentTime
. If the token is renewed, the expiry time will be extended to expire timeToLive
seconds after the (potentially different) currentTime
.
Implement the AuthenticationManager
class:
AuthenticationManager(int timeToLive)
constructs the AuthenticationManager
and sets the timeToLive
.generate(string tokenId, int currentTime)
generates a new token with the given tokenId
at the given currentTime
in seconds.renew(string tokenId, int currentTime)
renews the unexpired token with the given tokenId
at the given currentTime
in seconds. If there are no unexpired tokens with the given tokenId
, the request is ignored, and nothing happens.countUnexpiredTokens(int currentTime)
returns the number of unexpired tokens at the given currentTime.Note that if a token expires at time t
, and another action happens on time t
(renew
or countUnexpiredTokens
), the expiration takes place before the other actions.
\n
Example 1:
\n\nInput\n["AuthenticationManager", "\n\nrenew
", "generate", "countUnexpiredTokens
", "generate", "renew
", "renew
", "countUnexpiredTokens
"]\n[[5], ["aaa", 1], ["aaa", 2], [6], ["bbb", 7], ["aaa", 8], ["bbb", 10], [15]]\nOutput\n[null, null, null, 1, null, null, null, 0]\n\nExplanation\nAuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager withtimeToLive
= 5 seconds.\nauthenticationManager.renew
("aaa", 1); // No token exists with tokenId "aaa" at time 1, so nothing happens.\nauthenticationManager.generate("aaa", 2); // Generates a new token with tokenId "aaa" at time 2.\nauthenticationManager.countUnexpiredTokens
(6); // The token with tokenId "aaa" is the only unexpired one at time 6, so return 1.\nauthenticationManager.generate("bbb", 7); // Generates a new token with tokenId "bbb" at time 7.\nauthenticationManager.renew
("aaa", 8); // The token with tokenId "aaa" expired at time 7, and 8 >= 7, so at time 8 therenew
request is ignored, and nothing happens.\nauthenticationManager.renew
("bbb", 10); // The token with tokenId "bbb" is unexpired at time 10, so therenew
request is fulfilled and now the token will expire at time 15.\nauthenticationManager.countUnexpiredTokens
(15); // The token with tokenId "bbb" expires at time 15, and the token with tokenId "aaa" expired at time 7, so currently no token is unexpired, so return 0.\n
\n
Constraints:
\n\n1 <= timeToLive <= 108
1 <= currentTime <= 108
1 <= tokenId.length <= 5
tokenId
consists only of lowercase letters.generate
will contain unique values of tokenId
.currentTime
across all the function calls will be strictly increasing.2000
calls will be made to all functions combined.You are given an integer array coins
of length n
which represents the n
coins that you own. The value of the ith
coin is coins[i]
. You can make some value x
if you can choose some of your n
coins such that their values sum up to x
.
Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0
.
Note that you may have multiple coins of the same value.
\n\n\n
Example 1:
\n\n\nInput: coins = [1,3]\nOutput: 2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.\n\n
Example 2:
\n\n\nInput: coins = [1,1,1,4]\nOutput: 8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.\n\n
Example 3:
\n\n\nInput: coins = [1,4,10,3,1]\nOutput: 20\n\n
\n
Constraints:
\n\ncoins.length == n
1 <= n <= 4 * 104
1 <= coins[i] <= 4 * 104
You are given nums
, an array of positive integers of size 2 * n
. You must perform n
operations on this array.
In the ith
operation (1-indexed), you will:
x
and y
.i * gcd(x, y)
.x
and y
from nums
.Return the maximum score you can receive after performing n
operations.
The function gcd(x, y)
is the greatest common divisor of x
and y
.
\n
Example 1:
\n\n\nInput: nums = [1,2]\nOutput: 1\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1\n\n\n
Example 2:
\n\n\nInput: nums = [3,4,6,8]\nOutput: 11\nExplanation: The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5,6]\nOutput: 14\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n\n\n
\n
Constraints:
\n\n1 <= n <= 7
nums.length == 2 * n
1 <= nums[i] <= 106
Given an array of positive integers nums
, return the maximum possible sum of an ascending subarray in nums
.
A subarray is defined as a contiguous sequence of numbers in an array.
\n\nA subarray [numsl, numsl+1, ..., numsr-1, numsr]
is ascending if for all i
where l <= i < r
, numsi < numsi+1
. Note that a subarray of size 1
is ascending.
\n
Example 1:
\n\n\nInput: nums = [10,20,30,5,10,50]\nOutput: 65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n\n\n
Example 2:
\n\n\nInput: nums = [10,20,30,40,50]\nOutput: 150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n\n\n
Example 3:
\n\n\nInput: nums = [12,17,15,13,10,11,12]\nOutput: 33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
Given an array of positive integers nums
, return the maximum possible sum of an strictly increasing subarray in nums
.
A subarray is defined as a contiguous sequence of numbers in an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [10,20,30,5,10,50]\nOutput: 65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n\n\n
Example 2:
\n\n\nInput: nums = [10,20,30,40,50]\nOutput: 150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n\n\n
Example 3:
\n\n\nInput: nums = [12,17,15,13,10,11,12]\nOutput: 33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given a 2D integer array orders
, where each orders[i] = [pricei, amounti, orderTypei]
denotes that amounti
orders have been placed of type orderTypei
at the price pricei
. The orderTypei
is:
0
if it is a batch of buy
orders, or1
if it is a batch of sell
orders.Note that orders[i]
represents a batch of amounti
independent orders with the same price and order type. All orders represented by orders[i]
will be placed before all orders represented by orders[i+1]
for all valid i
.
There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:
\r\n\r\nbuy
order, you look at the sell
order with the smallest price in the backlog. If that sell
order's price is smaller than or equal to the current buy
order's price, they will match and be executed, and that sell
order will be removed from the backlog. Else, the buy
order is added to the backlog.sell
order, you look at the buy
order with the largest price in the backlog. If that buy
order's price is larger than or equal to the current sell
order's price, they will match and be executed, and that buy
order will be removed from the backlog. Else, the sell
order is added to the backlog.Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7
.
\r\n
Example 1:
\r\n\r\nInput: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\r\nOutput: 6\r\nExplanation: Here is what happens with the orders:\r\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\r\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\r\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\r\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.\r\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.\r\n\r\n\r\n
Example 2:
\r\n\r\nInput: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\r\nOutput: 999999984\r\nExplanation: Here is what happens with the orders:\r\n- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.\r\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\r\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\r\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\r\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= orders.length <= 105
orders[i].length == 3
1 <= pricei, amounti <= 109
orderTypei
is either 0
or 1
.You are given three positive integers: n
, index
, and maxSum
. You want to construct an array nums
(0-indexed) that satisfies the following conditions:
nums.length == n
nums[i]
is a positive integer where 0 <= i < n
.abs(nums[i] - nums[i+1]) <= 1
where 0 <= i < n-1
.nums
does not exceed maxSum
.nums[index]
is maximized.Return nums[index]
of the constructed array.
Note that abs(x)
equals x
if x >= 0
, and -x
otherwise.
\n
Example 1:
\n\n\nInput: n = 4, index = 2, maxSum = 6\nOutput: 2\nExplanation: nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].\n\n\n
Example 2:
\n\n\nInput: n = 6, index = 1, maxSum = 10\nOutput: 3\n\n\n
\n
Constraints:
\n\n1 <= n <= maxSum <= 109
0 <= index < n
Given a (0-indexed) integer array nums
and two integers low
and high
, return the number of nice pairs.
A nice pair is a pair (i, j)
where 0 <= i < j < nums.length
and low <= (nums[i] XOR nums[j]) <= high
.
\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [1,4,2,7], low = 2, high = 6\r\nOutput: 6\r\nExplanation: All nice pairs (i, j) are as follows:\r\n - (0, 1): nums[0] XOR nums[1] = 5 \r\n - (0, 2): nums[0] XOR nums[2] = 3\r\n - (0, 3): nums[0] XOR nums[3] = 6\r\n - (1, 2): nums[1] XOR nums[2] = 6\r\n - (1, 3): nums[1] XOR nums[3] = 3\r\n - (2, 3): nums[2] XOR nums[3] = 5\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [9,8,4,2,1], low = 5, high = 14\r\nOutput: 8\r\nExplanation: All nice pairs (i, j) are as follows:\r\n\u200b\u200b\u200b\u200b\u200b - (0, 2): nums[0] XOR nums[2] = 13\r\n - (0, 3): nums[0] XOR nums[3] = 11\r\n - (0, 4): nums[0] XOR nums[4] = 8\r\n - (1, 2): nums[1] XOR nums[2] = 12\r\n - (1, 3): nums[1] XOR nums[3] = 10\r\n - (1, 4): nums[1] XOR nums[4] = 9\r\n - (2, 3): nums[2] XOR nums[3] = 6\r\n - (2, 4): nums[2] XOR nums[4] = 5\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= nums.length <= 2 * 104
1 <= nums[i] <= 2 * 104
1 <= low <= high <= 2 * 104
You are given a string word
that consists of digits and lowercase English letters.
You will replace every non-digit character with a space. For example, "a123bc34d8ef34"
will become " 123 34 8 34"
. Notice that you are left with some integers that are separated by at least one space: "123"
, "34"
, "8"
, and "34"
.
Return the number of different integers after performing the replacement operations on word
.
Two integers are considered different if their decimal representations without any leading zeros are different.
\n\n\n
Example 1:
\n\n\nInput: word = "a123bc34d8ef34"\nOutput: 3\nExplanation: The three different integers are "123", "34", and "8". Notice that "34" is only counted once.\n\n\n
Example 2:
\n\n\nInput: word = "leet1234code234"\nOutput: 2\n\n\n
Example 3:
\n\n\nInput: word = "a1b01c001"\nOutput: 1\nExplanation: The three integers "1", "01", and "001" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 1000
word
consists of digits and lowercase English letters.You are given an even integer n
\u200b\u200b\u200b\u200b\u200b\u200b. You initially have a permutation perm
of size n
\u200b\u200b where perm[i] == i
\u200b (0-indexed)\u200b\u200b\u200b\u200b.
In one operation, you will create a new array arr
, and for each i
:
i % 2 == 0
, then arr[i] = perm[i / 2]
.i % 2 == 1
, then arr[i] = perm[n / 2 + (i - 1) / 2]
.You will then assign arr
\u200b\u200b\u200b\u200b to perm
.
Return the minimum non-zero number of operations you need to perform on perm
to return the permutation to its initial value.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 1\nExplanation: perm = [0,1] initially.\nAfter the 1st operation, perm = [0,1]\nSo it takes only 1 operation.\n\n\n
Example 2:
\n\n\nInput: n = 4\nOutput: 2\nExplanation: perm = [0,1,2,3] initially.\nAfter the 1st operation, perm = [0,2,1,3]\nAfter the 2nd operation, perm = [0,1,2,3]\nSo it takes only 2 operations.\n\n\n
Example 3:
\n\n\nInput: n = 6\nOutput: 4\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
n
\u200b\u200b\u200b\u200b\u200b\u200b is even.You are given a string s
that contains some bracket pairs, with each pair containing a non-empty key.
"(name)is(age)yearsold"
, there are two bracket pairs that contain the keys "name"
and "age"
.You know the values of a wide range of keys. This is represented by a 2D string array knowledge
where each knowledge[i] = [keyi, valuei]
indicates that key keyi
has a value of valuei
.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi
, you will:
keyi
and the bracket pair with the key's corresponding valuei
.keyi
and the bracket pair with a question mark "?"
(without the quotation marks).Each key will appear at most once in your knowledge
. There will not be any nested brackets in s
.
Return the resulting string after evaluating all of the bracket pairs.
\n\n\n
Example 1:
\n\n\nInput: s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]]\nOutput: "bobistwoyearsold"\nExplanation:\nThe key "name" has a value of "bob", so replace "(name)" with "bob".\nThe key "age" has a value of "two", so replace "(age)" with "two".\n\n\n
Example 2:
\n\n\nInput: s = "hi(name)", knowledge = [["a","b"]]\nOutput: "hi?"\nExplanation: As you do not know the value of the key "name", replace "(name)" with "?".\n\n\n
Example 3:
\n\n\nInput: s = "(a)(a)(a)aaa", knowledge = [["a","yes"]]\nOutput: "yesyesyesaaa"\nExplanation: The same key can appear multiple times.\nThe key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes".\nNotice that the "a"s not in a bracket pair are not evaluated.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
0 <= knowledge.length <= 105
knowledge[i].length == 2
1 <= keyi.length, valuei.length <= 10
s
consists of lowercase English letters and round brackets '('
and ')'
.'('
in s
will have a corresponding close bracket ')'
.s
will be non-empty.s
.keyi
and valuei
consist of lowercase English letters.keyi
in knowledge
is unique.You are given a positive integer primeFactors
. You are asked to construct a positive integer n
that satisfies the following conditions:
n
(not necessarily distinct) is at most primeFactors
.n
is maximized. Note that a divisor of n
is nice if it is divisible by every prime factor of n
. For example, if n = 12
, then its prime factors are [2,2,3]
, then 6
and 12
are nice divisors, while 3
and 4
are not.Return the number of nice divisors of n
. Since that number can be too large, return it modulo 109 + 7
.
Note that a prime number is a natural number greater than 1
that is not a product of two smaller natural numbers. The prime factors of a number n
is a list of prime numbers such that their product equals n
.
\r\n
Example 1:
\r\n\r\n\r\nInput: primeFactors = 5\r\nOutput: 6\r\nExplanation: 200 is a valid value of n.\r\nIt has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\r\nThere is not other value of n that has at most 5 prime factors and more nice divisors.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: primeFactors = 8\r\nOutput: 18\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= primeFactors <= 109
You are given coordinates
, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return true
if the square is white, and false
if the square is black.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
\n\n\n
Example 1:
\n\n\nInput: coordinates = "a1"\nOutput: false\nExplanation: From the chessboard above, the square with coordinates "a1" is black, so return false.\n\n\n
Example 2:
\n\n\nInput: coordinates = "h3"\nOutput: true\nExplanation: From the chessboard above, the square with coordinates "h3" is white, so return true.\n\n\n
Example 3:
\n\n\nInput: coordinates = "c7"\nOutput: false\n\n\n
\n
Constraints:
\n\ncoordinates.length == 2
'a' <= coordinates[0] <= 'h'
'1' <= coordinates[1] <= '8'
You are given two strings sentence1
and sentence2
, each representing a sentence composed of words. A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of only uppercase and lowercase English characters.
Two sentences s1
and s2
are considered similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. Note that the inserted sentence must be separated from existing words by spaces.
For example,
\n\ns1 = "Hello Jane"
and s2 = "Hello my name is Jane"
can be made equal by inserting "my name is"
between "Hello"
and "Jane"
in s1.s1 = "Frog cool"
and s2 = "Frogs are cool"
are not similar, since although there is a sentence "s are"
inserted into s1
, it is not separated from "Frog"
by a space.Given two sentences sentence1
and sentence2
, return true if sentence1
and sentence2
are similar. Otherwise, return false.
\n
Example 1:
\n\nInput: sentence1 = "My name is Haley", sentence2 = "My Haley"
\n\nOutput: true
\n\nExplanation:
\n\nsentence2
can be turned to sentence1
by inserting "name is" between "My" and "Haley".
Example 2:
\n\nInput: sentence1 = "of", sentence2 = "A lot of words"
\n\nOutput: false
\n\nExplanation:
\n\nNo single sentence can be inserted inside one of the sentences to make it equal to the other.
\nExample 3:
\n\nInput: sentence1 = "Eating right now", sentence2 = "Eating"
\n\nOutput: true
\n\nExplanation:
\n\nsentence2
can be turned to sentence1
by inserting "right now" at the end of the sentence.
\n
Constraints:
\n\n1 <= sentence1.length, sentence2.length <= 100
sentence1
and sentence2
consist of lowercase and uppercase English letters and spaces.sentence1
and sentence2
are separated by a single space.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
nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])
Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [42,11,1,97]\nOutput: 2\nExplanation: The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.\n\n\n
Example 2:
\n\n\nInput: nums = [13,10,35,24,76]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
There is a donuts shop that bakes donuts in batches of batchSize
. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize
and an integer array groups
, where groups[i]
denotes that there is a group of groups[i]
customers that will visit the shop. Each customer will get exactly one donut.
When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.
\n\nYou can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.
\n\n\n
Example 1:
\n\n\nInput: batchSize = 3, groups = [1,2,3,4,5,6]\nOutput: 4\nExplanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\n\n\n
Example 2:
\n\n\nInput: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\nOutput: 4\n\n\n
\n
Constraints:
\n\n1 <= batchSize <= 9
1 <= groups.length <= 30
1 <= groups[i] <= 109
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
\n\n"Hello World"
, "HELLO"
, and "hello world hello world"
are all sentences.You are given a sentence s
\u200b\u200b\u200b\u200b\u200b\u200b and an integer k
\u200b\u200b\u200b\u200b\u200b\u200b. You want to truncate s
\u200b\u200b\u200b\u200b\u200b\u200b such that it contains only the first k
\u200b\u200b\u200b\u200b\u200b\u200b words. Return s
\u200b\u200b\u200b\u200b\u200b\u200b after truncating it.
\n
Example 1:
\n\n\nInput: s = "Hello how are you Contestant", k = 4\nOutput: "Hello how are you"\nExplanation:\nThe words in s are ["Hello", "how" "are", "you", "Contestant"].\nThe first 4 words are ["Hello", "how", "are", "you"].\nHence, you should return "Hello how are you".\n\n\n
Example 2:
\n\n\nInput: s = "What is the solution to this problem", k = 4\nOutput: "What is the solution"\nExplanation:\nThe words in s are ["What", "is" "the", "solution", "to", "this", "problem"].\nThe first 4 words are ["What", "is", "the", "solution"].\nHence, you should return "What is the solution".\n\n
Example 3:
\n\n\nInput: s = "chopper is not a tanuki", k = 5\nOutput: "chopper is not a tanuki"\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 500
k
is in the range [1, the number of words in s]
.s
consist of only lowercase and uppercase English letters and spaces.s
are separated by a single space.You are given the logs for users' actions on LeetCode, and an integer k
. The logs are represented by a 2D integer array logs
where each logs[i] = [IDi, timei]
indicates that the user with IDi
performed an action at the minute timei
.
Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.
\n\nThe user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.
\n\nYou are to calculate a 1-indexed array answer
of size k
such that, for each j
(1 <= j <= k
), answer[j]
is the number of users whose UAM equals j
.
Return the array answer
as described above.
\n
Example 1:
\n\n\nInput: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput: [0,2,0,0,0]\nExplanation:\nThe user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n\n\n
Example 2:
\n\n\nInput: logs = [[1,1],[2,2],[2,3]], k = 4\nOutput: [1,1,0,0]\nExplanation:\nThe user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n\n\n
\n
Constraints:
\n\n1 <= logs.length <= 104
0 <= IDi <= 109
1 <= timei <= 105
k
is in the range [The maximum UAM for a user, 105]
.You are given two positive integer arrays nums1
and nums2
, both of length n
.
The absolute sum difference of arrays nums1
and nums2
is defined as the sum of |nums1[i] - nums2[i]|
for each 0 <= i < n
(0-indexed).
You can replace at most one element of nums1
with any other element in nums1
to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most one element in the array nums1
. Since the answer may be large, return it modulo 109 + 7
.
|x|
is defined as:
x
if x >= 0
, or-x
if x < 0
.\n
Example 1:
\n\n\nInput: nums1 = [1,7,5], nums2 = [2,3,5]\nOutput: 3\nExplanation: There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| =
3.\n
\n\nExample 2:
\n\n\nInput: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput: 0\nExplanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput: 20\nExplanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
\n
\n\n\n
Constraints:
\n\nn == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105
You are given an array nums
that consists of positive integers.
The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.
\n\n[4,6,16]
is 2
.A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
\n\n[2,5,10]
is a subsequence of [1,2,1,2,4,1,5,10]
.Return the number of different GCDs among all non-empty subsequences of nums
.
\n
Example 1:
\n\nInput: nums = [6,10,3]\nOutput: 5\nExplanation: The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.\n\n\n
Example 2:
\n\n\nInput: nums = [5,15,40,5,6]\nOutput: 7\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 2 * 105
Implement a function signFunc(x)
that returns:
1
if x
is positive.-1
if x
is negative.0
if x
is equal to 0
.You are given an integer array nums
. Let product
be the product of all values in the array nums
.
Return signFunc(product)
.
\n
Example 1:
\n\n\nInput: nums = [-1,-2,-3,-4,3,2,1]\nOutput: 1\nExplanation: The product of all values in the array is 144, and signFunc(144) = 1\n\n\n
Example 2:
\n\n\nInput: nums = [1,5,0,2,-3]\nOutput: 0\nExplanation: The product of all values in the array is 0, and signFunc(0) = 0\n\n\n
Example 3:
\n\n\nInput: nums = [-1,1,-1,1,-1]\nOutput: -1\nExplanation: The product of all values in the array is -1, and signFunc(-1) = -1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-100 <= nums[i] <= 100
There are n
friends that are playing a game. The friends are sitting in a circle and are numbered from 1
to n
in clockwise order. More formally, moving clockwise from the ith
friend brings you to the (i+1)th
friend for 1 <= i < n
, and moving clockwise from the nth
friend brings you to the 1st
friend.
The rules of the game are as follows:
\n\n1st
friend.k
friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.2
starting from the friend immediately clockwise of the friend who just lost and repeat.Given the number of friends, n
, and an integer k
, return the winner of the game.
\n
Example 1:
\n\nInput: n = 5, k = 2\nOutput: 3\nExplanation: Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n\n
Example 2:
\n\n\nInput: n = 6, k = 5\nOutput: 1\nExplanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 500
\n
Follow up:
\n\nCould you solve this problem in linear time with constant space?
\n", - "likes": 3889, - "dislikes": 114, - "stats": "{\"totalAccepted\": \"315.5K\", \"totalSubmission\": \"384.9K\", \"totalAcceptedRaw\": 315469, \"totalSubmissionRaw\": 384854, \"acRate\": \"82.0%\"}", + "likes": 3945, + "dislikes": 115, + "stats": "{\"totalAccepted\": \"333.6K\", \"totalSubmission\": \"406.5K\", \"totalAcceptedRaw\": 333639, \"totalSubmissionRaw\": 406549, \"acRate\": \"82.1%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -68838,9 +68946,9 @@ "questionFrontendId": "1824", "title": "Minimum Sideway Jumps", "content": "There is a 3 lane road of length n
that consists of n + 1
points labeled from 0
to n
. A frog starts at point 0
in the second lane and wants to jump to point n
. However, there could be obstacles along the way.
You are given an array obstacles
of length n + 1
where each obstacles[i]
(ranging from 0 to 3) describes an obstacle on the lane obstacles[i]
at point i
. If obstacles[i] == 0
, there are no obstacles at point i
. There will be at most one obstacle in the 3 lanes at each point.
obstacles[2] == 1
, then there is an obstacle on lane 1 at point 2.The frog can only travel from point i
to point i + 1
on the same lane if there is not an obstacle on the lane at point i + 1
. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.
Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2
at point 0.
Note: There will be no obstacles on points 0
and n
.
\n
Example 1:
\n\nInput: obstacles = [0,1,2,3,0]\nOutput: 2 \nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n\n\n
Example 2:
\n\nInput: obstacles = [0,1,1,3,3,0]\nOutput: 0\nExplanation: There are no obstacles on lane 2. No side jumps are required.\n\n\n
Example 3:
\n\nInput: obstacles = [0,2,1,0,3,0]\nOutput: 2\nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n\n\n
\n
Constraints:
\n\nobstacles.length == n + 1
1 <= n <= 5 * 105
0 <= obstacles[i] <= 3
obstacles[0] == obstacles[n] == 0
You are given two integers, m
and k
, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
\n\nm
you should consider the MKAverage to be -1
. Otherwise, copy the last m
elements of the stream to a separate container.k
elements and the largest k
elements from the container.Implement the MKAverage
class:
MKAverage(int m, int k)
Initializes the MKAverage object with an empty stream and the two integers m
and k
.void addElement(int num)
Inserts a new element num
into the stream.int calculateMKAverage()
Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n
Example 1:
\n\n\nInput\n["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\nOutput\n[null, null, null, -1, null, 3, null, null, null, 5]\n\nExplanation\nMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be [3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be [5].\n // The average of [5] equals 5/1 = 5, return 5\n
\n\n\n
Constraints:
\n\n3 <= m <= 105
1 <= k*2 < m
1 <= num <= 105
105
calls will be made to addElement
and calculateMKAverage
.You are given two integers, m
and k
, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.
The MKAverage can be calculated using these steps:
\n\nm
you should consider the MKAverage to be -1
. Otherwise, copy the last m
elements of the stream to a separate container.k
elements and the largest k
elements from the container.Implement the MKAverage
class:
MKAverage(int m, int k)
Initializes the MKAverage object with an empty stream and the two integers m
and k
.void addElement(int num)
Inserts a new element num
into the stream.int calculateMKAverage()
Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n
Example 1:
\n\n\nInput\n["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]\n[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\nOutput\n[null, null, null, -1, null, 3, null, null, null, 5]\n\nExplanation\nMKAverage obj = new MKAverage(3, 1); \nobj.addElement(3); // current elements are [3]\nobj.addElement(1); // current elements are [3,1]\nobj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\nobj.addElement(10); // current elements are [3,1,10]\nobj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be [3].\n // The average of [3] equals 3/1 = 3, return 3\nobj.addElement(5); // current elements are [3,1,10,5]\nobj.addElement(5); // current elements are [3,1,10,5,5]\nobj.addElement(5); // current elements are [3,1,10,5,5,5]\nobj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be [5].\n // The average of [5] equals 5/1 = 5, return 5\n
\n\n\n
Constraints:
\n\n3 <= m <= 105
1 < k*2 < m
1 <= num <= 105
105
calls will be made to addElement
and calculateMKAverage
.You are given an integer array nums
(0-indexed). In one operation, you can choose an element of the array and increment it by 1
.
nums = [1,2,3]
, you can choose to increment nums[1]
to make nums = [1,3,3]
.Return the minimum number of operations needed to make nums
strictly increasing.
An array nums
is strictly increasing if nums[i] < nums[i+1]
for all 0 <= i < nums.length - 1
. An array of length 1
is trivially strictly increasing.
\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [1,1,1]\r\nOutput: 3\r\nExplanation: You can do the following operations:\r\n1) Increment nums[2], so nums becomes [1,1,2].\r\n2) Increment nums[1], so nums becomes [1,2,2].\r\n3) Increment nums[2], so nums becomes [1,2,3].\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [1,5,2,4,1]\r\nOutput: 14\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: nums = [8]\r\nOutput: 0\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= nums.length <= 5000
1 <= nums[i] <= 104
You are given an array points
where points[i] = [xi, yi]
is the coordinates of the ith
point on a 2D plane. Multiple points can have the same coordinates.
You are also given an array queries
where queries[j] = [xj, yj, rj]
describes a circle centered at (xj, yj)
with a radius of rj
.
For each query queries[j]
, compute the number of points inside the jth
circle. Points on the border of the circle are considered inside.
Return an array answer
, where answer[j]
is the answer to the jth
query.
\n
Example 1:
\n\nInput: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\nOutput: [3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\n\n\n
Example 2:
\n\nInput: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\nOutput: [2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n\n\n
\n
Constraints:
\n\n1 <= points.length <= 500
points[i].length == 2
0 <= x\u200b\u200b\u200b\u200b\u200b\u200bi, y\u200b\u200b\u200b\u200b\u200b\u200bi <= 500
1 <= queries.length <= 500
queries[j].length == 3
0 <= xj, yj <= 500
1 <= rj <= 500
\n
Follow up: Could you find the answer for each query in better complexity than O(n)
?
You are given a sorted array nums
of n
non-negative integers and an integer maximumBit
. You want to perform the following query n
times:
k < 2maximumBit
such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k
is maximized. k
is the answer to the ith
query.nums
.Return an array answer
, where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: nums = [0,1,1,3], maximumBit = 2\nOutput: [0,3,2,3]\nExplanation: The queries are answered as follows:\n1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n4th query: nums = [0], k = 3 since 0 XOR 3 = 3.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,4,7], maximumBit = 3\nOutput: [5,2,6,5]\nExplanation: The queries are answered as follows:\n1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n4th query: nums = [2], k = 5 since 2 XOR 5 = 7.\n\n\n
Example 3:
\n\n\nInput: nums = [0,1,2,2,5,7], maximumBit = 3\nOutput: [4,3,6,4,6,7]\n\n\n
\n
Constraints:
\n\nnums.length == n
1 <= n <= 105
1 <= maximumBit <= 20
0 <= nums[i] < 2maximumBit
nums
\u200b\u200b\u200b is sorted in ascending order.You are given a string s
(0-indexed)\u200b\u200b\u200b\u200b\u200b\u200b. You are asked to perform the following operation on s
\u200b\u200b\u200b\u200b\u200b\u200b until you get a sorted string:
i
such that 1 <= i < s.length
and s[i] < s[i - 1]
.j
such that i <= j < s.length
and s[k] < s[i - 1]
for all the possible values of k
in the range [i, j]
inclusive.i - 1
\u200b\u200b\u200b\u200b and j
\u200b\u200b\u200b\u200b\u200b.i
\u200b\u200b\u200b\u200b\u200b\u200b.Return the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "cba"\nOutput: 5\nExplanation: The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".\n\n\n
Example 2:
\n\n\nInput: s = "aabaa"\nOutput: 2\nExplanation: The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 3000
s
\u200b\u200b\u200b\u200b\u200b\u200b consists only of lowercase English letters.A pangram is a sentence where every letter of the English alphabet appears at least once.
\n\nGiven a string sentence
containing only lowercase English letters, return true
if sentence
is a pangram, or false
otherwise.
\n
Example 1:
\n\n\nInput: sentence = "thequickbrownfoxjumpsoverthelazydog"\nOutput: true\nExplanation: sentence contains at least one of every letter of the English alphabet.\n\n\n
Example 2:
\n\n\nInput: sentence = "leetcode"\nOutput: false\n\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 1000
sentence
consists of lowercase English letters.It is a sweltering summer day, and a boy wants to buy some ice cream bars.
\n\nAt the store, there are n
ice cream bars. You are given an array costs
of length n
, where costs[i]
is the price of the ith
ice cream bar in coins. The boy initially has coins
coins to spend, and he wants to buy as many ice cream bars as possible.
Note: The boy can buy the ice cream bars in any order.
\n\nReturn the maximum number of ice cream bars the boy can buy with coins
coins.
You must solve the problem by counting sort.
\n\n\n
Example 1:
\n\n\nInput: costs = [1,3,2,4,1], coins = 7\nOutput: 4\nExplanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\n\n\n
Example 2:
\n\n\nInput: costs = [10,6,8,7,7,8], coins = 5\nOutput: 0\nExplanation: The boy cannot afford any of the ice cream bars.\n\n\n
Example 3:
\n\n\nInput: costs = [1,6,3,1,2,5], coins = 20\nOutput: 6\nExplanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n\n\n
\n
Constraints:
\n\ncosts.length == n
1 <= n <= 105
1 <= costs[i] <= 105
1 <= coins <= 108
You are given n
\u200b\u200b\u200b\u200b\u200b\u200b tasks labeled from 0
to n - 1
represented by a 2D integer array tasks
, where tasks[i] = [enqueueTimei, processingTimei]
means that the i\u200b\u200b\u200b\u200b\u200b\u200bth
\u200b\u200b\u200b\u200b task will be available to process at enqueueTimei
and will take processingTimei
to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
\n\nReturn the order in which the CPU will process the tasks.
\n\n\n
Example 1:
\n\n\nInput: tasks = [[1,2],[2,4],[3,2],[4,1]]\nOutput: [0,2,3,1]\nExplanation: The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.\n\n\n
Example 2:
\n\n\nInput: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\nOutput: [4,3,2,0,1]\nExplanation: The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.\n\n\n
\n
Constraints:
\n\ntasks.length == n
1 <= n <= 105
1 <= enqueueTimei, processingTimei <= 109
The XOR sum of a list is the bitwise XOR
of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.
[1,2,3,4]
is equal to 1 XOR 2 XOR 3 XOR 4 = 4
, and the XOR sum of [3]
is equal to 3
.You are given two 0-indexed arrays arr1
and arr2
that consist only of non-negative integers.
Consider the list containing the result of arr1[i] AND arr2[j]
(bitwise AND
) for every (i, j)
pair where 0 <= i < arr1.length
and 0 <= j < arr2.length
.
Return the XOR sum of the aforementioned list.
\n\n\n
Example 1:
\n\n\nInput: arr1 = [1,2,3], arr2 = [6,5]\nOutput: 0\nExplanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\n\n\n
Example 2:
\n\n\nInput: arr1 = [12], arr2 = [4]\nOutput: 4\nExplanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n\n\n
\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 105
0 <= arr1[i], arr2[j] <= 109
Given an integer n
(in base 10
) and a base k
, return the sum of the digits of n
after converting n
from base 10
to base k
.
After converting, each digit should be interpreted as a base 10
number, and the sum should be returned in base 10
.
\n
Example 1:
\n\n\nInput: n = 34, k = 6\nOutput: 9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\n\n\n
Example 2:
\n\n\nInput: n = 10, k = 10\nOutput: 1\nExplanation: n is already in base 10. 1 + 0 = 1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
2 <= k <= 10
The frequency of an element is the number of times it occurs in an array.
\n\nYou are given an integer array nums
and an integer k
. In one operation, you can choose an index of nums
and increment the element at that index by 1
.
Return the maximum possible frequency of an element after performing at most k
operations.
\n
Example 1:
\n\n\nInput: nums = [1,2,4], k = 5\nOutput: 3\nExplanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n4 has a frequency of 3.\n\n
Example 2:
\n\n\nInput: nums = [1,4,8,13], k = 5\nOutput: 2\nExplanation: There are multiple optimal solutions:\n- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n\n\n
Example 3:
\n\n\nInput: nums = [3,9,6], k = 2\nOutput: 1\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 105
A string is considered beautiful if it satisfies the following conditions:
\n\n'a'
, 'e'
, 'i'
, 'o'
, 'u'
) must appear at least once in it.'a'
s before 'e'
s, all 'e'
s before 'i'
s, etc.).For example, strings "aeiou"
and "aaaaaaeiiiioou"
are considered beautiful, but "uaeio"
, "aeoiu"
, and "aaaeeeooo"
are not beautiful.
Given a string word
consisting of English vowels, return the length of the longest beautiful substring of word
. If no such substring exists, return 0
.
A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: word = "aeiaaioaaaaeiiiiouuuooaauuaeiu"\nOutput: 13\nExplanation: The longest beautiful substring in word is "aaaaeiiiiouuu" of length 13.\n\n
Example 2:
\n\n\nInput: word = "aeeeiiiioooauuuaeiou"\nOutput: 5\nExplanation: The longest beautiful substring in word is "aeiou" of length 5.\n\n\n
Example 3:
\n\n\nInput: word = "a"\nOutput: 0\nExplanation: There is no beautiful substring, so return 0.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 5 * 105
word
consists of characters 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.You want to build n
new buildings in a city. The new buildings will be built in a line and are labeled from 1
to n
.
However, there are city restrictions on the heights of the new buildings:
\n\n0
.1
.Additionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions
where restrictions[i] = [idi, maxHeighti]
indicates that building idi
must have a height less than or equal to maxHeighti
.
It is guaranteed that each building will appear at most once in restrictions
, and building 1
will not be in restrictions
.
Return the maximum possible height of the tallest building.
\n\n\n
Example 1:
\n\nInput: n = 5, restrictions = [[2,1],[4,1]]\nOutput: 2\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\n\n
Example 2:
\n\nInput: n = 6, restrictions = []\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\n\n\n
Example 3:
\n\nInput: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.\n\n\n
\n
Constraints:
\n\n2 <= n <= 109
0 <= restrictions.length <= min(n - 1, 105)
2 <= idi <= n
idi
is unique.0 <= maxHeighti <= 109
You are given a 0-indexed string s
that has lowercase English letters in its even indices and digits in its odd indices.
You must perform an operation shift(c, x)
, where c
is a character and x
is a digit, that returns the xth
character after c
.
shift('a', 5) = 'f'
and shift('x', 0) = 'x'
.For every odd index i
, you want to replace the digit s[i]
with the result of the shift(s[i-1], s[i])
operation.
Return s
after replacing all digits. It is guaranteed that shift(s[i-1], s[i])
will never exceed 'z'
.
Note that shift(c, x)
is not a preloaded function, but an operation to be implemented as part of the solution.
\n
Example 1:
\n\n\nInput: s = "a1c1e1"\nOutput: "abcdef"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'\n\n
Example 2:
\n\n\nInput: s = "a1b2c3d4e"\nOutput: "abbdcfdhe"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of lowercase English letters and digits.shift(s[i-1], s[i]) <= 'z'
for all odd indices i
.Design a system that manages the reservation state of n
seats that are numbered from 1
to n
.
Implement the SeatManager
class:
SeatManager(int n)
Initializes a SeatManager
object that will manage n
seats numbered from 1
to n
. All seats are initially available.int reserve()
Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.void unreserve(int seatNumber)
Unreserves the seat with the given seatNumber
.\n
Example 1:
\n\n\nInput\n["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"]\n[[5], [], [], [2], [], [], [], [], [5]]\nOutput\n[null, 1, 2, null, 2, 3, 4, 5, null]\n\nExplanation\nSeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\nseatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\nseatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\nseatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\nseatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\nseatManager.reserve(); // The only available seat is seat 5, so return 5.\nseatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= seatNumber <= n
reserve
, it is guaranteed that there will be at least one unreserved seat.unreserve
, it is guaranteed that seatNumber
will be reserved.105
calls in total will be made to reserve
and unreserve
.You are given an array of positive integers arr
. Perform some operations (possibly none) on arr
so that it satisfies these conditions:
arr
must be 1
.1
. In other words, abs(arr[i] - arr[i - 1]) <= 1
for each i
where 1 <= i < arr.length
(0-indexed). abs(x)
is the absolute value of x
.There are 2 types of operations that you can perform any number of times:
\n\narr
to a smaller positive integer.arr
to be in any order.Return the maximum possible value of an element in arr
after performing the operations to satisfy the conditions.
\n
Example 1:
\n\n\nInput: arr = [2,2,1,2,1]\nOutput: 2\nExplanation: \nWe can satisfy the conditions by rearranging\n\narr
so it becomes[1,2,2,2,1]
.\nThe largest element inarr
is 2.\n
Example 2:
\n\n\nInput: arr = [100,1,1000]\nOutput: 3\nExplanation: \nOne possible way to satisfy the conditions is by doing the following:\n1. Rearrange\n\narr
so it becomes[1,100,1000]
.\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNowarr = [1,2,3]
, whichsatisfies the conditions.\nThe largest element in
arr is 3.
\n
Example 3:
\n\n\nInput: arr = [1,2,3,4,5]\nOutput: 5\nExplanation: The array already satisfies the conditions, and the largest element is 5.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i] <= 109
There is a hotel with n
rooms. The rooms are represented by a 2D integer array rooms
where rooms[i] = [roomIdi, sizei]
denotes that there is a room with room number roomIdi
and size equal to sizei
. Each roomIdi
is guaranteed to be unique.
You are also given k
queries in a 2D array queries
where queries[j] = [preferredj, minSizej]
. The answer to the jth
query is the room number id
of a room such that:
minSizej
, andabs(id - preferredj)
is minimized, where abs(x)
is the absolute value of x
.If there is a tie in the absolute difference, then use the room with the smallest such id
. If there is no such room, the answer is -1
.
Return an array answer
of length k
where answer[j]
contains the answer to the jth
query.
\n
Example 1:
\n\n\nInput: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\nOutput: [3,-1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.\n\n
Example 2:
\n\n\nInput: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\nOutput: [2,1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.\n\n
\n
Constraints:
\n\nn == rooms.length
1 <= n <= 105
k == queries.length
1 <= k <= 104
1 <= roomIdi, preferredj <= 107
1 <= sizei, minSizej <= 107
Given an integer array nums
(0-indexed) and two integers target
and start
, find an index i
such that nums[i] == target
and abs(i - start)
is minimized. Note that abs(x)
is the absolute value of x
.
Return abs(i - start)
.
It is guaranteed that target
exists in nums
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5], target = 5, start = 3\nOutput: 1\nExplanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n\n\n
Example 2:
\n\n\nInput: nums = [1], target = 1, start = 0\nOutput: 0\nExplanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput: 0\nExplanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 104
0 <= start < nums.length
target
is in nums
.You are given a string s
that consists of only digits.
Check if we can split s
into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1
.
s = "0090089"
can be split into ["0090", "089"]
with numerical values [90,89]
. The values are in descending order and adjacent values differ by 1
, so this way is valid.s = "001"
can be split into ["0", "01"]
, ["00", "1"]
, or ["0", "0", "1"]
. However all the ways are invalid because they have numerical values [0,1]
, [0,1]
, and [0,0,1]
respectively, all of which are not in descending order.Return true
if it is possible to split s
\u200b\u200b\u200b\u200b\u200b\u200b as described above, or false
otherwise.
A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: s = "1234"\nOutput: false\nExplanation: There is no valid way to split s.\n\n\n
Example 2:
\n\n\nInput: s = "050043"\nOutput: true\nExplanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.\n\n\n
Example 3:
\n\n\nInput: s = "9080701"\nOutput: false\nExplanation: There is no valid way to split s.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 20
s
only consists of digits.You are given a string num
, representing a large integer, and an integer k
.
We call some integer wonderful if it is a permutation of the digits in num
and is greater in value than num
. There can be many wonderful integers. However, we only care about the smallest-valued ones.
num = "5489355142"
:\n\n\t"5489355214"
."5489355241"
."5489355412"
."5489355421"
.Return the minimum number of adjacent digit swaps that needs to be applied to num
to reach the kth
smallest wonderful integer.
The tests are generated in such a way that kth
smallest wonderful integer exists.
\n
Example 1:
\n\n\nInput: num = "5489355142", k = 4\nOutput: 2\nExplanation: The 4th smallest wonderful number is "5489355421". To get this number:\n- Swap index 7 with index 8: "5489355142" -> "5489355412"\n- Swap index 8 with index 9: "5489355412" -> "5489355421"\n\n\n
Example 2:
\n\n\nInput: num = "11112", k = 4\nOutput: 4\nExplanation: The 4th smallest wonderful number is "21111". To get this number:\n- Swap index 3 with index 4: "11112" -> "11121"\n- Swap index 2 with index 3: "11121" -> "11211"\n- Swap index 1 with index 2: "11211" -> "12111"\n- Swap index 0 with index 1: "12111" -> "21111"\n\n\n
Example 3:
\n\n\nInput: num = "00123", k = 1\nOutput: 1\nExplanation: The 1st smallest wonderful number is "00132". To get this number:\n- Swap index 3 with index 4: "00123" -> "00132"\n\n\n
\n
Constraints:
\n\n2 <= num.length <= 1000
1 <= k <= 1000
num
only consists of digits.You are given a 2D integer array intervals
, where intervals[i] = [lefti, righti]
describes the ith
interval starting at lefti
and ending at righti
(inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1
.
You are also given an integer array queries
. The answer to the jth
query is the size of the smallest interval i
such that lefti <= queries[j] <= righti
. If no such interval exists, the answer is -1
.
Return an array containing the answers to the queries.
\n\n\n
Example 1:
\n\n\nInput: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]\nOutput: [3,3,1,4]\nExplanation: The queries are processed as follows:\n- Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n- Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n- Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n- Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.\n\n\n
Example 2:
\n\n\nInput: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]\nOutput: [2,-1,4,6]\nExplanation: The queries are processed as follows:\n- Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n- Query = 19: None of the intervals contain 19. The answer is -1.\n- Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n- Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 105
1 <= queries.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 107
1 <= queries[j] <= 107
You are given a 2D integer array logs
where each logs[i] = [birthi, deathi]
indicates the birth and death years of the ith
person.
The population of some year x
is the number of people alive during that year. The ith
person is counted in year x
's population if x
is in the inclusive range [birthi, deathi - 1]
. Note that the person is not counted in the year that they die.
Return the earliest year with the maximum population.
\n\n\n
Example 1:
\n\n\nInput: logs = [[1993,1999],[2000,2010]]\nOutput: 1993\nExplanation: The maximum population is 1, and 1993 is the earliest year with this population.\n\n\n
Example 2:
\n\n\nInput: logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput: 1960\nExplanation: \nThe maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.\n\n
\n
Constraints:
\n\n1 <= logs.length <= 100
1950 <= birthi < deathi <= 2050
You are given two non-increasing 0-indexed integer arrays nums1
\u200b\u200b\u200b\u200b\u200b\u200b and nums2
\u200b\u200b\u200b\u200b\u200b\u200b.
A pair of indices (i, j)
, where 0 <= i < nums1.length
and 0 <= j < nums2.length
, is valid if both i <= j
and nums1[i] <= nums2[j]
. The distance of the pair is j - i
\u200b\u200b\u200b\u200b.
Return the maximum distance of any valid pair (i, j)
. If there are no valid pairs, return 0
.
An array arr
is non-increasing if arr[i-1] >= arr[i]
for every 1 <= i < arr.length
.
\n
Example 1:
\n\n\nInput: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput: 2\nExplanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,2,2], nums2 = [10,10,1]\nOutput: 1\nExplanation: The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).\n\n\n
Example 3:
\n\n\nInput: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput: 2\nExplanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 105
nums1
and nums2
are non-increasing.The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.
\n\n[3,2,5]
(minimum value is 2
) has a min-product of 2 * (3+2+5) = 2 * 10 = 20
.Given an array of integers nums
, return the maximum min-product of any non-empty subarray of nums
. Since the answer may be large, return it modulo 109 + 7
.
Note that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.
\n\nA subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,2]\nOutput: 14\nExplanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,3,1,2]\nOutput: 18\nExplanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18.\n\n\n
Example 3:
\n\n\nInput: nums = [3,1,5,6,4,2]\nOutput: 60\nExplanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 107
There is a directed graph of n
colored nodes and m
edges. The nodes are numbered from 0
to n - 1
.
You are given a string colors
where colors[i]
is a lowercase English letter representing the color of the ith
node in this graph (0-indexed). You are also given a 2D array edges
where edges[j] = [aj, bj]
indicates that there is a directed edge from node aj
to node bj
.
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk
such that there is a directed edge from xi
to xi+1
for every 1 <= i < k
. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1
if the graph contains a cycle.
\r\n
Example 1:
\r\n\r\n\r\nInput: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]\r\nOutput: 3\r\nExplanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image)
.\r\n
\r\n\r\nExample 2:
\r\n\r\n\r\nInput: colors = "a", edges = [[0,0]]\r\nOutput: -1\r\nExplanation: There is a cycle from 0 to 0.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\nn == colors.length
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors
consists of lowercase English letters.0 <= aj, bj < n
There is a directed graph of n
colored nodes and m
edges. The nodes are numbered from 0
to n - 1
.
You are given a string colors
where colors[i]
is a lowercase English letter representing the color of the ith
node in this graph (0-indexed). You are also given a 2D array edges
where edges[j] = [aj, bj]
indicates that there is a directed edge from node aj
to node bj
.
A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk
such that there is a directed edge from xi
to xi+1
for every 1 <= i < k
. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.
Return the largest color value of any valid path in the given graph, or -1
if the graph contains a cycle.
\n
Example 1:
\n\n\nInput: colors = "abaca", edges = [[0,1],[0,2],[2,3],[3,4]]\nOutput: 3\nExplanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored "a" (red in the above image)
.\n
\n\nExample 2:
\n\n\nInput: colors = "a", edges = [[0,0]]\nOutput: -1\nExplanation: There is a cycle from 0 to 0.\n\n\n
\n
Constraints:
\n\nn == colors.length
m == edges.length
1 <= n <= 105
0 <= m <= 105
colors
consists of lowercase English letters.0 <= aj, bj < n
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.
\n\nA sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.
\n\n"This is a sentence"
can be shuffled as "sentence4 a3 is2 This1"
or "is2 sentence4 This1 a3"
.Given a shuffled sentence s
containing no more than 9
words, reconstruct and return the original sentence.
\n
Example 1:
\n\n\nInput: s = "is2 sentence4 This1 a3"\nOutput: "This is a sentence"\nExplanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.\n\n\n
Example 2:
\n\n\nInput: s = "Myself2 Me1 I4 and3"\nOutput: "Me Myself and I"\nExplanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 200
s
consists of lowercase and uppercase English letters, spaces, and digits from 1
to 9
.s
is between 1
and 9
.s
are separated by a single space.s
contains no leading or trailing spaces.You are given two integers memory1
and memory2
representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.
At the ith
second (starting from 1), i
bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i
bits of available memory, the program crashes.
Return an array containing [crashTime, memory1crash, memory2crash]
, where crashTime
is the time (in seconds) when the program crashed and memory1crash
and memory2crash
are the available bits of memory in the first and second sticks respectively.
\n
Example 1:
\n\n\nInput: memory1 = 2, memory2 = 2\nOutput: [3,1,0]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n\n\n
Example 2:
\n\n\nInput: memory1 = 8, memory2 = 11\nOutput: [6,0,4]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n\n\n
\n
Constraints:
\n\n0 <= memory1, memory2 <= 231 - 1
You are given an m x n
matrix of characters boxGrid
representing a side-view of a box. Each cell of the box is one of the following:
'#'
'*'
'.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
\n\nIt is guaranteed that each stone in boxGrid
rests on an obstacle, another stone, or the bottom of the box.
Return an n x m
matrix representing the box after the rotation described above.
\n
Example 1:
\n\n\nInput: boxGrid = [["#",".","#"]]\nOutput: [["."],\n ["#"],\n ["#"]]\n\n\n
Example 2:
\n\n\nInput: boxGrid = [["#",".","*","."],\n ["#","#","*","."]]\nOutput: [["#","."],\n ["#","#"],\n ["*","*"],\n [".","."]]\n\n\n
Example 3:
\n\n\nInput: boxGrid = [["#","#","*",".","*","."],\n ["#","#","#","*",".","."],\n ["#","#","#",".","#","."]]\nOutput: [[".","#","#"],\n [".","#","#"],\n ["#","#","*"],\n ["#","*","."],\n ["#",".","*"],\n ["#",".","."]]\n\n\n
\n
Constraints:
\n\nm == boxGrid.length
n == boxGrid[i].length
1 <= m, n <= 500
boxGrid[i][j]
is either '#'
, '*'
, or '.'
.Given an integer array nums
, return the sum of floor(nums[i] / nums[j])
for all pairs of indices 0 <= i, j < nums.length
in the array. Since the answer may be too large, return it modulo 109 + 7
.
The floor()
function returns the integer part of the division.
\n
Example 1:
\n\n\nInput: nums = [2,5,9]\nOutput: 10\nExplanation:\nfloor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up.\n\n\n
Example 2:
\n\n\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 49\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
The XOR total of an array is defined as the bitwise XOR
of all its elements, or 0
if the array is empty.
[2,5,6]
is 2 XOR 5 XOR 6 = 1
.Given an array nums
, return the sum of all XOR totals for every subset of nums
.
Note: Subsets with the same elements should be counted multiple times.
\n\nAn array a
is a subset of an array b
if a
can be obtained from b
by deleting some (possibly zero) elements of b
.
\n
Example 1:
\n\n\nInput: nums = [1,3]\nOutput: 6\nExplanation: The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6\n\n\n
Example 2:
\n\n\nInput: nums = [5,1,6]\nOutput: 28\nExplanation: The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28\n\n\n
Example 3:
\n\n\nInput: nums = [3,4,5,6,7,8]\nOutput: 480\nExplanation: The sum of all XOR totals for every subset is 480.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 12
1 <= nums[i] <= 20
Given a binary string s
, return the minimum number of character swaps to make it alternating, or -1
if it is impossible.
The string is called alternating if no two adjacent characters are equal. For example, the strings "010"
and "1010"
are alternating, while the string "0100"
is not.
Any two characters may be swapped, even if they are not adjacent.
\n\n\n
Example 1:
\n\n\nInput: s = "111000"\nOutput: 1\nExplanation: Swap positions 1 and 4: "111000" -> "101010"\nThe string is now alternating.\n\n\n
Example 2:
\n\n\nInput: s = "010"\nOutput: 0\nExplanation: The string is already alternating, no swaps are needed.\n\n\n
Example 3:
\n\n\nInput: s = "1110"\nOutput: -1\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either '0'
or '1'
.You are given two integer arrays nums1
and nums2
. You are tasked to implement a data structure that supports queries of two types:
nums2
.(i, j)
such that nums1[i] + nums2[j]
equals a given value (0 <= i < nums1.length
and 0 <= j < nums2.length
).Implement the FindSumPairs
class:
FindSumPairs(int[] nums1, int[] nums2)
Initializes the FindSumPairs
object with two integer arrays nums1
and nums2
.void add(int index, int val)
Adds val
to nums2[index]
, i.e., apply nums2[index] += val
.int count(int tot)
Returns the number of pairs (i, j)
such that nums1[i] + nums2[j] == tot
.\n
Example 1:
\n\n\nInput\n["FindSumPairs", "count", "add", "count", "count", "add", "add", "count"]\n[[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]\nOutput\n[null, 8, null, 2, 1, null, null, 11]\n\nExplanation\nFindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\nfindSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\nfindSumPairs.add(3, 2); // now nums2 = [1,4,5,4\n\n,5,4
]\nfindSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\nfindSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\nfindSumPairs.add(0, 1); // now nums2 = [2
,4,5,4,5,4
]\nfindSumPairs.add(1, 1); // now nums2 = [2
,5,5,4,5,4
]\nfindSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4\n
\n
Constraints:
\n\n1 <= nums1.length <= 1000
1 <= nums2.length <= 105
1 <= nums1[i] <= 109
1 <= nums2[i] <= 105
0 <= index < nums2.length
1 <= val <= 105
1 <= tot <= 109
1000
calls are made to add
and count
each.There are n
uniquely-sized sticks whose lengths are integers from 1
to n
. You want to arrange the sticks such that exactly k
sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.
[1,3,2,5,4]
, then the sticks with lengths 1
, 3
, and 5
are visible from the left.Given n
and k
, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 3, k = 2\nOutput: 3\nExplanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.\n\n\n
Example 2:
\n\n\nInput: n = 5, k = 5\nOutput: 1\nExplanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.\n\n\n
Example 3:
\n\n\nInput: n = 20, k = 11\nOutput: 647427950\nExplanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
1 <= k <= n
Given a binary string s
, return true
if the longest contiguous segment of 1
's is strictly longer than the longest contiguous segment of 0
's in s
, or return false
otherwise.
s = "110100010"
the longest continuous segment of 1
s has length 2
, and the longest continuous segment of 0
s has length 3
.Note that if there are no 0
's, then the longest continuous segment of 0
's is considered to have a length 0
. The same applies if there is no 1
's.
\n
Example 1:
\n\n\nInput: s = "1101"\nOutput: true\nExplanation:\nThe longest contiguous segment of 1s has length 2: "1101"\nThe longest contiguous segment of 0s has length 1: "1101"\nThe segment of 1s is longer, so return true.\n\n\n
Example 2:
\n\n\nInput: s = "111000"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 3: "111000"\nThe longest contiguous segment of 0s has length 3: "111000"\nThe segment of 1s is not longer, so return false.\n\n\n
Example 3:
\n\n\nInput: s = "110100010"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 2: "110100010"\nThe longest contiguous segment of 0s has length 3: "110100010"\nThe segment of 1s is not longer, so return false.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s[i]
is either '0'
or '1'
.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.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
\n\n1st
train ride takes 1.5
hours, you must wait for an additional 0.5
hours before you can depart on the 2nd
train ride at the 2 hour mark.Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1
if it is impossible to be on time.
Tests are generated such that the answer will not exceed 107
and hour
will have at most two digits after the decimal point.
\n
Example 1:
\n\n\nInput: dist = [1,3,2], hour = 6\nOutput: 1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.\n\n\n
Example 2:
\n\n\nInput: dist = [1,3,2], hour = 2.7\nOutput: 3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.\n\n\n
Example 3:
\n\n\nInput: dist = [1,3,2], hour = 1.9\nOutput: -1\nExplanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n\n\n
\n
Constraints:
\n\nn == dist.length
1 <= n <= 105
1 <= dist[i] <= 105
1 <= hour <= 109
hour
.You are given a 0-indexed binary string s
and two integers minJump
and maxJump
. In the beginning, you are standing at index 0
, which is equal to '0'
. You can move from index i
to index j
if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1)
, ands[j] == '0'
.Return true
if you can reach index s.length - 1
in s
, or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "011010", minJump = 2, maxJump = 3\nOutput: true\nExplanation:\nIn the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.\n\n\n
Example 2:
\n\n\nInput: s = "01101110", minJump = 2, maxJump = 3\nOutput: false\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 105
s[i]
is either '0'
or '1'
.s[0] == '0'
1 <= minJump <= maxJump < s.length
Alice and Bob take turns playing a game, with Alice starting first.
\r\n\r\nThere are n
stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:
x > 1
, and remove the leftmost x
stones from the row.The game stops when only one stone is left in the row.
\r\n\r\nThe score difference between Alice and Bob is (Alice's score - Bob's score)
. Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.
Given an integer array stones
of length n
where stones[i]
represents the value of the ith
stone from the left, return the score difference between Alice and Bob if they both play optimally.
\r\n
Example 1:
\r\n\r\n\r\nInput: stones = [-1,2,-3,4,-5]\r\nOutput: 5\r\nExplanation:\r\n- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\r\n value 2 on the left. stones = [2,-5].\r\n- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\r\n the left. stones = [-3].\r\nThe difference between their scores is 2 - (-3) = 5.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: stones = [7,-6,5,10,5,-2,-6]\r\nOutput: 13\r\nExplanation:\r\n- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\r\n stone of value 13 on the left. stones = [13].\r\nThe difference between their scores is 13 - 0 = 13.\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: stones = [-10,-12]\r\nOutput: -22\r\nExplanation:\r\n- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\r\n score and places a stone of value -22 on the left. stones = [-22].\r\nThe difference between their scores is (-22) - 0 = -22.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\nn == stones.length
2 <= n <= 105
-104 <= stones[i] <= 104
Table: Employees
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| employee_id | int |\n| name | varchar |\n| salary | int |\n+-------------+---------+\nemployee_id is the primary key (column with unique values) for this table.\nEach row of this table indicates the employee ID, employee name, and salary.\n\n\n
\n\n
Write a solution to calculate the bonus of each employee. The bonus of an employee is 100%
of their salary if the ID of the employee is an odd number and the employee's name does not start with the character 'M'
. The bonus of an employee is 0
otherwise.
Return the result table ordered by employee_id
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+-------------+---------+--------+\n| employee_id | name | salary |\n+-------------+---------+--------+\n| 2 | Meir | 3000 |\n| 3 | Michael | 3800 |\n| 7 | Addilyn | 7400 |\n| 8 | Juan | 6100 |\n| 9 | Kannon | 7700 |\n+-------------+---------+--------+\nOutput: \n+-------------+-------+\n| employee_id | bonus |\n+-------------+-------+\n| 2 | 0 |\n| 3 | 0 |\n| 7 | 7400 |\n| 8 | 0 |\n| 9 | 7700 |\n+-------------+-------+\nExplanation: \nThe employees with IDs 2 and 8 get 0 bonus because they have an even employee_id.\nThe employee with ID 3 gets 0 bonus because their name starts with 'M'.\nThe rest of the employees get a 100% bonus.\n\n", - "likes": 1103, - "dislikes": 78, - "stats": "{\"totalAccepted\": \"272.8K\", \"totalSubmission\": \"474.6K\", \"totalAcceptedRaw\": 272756, \"totalSubmissionRaw\": 474601, \"acRate\": \"57.5%\"}", + "likes": 1126, + "dislikes": 79, + "stats": "{\"totalAccepted\": \"292.6K\", \"totalSubmission\": \"510.7K\", \"totalAcceptedRaw\": 292593, \"totalSubmissionRaw\": 510653, \"acRate\": \"57.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -70688,7 +70796,7 @@ "content": null, "likes": 248, "dislikes": 27, - "stats": "{\"totalAccepted\": \"20.9K\", \"totalSubmission\": \"23.5K\", \"totalAcceptedRaw\": 20935, \"totalSubmissionRaw\": 23484, \"acRate\": \"89.1%\"}", + "stats": "{\"totalAccepted\": \"21.5K\", \"totalSubmission\": \"24.1K\", \"totalAcceptedRaw\": 21489, \"totalSubmissionRaw\": 24132, \"acRate\": \"89.0%\"}", "similarQuestions": "[{\"title\": \"Choose Numbers From Two Arrays in Range\", \"titleSlug\": \"choose-numbers-from-two-arrays-in-range\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -70728,7 +70836,7 @@ "content": null, "likes": 75, "dislikes": 6, - "stats": "{\"totalAccepted\": \"13.4K\", \"totalSubmission\": \"20K\", \"totalAcceptedRaw\": 13357, \"totalSubmissionRaw\": 19995, \"acRate\": \"66.8%\"}", + "stats": "{\"totalAccepted\": \"14.1K\", \"totalSubmission\": \"21.2K\", \"totalAcceptedRaw\": 14060, \"totalSubmissionRaw\": 21196, \"acRate\": \"66.3%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -70754,9 +70862,9 @@ "questionFrontendId": "1876", "title": "Substrings of Size Three with Distinct Characters", "content": "
A string is good if there are no repeated characters.
\n\nGiven a string s
\u200b\u200b\u200b\u200b\u200b, return the number of good substrings of length three in s
\u200b\u200b\u200b\u200b\u200b\u200b.
Note that if there are multiple occurrences of the same substring, every occurrence should be counted.
\n\nA substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: s = "xyzzaz"\nOutput: 1\nExplanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". \nThe only good substring of length 3 is "xyz".\n\n\n
Example 2:
\n\n\nInput: s = "aababcabc"\nOutput: 4\nExplanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc".\nThe good substrings are "abc", "bca", "cab", and "abc".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
\u200b\u200b\u200b\u200b\u200b\u200b consists of lowercase English letters.The pair sum of a pair (a,b)
is equal to a + b
. The maximum pair sum is the largest pair sum in a list of pairs.
(1,5)
, (2,3)
, and (4,4)
, the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8
.Given an array nums
of even length n
, pair up the elements of nums
into n / 2
pairs such that:
nums
is in exactly one pair, andReturn the minimized maximum pair sum after optimally pairing up the elements.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [3,5,2,3]\r\nOutput: 7\r\nExplanation: The elements can be paired up into pairs (3,3) and (5,2).\r\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [3,5,4,2,4,6]\r\nOutput: 8\r\nExplanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\r\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\nn == nums.length
2 <= n <= 105
n
is even.1 <= nums[i] <= 105
You are given an m x n
integer matrix grid
\u200b\u200b\u200b.
A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid
\u200b\u200b\u200b. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:
Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.
\n\nReturn the biggest three distinct rhombus sums in the grid
in descending order. If there are less than three distinct values, return all of them.
\n
Example 1:
\n\nInput: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput: [228,216,211]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211\n\n\n
Example 2:
\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [20,9,8]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)\n\n\n
Example 3:
\n\n\nInput: grid = [[7,7,7]]\nOutput: [7]\nExplanation: All three possible rhombus sums are the same, so return [7].\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 105
You are given two integer arrays nums1
and nums2
of length n
.
The XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])
(0-indexed).
[1,2,3]
and [3,2,1]
is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4
.Rearrange the elements of nums2
such that the resulting XOR sum is minimized.
Return the XOR sum after the rearrangement.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [1,2], nums2 = [2,3]\nOutput: 2\nExplanation: Rearrange\n\nnums2
so that it becomes[3,2]
.\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.
Example 2:
\n\n\nInput: nums1 = [1,0,3], nums2 = [5,3,4]\nOutput: 8\nExplanation: Rearrange\n\nnums2
so that it becomes[5,4,3]
. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.\n
\n
Constraints:
\n\nn == nums1.length
n == nums2.length
1 <= n <= 14
0 <= nums1[i], nums2[i] <= 107
The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0
, 'b' -> 1
, 'c' -> 2
, etc.).
The numerical value of some string of lowercase English letters s
is the concatenation of the letter values of each letter in s
, which is then converted into an integer.
s = "acb"
, we concatenate each letter's letter value, resulting in "021"
. After converting it, we get 21
.You are given three strings firstWord
, secondWord
, and targetWord
, each consisting of lowercase English letters 'a'
through 'j'
inclusive.
Return true
if the summation of the numerical values of firstWord
and secondWord
equals the numerical value of targetWord
, or false
otherwise.
\n
Example 1:
\n\n\nInput: firstWord = "acb", secondWord = "cba", targetWord = "cdb"\nOutput: true\nExplanation:\nThe numerical value of firstWord is "acb" -> "021" -> 21.\nThe numerical value of secondWord is "cba" -> "210" -> 210.\nThe numerical value of targetWord is "cdb" -> "231" -> 231.\nWe return true because 21 + 210 == 231.\n\n\n
Example 2:
\n\n\nInput: firstWord = "aaa", secondWord = "a", targetWord = "aab"\nOutput: false\nExplanation: \nThe numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aab" -> "001" -> 1.\nWe return false because 0 + 0 != 1.\n\n\n
Example 3:
\n\n\nInput: firstWord = "aaa", secondWord = "a", targetWord = "aaaa"\nOutput: true\nExplanation: \nThe numerical value of firstWord is "aaa" -> "000" -> 0.\nThe numerical value of secondWord is "a" -> "0" -> 0.\nThe numerical value of targetWord is "aaaa" -> "0000" -> 0.\nWe return true because 0 + 0 == 0.\n\n\n
\n
Constraints:
\n\n1 <= firstWord.length,
secondWord.length,
targetWord.length <= 8
firstWord
, secondWord
, and targetWord
consist of lowercase English letters from 'a'
to 'j'
inclusive.You are given a very large integer n
, represented as a string,\u200b\u200b\u200b\u200b\u200b\u200b and an integer digit x
. The digits in n
and the digit x
are in the inclusive range [1, 9]
, and n
may represent a negative number.
You want to maximize n
's numerical value by inserting x
anywhere in the decimal representation of n
\u200b\u200b\u200b\u200b\u200b\u200b. You cannot insert x
to the left of the negative sign.
n = 73
and x = 6
, it would be best to insert it between 7
and 3
, making n = 763
.n = -55
and x = 2
, it would be best to insert it before the first 5
, making n = -255
.Return a string representing the maximum value of n
\u200b\u200b\u200b\u200b\u200b\u200b after the insertion.
\n
Example 1:
\n\n\nInput: n = "99", x = 9\nOutput: "999"\nExplanation: The result is the same regardless of where you insert 9.\n\n\n
Example 2:
\n\n\nInput: n = "-13", x = 2\nOutput: "-123"\nExplanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n\n\n
\n
Constraints:
\n\n1 <= n.length <= 105
1 <= x <= 9
n
\u200b\u200b\u200b are in the range [1, 9]
.n
is a valid representation of an integer.n
,\u200b\u200b\u200b\u200b\u200b\u200b it will begin with '-'
.You are given two 0-indexed integer arrays servers
and tasks
of lengths n
\u200b\u200b\u200b\u200b\u200b\u200b and m
\u200b\u200b\u200b\u200b\u200b\u200b respectively. servers[i]
is the weight of the i\u200b\u200b\u200b\u200b\u200b\u200bth
\u200b\u200b\u200b\u200b server, and tasks[j]
is the time needed to process the j\u200b\u200b\u200b\u200b\u200b\u200bth
\u200b\u200b\u200b\u200b task in seconds.
Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.
\n\nAt second j
, the jth
task is inserted into the queue (starting with the 0th
task being inserted at second 0
). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.
If there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.
\n\nA server that is assigned task j
at second t
will be free again at second t + tasks[j]
.
Build an array ans
\u200b\u200b\u200b\u200b of length m
, where ans[j]
is the index of the server the j\u200b\u200b\u200b\u200b\u200b\u200bth
task will be assigned to.
Return the array ans
\u200b\u200b\u200b\u200b.
\n
Example 1:
\n\n\nInput: servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput: [2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n\n
Example 2:
\n\n\nInput: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput: [1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.\n\n\n
\n
Constraints:
\n\nservers.length == n
tasks.length == m
1 <= n, m <= 2 * 105
1 <= servers[i], tasks[j] <= 2 * 105
You are given an integer hoursBefore
, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n
roads. The road lengths are given as an integer array dist
of length n
, where dist[i]
describes the length of the ith
road in kilometers. In addition, you are given an integer speed
, which is the speed (in km/h) you will travel at.
After you travel road i
, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.
1.4
hours, you must wait until the 2
hour mark before traveling the next road. If traveling a road takes exactly 2
hours, you do not need to wait.However, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.
\n\n1.4
hours and traveling the second road takes 0.6
hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2
hour mark, letting you start traveling the third road immediately.Return the minimum number of skips required to arrive at the meeting on time, or -1
if it is impossible.
\n
Example 1:
\n\n\nInput: dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput: 1\nExplanation:\nWithout skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\n\n\n
Example 2:
\n\n\nInput: dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput: 2\nExplanation:\nWithout skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\n\n\n
Example 3:
\n\n\nInput: dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput: -1\nExplanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n\n\n
\n
Constraints:
\n\nn == dist.length
1 <= n <= 1000
1 <= dist[i] <= 105
1 <= speed <= 106
1 <= hoursBefore <= 107
You are given two identical eggs and you have access to a building with n
floors labeled from 1
to n
.
You know that there exists a floor f
where 0 <= f <= n
such that any egg dropped at a floor higher than f
will break, and any egg dropped at or below floor f
will not break.
In each move, you may take an unbroken egg and drop it from any floor x
(where 1 <= x <= n
). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f
is.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: 2\nExplanation: We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.\n\n\n
Example 2:
\n\n\nInput: n = 100\nOutput: 14\nExplanation: One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
Given two n x n
binary matrices mat
and target
, return true
if it is possible to make mat
equal to target
by rotating mat
in 90-degree increments, or false
otherwise.
\n
Example 1:
\n\nInput: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.\n\n\n
Example 2:
\n\nInput: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput: false\nExplanation: It is impossible to make mat equal to target by rotating mat.\n\n\n
Example 3:
\n\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.\n\n\n
\n
Constraints:
\n\nn == mat.length == target.length
n == mat[i].length == target[i].length
1 <= n <= 10
mat[i][j]
and target[i][j]
are either 0
or 1
.Given an integer array nums
, your goal is to make all elements in nums
equal. To complete one operation, follow these steps:
nums
. Let its index be i
(0-indexed) and its value be largest
. If there are multiple elements with the largest value, pick the smallest i
.nums
strictly smaller than largest
. Let its value be nextLargest
.nums[i]
to nextLargest
.Return the number of operations to make all elements in nums
equal.
\n
Example 1:
\n\n\nInput: nums = [5,1,3]\nOutput: 3\nExplanation: It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1]\nOutput: 0\nExplanation: All elements in nums are already equal.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,2,2,3]\nOutput: 4\nExplanation: It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
1 <= nums[i] <= 5 * 104
You are given a binary string s
. You are allowed to perform two types of operations on the string in any sequence:
s
and append it to the end of the string.s
and flip its value, i.e., if its value is '0'
it becomes '1'
and vice-versa.Return the minimum number of type-2 operations you need to perform such that s
becomes alternating.
The string is called alternating if no two adjacent characters are equal.
\n\n"010"
and "1010"
are alternating, while the string "0100"
is not.\n
Example 1:
\n\n\nInput: s = "111000"\nOutput: 2\nExplanation: Use the first operation two times to make s = "100011".\nThen, use the second operation on the third and sixth elements to make s = "101010".\n\n\n
Example 2:
\n\n\nInput: s = "010"\nOutput: 0\nExplanation: The string is already alternating.\n\n\n
Example 3:
\n\n\nInput: s = "1110"\nOutput: 1\nExplanation: Use the second operation on the second element to make s = "1010".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.You have n
packages that you are trying to place in boxes, one package in each box. There are m
suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.
The package sizes are given as an integer array packages
, where packages[i]
is the size of the ith
package. The suppliers are given as a 2D integer array boxes
, where boxes[j]
is an array of box sizes that the jth
supplier produces.
You want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package
. The total wasted space is the sum of the space wasted in all the boxes.
[2,3,5]
and the supplier offers boxes of sizes [4,8]
, you can fit the packages of size-2
and size-3
into two boxes of size-4
and the package with size-5
into a box of size-8
. This would result in a waste of (4-2) + (4-3) + (8-5) = 6
.Return the minimum total wasted space by choosing the box supplier optimally, or -1
if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput: 6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.\n\n\n
Example 2:
\n\n\nInput: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput: -1\nExplanation: There is no box that the package of size 5 can fit in.\n\n\n
Example 3:
\n\n\nInput: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput: 9\nExplanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n\n\n
\n
Constraints:
\n\nn == packages.length
m == boxes.length
1 <= n <= 105
1 <= m <= 105
1 <= packages[i] <= 105
1 <= boxes[j].length <= 105
1 <= boxes[j][k] <= 105
sum(boxes[j].length) <= 105
boxes[j]
are distinct.Table: Logins
\n+----------------+----------+\n| Column Name | Type |\n+----------------+----------+\n| user_id | int |\n| time_stamp | datetime |\n+----------------+----------+\n(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.\nEach row contains information about the login time for the user with ID user_id.\n\n\n
\n\n
Write a solution to report the latest login for all users in the year 2020
. Do not include the users who did not login in 2020
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nLogins table:\n+---------+---------------------+\n| user_id | time_stamp |\n+---------+---------------------+\n| 6 | 2020-06-30 15:06:07 |\n| 6 | 2021-04-21 14:06:06 |\n| 6 | 2019-03-07 00:18:15 |\n| 8 | 2020-02-01 05:10:53 |\n| 8 | 2020-12-30 00:46:50 |\n| 2 | 2020-01-16 02:49:50 |\n| 2 | 2019-08-25 07:59:08 |\n| 14 | 2019-07-14 09:00:00 |\n| 14 | 2021-01-06 11:59:59 |\n+---------+---------------------+\nOutput: \n+---------+---------------------+\n| user_id | last_stamp |\n+---------+---------------------+\n| 6 | 2020-06-30 15:06:07 |\n| 8 | 2020-12-30 00:46:50 |\n| 2 | 2020-01-16 02:49:50 |\n+---------+---------------------+\nExplanation: \nUser 6 logged into their account 3 times but only once in 2020, so we include this login in the result table.\nUser 8 logged into their account 2 times in 2020, once in February and once in December. We include only the latest one (December) in the result table.\nUser 2 logged into their account 2 times but only once in 2020, so we include this login in the result table.\nUser 14 did not login in 2020, so we do not include them in the result table.\n\n", - "likes": 426, - "dislikes": 15, - "stats": "{\"totalAccepted\": \"104.7K\", \"totalSubmission\": \"135.2K\", \"totalAcceptedRaw\": 104680, \"totalSubmissionRaw\": 135226, \"acRate\": \"77.4%\"}", + "likes": 442, + "dislikes": 16, + "stats": "{\"totalAccepted\": \"114.8K\", \"totalSubmission\": \"148.3K\", \"totalAcceptedRaw\": 114803, \"totalSubmissionRaw\": 148299, \"acRate\": \"77.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -71317,9 +71422,9 @@ "questionFrontendId": "1891", "title": "Cutting Ribbons", "content": null, - "likes": 605, - "dislikes": 56, - "stats": "{\"totalAccepted\": \"74.4K\", \"totalSubmission\": \"144.4K\", \"totalAcceptedRaw\": 74421, \"totalSubmissionRaw\": 144437, \"acRate\": \"51.5%\"}", + "likes": 619, + "dislikes": 67, + "stats": "{\"totalAccepted\": \"83.7K\", \"totalSubmission\": \"159.2K\", \"totalAcceptedRaw\": 83748, \"totalSubmissionRaw\": 159217, \"acRate\": \"52.6%\"}", "similarQuestions": "[{\"title\": \"Capacity To Ship Packages Within D Days\", \"titleSlug\": \"capacity-to-ship-packages-within-d-days\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Add Minimum Number of Rungs\", \"titleSlug\": \"add-minimum-number-of-rungs\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -71354,9 +71459,9 @@ "questionFrontendId": "1892", "title": "Page Recommendations II", "content": null, - "likes": 89, + "likes": 90, "dislikes": 23, - "stats": "{\"totalAccepted\": \"8.4K\", \"totalSubmission\": \"19K\", \"totalAcceptedRaw\": 8436, \"totalSubmissionRaw\": 19023, \"acRate\": \"44.3%\"}", + "stats": "{\"totalAccepted\": \"9.2K\", \"totalSubmission\": \"20.5K\", \"totalAcceptedRaw\": 9159, \"totalSubmissionRaw\": 20471, \"acRate\": \"44.7%\"}", "similarQuestions": "[{\"title\": \"Page Recommendations\", \"titleSlug\": \"page-recommendations\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Strong Friendship\", \"titleSlug\": \"strong-friendship\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -71382,9 +71487,9 @@ "questionFrontendId": "1893", "title": "Check if All the Integers in a Range Are Covered", "content": "
You are given a 2D integer array ranges
and two integers left
and right
. Each ranges[i] = [starti, endi]
represents an inclusive interval between starti
and endi
.
Return true
if each integer in the inclusive range [left, right]
is covered by at least one interval in ranges
. Return false
otherwise.
An integer x
is covered by an interval ranges[i] = [starti, endi]
if starti <= x <= endi
.
\n
Example 1:
\n\n\nInput: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput: true\nExplanation: Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.\n\n\n
Example 2:
\n\n\nInput: ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput: false\nExplanation: 21 is not covered by any range.\n\n\n
\n
Constraints:
\n\n1 <= ranges.length <= 50
1 <= starti <= endi <= 50
1 <= left <= right <= 50
There are n
students in a class numbered from 0
to n - 1
. The teacher will give each student a problem starting with the student number 0
, then the student number 1
, and so on until the teacher reaches the student number n - 1
. After that, the teacher will restart the process, starting with the student number 0
again.
You are given a 0-indexed integer array chalk
and an integer k
. There are initially k
pieces of chalk. When the student number i
is given a problem to solve, they will use chalk[i]
pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i]
, then the student number i
will be asked to replace the chalk.
Return the index of the student that will replace the chalk pieces.
\n\n\n
Example 1:
\n\n\nInput: chalk = [5,1,5], k = 22\nOutput: 0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.\n\n
Example 2:
\n\n\nInput: chalk = [3,4,1,2], k = 25\nOutput: 1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.\n\n\n
\n
Constraints:
\n\nchalk.length == n
1 <= n <= 105
1 <= chalk[i] <= 105
1 <= k <= 109
A k x k
magic square is a k x k
grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1
grid is trivially a magic square.
Given an m x n
integer grid
, return the size (i.e., the side length k
) of the largest magic square that can be found within this grid.
\n
Example 1:
\n\nInput: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput: 3\nExplanation: The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12\n\n\n
Example 2:
\n\nInput: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput: 2\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 106
You are given a valid boolean expression as a string expression
consisting of the characters '1'
,'0'
,'&'
(bitwise AND operator),'|'
(bitwise OR operator),'('
, and ')'
.
"()1|1"
and "(1)&()"
are not valid while "1"
, "(((1))|(0))"
, and "1|(0&(1))"
are valid expressions.Return the minimum cost to change the final value of the expression.
\n\nexpression = "1|1|(0&0)&1"
, its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1
. We want to apply operations so that the new expression evaluates to 0
.The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:
\n\n'1'
into a '0'
.'0'
into a '1'
.'&'
into a '|'
.'|'
into a '&'
.Note: '&'
does not take precedence over '|'
in the order of calculation. Evaluate parentheses first, then in left-to-right order.
\n
Example 1:
\n\n\nInput: expression = "1&(0|1)"\nOutput: 1\nExplanation: We can turn "1&(0|1)" into "1&(0&1)" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0. \n\n\n
Example 2:
\n\n\nInput: expression = "(0&0)&(0&0&0)"\nOutput: 3\nExplanation: We can turn "(0&0)&(0&0&0)" into "(0|1)|(0&0&0)" using 3 operations.\nThe new expression evaluates to 1.\n\n\n
Example 3:
\n\n\nInput: expression = "(0|(1|0&1))"\nOutput: 1\nExplanation: We can turn "(0|(1|0&1))" into "(0|(0|0&1))" using 1 operation.\nThe new expression evaluates to 0.\n\n
\n
Constraints:
\n\n1 <= expression.length <= 105
expression
only contains '1'
,'0'
,'&'
,'|'
,'('
, and ')'
"()"
is not a substring of expression
).You are given an array of strings words
(0-indexed).
In one operation, pick two distinct indices i
and j
, where words[i]
is a non-empty string, and move any character from words[i]
to any position in words[j]
.
Return true
if you can make every string in words
equal using any number of operations, and false
otherwise.
\n
Example 1:
\n\n\nInput: words = ["abc","aabc","bc"]\nOutput: true\nExplanation: Move the first 'a' in\n\nwords[1] to the front of words[2],\nto make
words[1]
= "abc" and words[2] = "abc".\nAll the strings are now equal to "abc", so returntrue
.\n
Example 2:
\n\n\nInput: words = ["ab","a"]\nOutput: false\nExplanation: It is impossible to make all the strings equal using the operation.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists of lowercase English letters.You are given two strings s
and p
where p
is a subsequence of s
. You are also given a distinct 0-indexed integer array removable
containing a subset of indices of s
(s
is also 0-indexed).
You want to choose an integer k
(0 <= k <= removable.length
) such that, after removing k
characters from s
using the first k
indices in removable
, p
is still a subsequence of s
. More formally, you will mark the character at s[removable[i]]
for each 0 <= i < k
, then remove all marked characters and check if p
is still a subsequence.
Return the maximum k
you can choose such that p
is still a subsequence of s
after the removals.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
\n\n\n
Example 1:
\n\n\nInput: s = "abcacb", p = "ab", removable = [3,1,0]\nOutput: 2\nExplanation: After removing the characters at indices 3 and 1, "a\n\nbcacb" becomes "accb".\n"ab" is a subsequence of "accb".\nIf we remove the characters at indices 3, 1, and 0, "abcacb" becomes "ccb", and "ab" is no longer a subsequence.\nHence, the maximum k is 2.\n
Example 2:
\n\n\nInput: s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]\nOutput: 1\nExplanation: After removing the character at index 3, "abc\n\nbddddd" becomes "abcddddd".\n"abcd" is a subsequence of "abcddddd".\n
Example 3:
\n\n\nInput: s = "abcab", p = "abc", removable = [0,1,2,3,4]\nOutput: 0\nExplanation: If you remove the first index in the array removable, "abc" is no longer a subsequence.\n\n\n
\n
Constraints:
\n\n1 <= p.length <= s.length <= 105
0 <= removable.length < s.length
0 <= removable[i] < s.length
p
is a subsequence of s
.s
and p
both consist of lowercase English letters.removable
are distinct.A triplet is an array of three integers. You are given a 2D integer array triplets
, where triplets[i] = [ai, bi, ci]
describes the ith
triplet. You are also given an integer array target = [x, y, z]
that describes the triplet you want to obtain.
To obtain target
, you may apply the following operation on triplets
any number of times (possibly zero):
i
and j
(i != j
) and update triplets[j]
to become [max(ai, aj), max(bi, bj), max(ci, cj)]
.\n\n\ttriplets[i] = [2, 5, 3]
and triplets[j] = [1, 7, 5]
, triplets[j]
will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5]
.Return true
if it is possible to obtain the target
triplet [x, y, z]
as an element of triplets
, or false
otherwise.
\n
Example 1:
\n\n\nInput: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\nThe target triplet [2,7,5] is now an element of triplets.\n\n\n
Example 2:
\n\n\nInput: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\nOutput: false\nExplanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\n\n\n
Example 3:
\n\n\nInput: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\nThe target triplet [5,5,5] is now an element of triplets.\n\n\n
\n
Constraints:
\n\n1 <= triplets.length <= 105
triplets[i].length == target.length == 3
1 <= ai, bi, ci, x, y, z <= 1000
There is a tournament where n
players are participating. The players are standing in a single row and are numbered from 1
to n
based on their initial standing position (player 1
is the first player in the row, player 2
is the second player in the row, etc.).
The tournament consists of multiple rounds (starting from round number 1
). In each round, the ith
player from the front of the row competes against the ith
player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.
1, 2, 4, 6, 7
\n\n\t1
competes against player 7
.2
competes against player 6
.4
automatically advances to the next round.After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).
\n\nThe players numbered firstPlayer
and secondPlayer
are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.
Given the integers n
, firstPlayer
, and secondPlayer
, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
\n
Example 1:
\n\n\nInput: n = 11, firstPlayer = 2, secondPlayer = 4\nOutput: [3,4]\nExplanation:\nOne possible scenario which leads to the earliest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 2, 3, 4, 5, 6, 11\nThird round: 2, 3, 4\nOne possible scenario which leads to the latest round number:\nFirst round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\nSecond round: 1, 2, 3, 4, 5, 6\nThird round: 1, 2, 4\nFourth round: 2, 4\n\n\n
Example 2:
\n\n\nInput: n = 5, firstPlayer = 1, secondPlayer = 5\nOutput: [1,1]\nExplanation: The players numbered 1 and 5 compete in the first round.\nThere is no way to make them compete in any other round.\n\n\n
\n
Constraints:
\n\n2 <= n <= 28
1 <= firstPlayer < secondPlayer <= n
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.
\n\nGiven a 0-indexed m x n
matrix mat
where no two adjacent cells are equal, find any peak element mat[i][j]
and return the length 2 array [i,j]
.
You may assume that the entire matrix is surrounded by an outer perimeter with the value -1
in each cell.
You must write an algorithm that runs in O(m log(n))
or O(n log(m))
time.
\n
Example 1:
\n\n\nInput: mat = [[1,4],[3,2]]\nOutput: [0,1]\nExplanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.\n\n\n
Example 2:
\n\n\nInput: mat = [[10,20,15],[21,30,14],[7,16,32]]\nOutput: [1,1]\nExplanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 500
1 <= mat[i][j] <= 105
You are given a string num
, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num
, or an empty string ""
if no odd integer exists.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: num = "52"\nOutput: "5"\nExplanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.\n\n\n
Example 2:
\n\n\nInput: num = "4206"\nOutput: ""\nExplanation: There are no odd numbers in "4206".\n\n\n
Example 3:
\n\n\nInput: num = "35427"\nOutput: "35427"\nExplanation: "35427" is already an odd number.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 105
num
only consists of digits and does not contain any leading zeros.You are participating in an online chess tournament. There is a chess round that starts every 15
minutes. The first round of the day starts at 00:00
, and after every 15
minutes, a new round starts.
00:15
, the fourth round starts at 00:45
, and the seventh round starts at 01:30
.You are given two strings loginTime
and logoutTime
where:
loginTime
is the time you will login to the game, andlogoutTime
is the time you will logout from the game.If logoutTime
is earlier than loginTime
, this means you have played from loginTime
to midnight and from midnight to logoutTime
.
Return the number of full chess rounds you have played in the tournament.
\n\nNote: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00
and the last round of the day starts at 23:45
.
\n
Example 1:
\n\n\nInput: loginTime = "09:31", logoutTime = "10:14"\nOutput: 1\nExplanation: You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.\n\n\n
Example 2:
\n\n\nInput: loginTime = "21:30", logoutTime = "03:00"\nOutput: 22\nExplanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.\n\n\n
\n
Constraints:
\n\nloginTime
and logoutTime
are in the format hh:mm
.00 <= hh <= 23
00 <= mm <= 59
loginTime
and logoutTime
are not equal.You are given two m x n
binary matrices grid1
and grid2
containing only 0
's (representing water) and 1
's (representing land). An island is a group of 1
's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.
An island in grid2
is considered a sub-island if there is an island in grid1
that contains all the cells that make up this island in grid2
.
Return the number of islands in grid2
that are considered sub-islands.
\n
Example 1:
\n\nInput: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]\nOutput: 3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\n\n\n
Example 2:
\n\nInput: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]\nOutput: 2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n\n\n
\n
Constraints:
\n\nm == grid1.length == grid2.length
n == grid1[i].length == grid2[i].length
1 <= m, n <= 500
grid1[i][j]
and grid2[i][j]
are either 0
or 1
.The minimum absolute difference of an array a
is defined as the minimum value of |a[i] - a[j]|
, where 0 <= i < j < a.length
and a[i] != a[j]
. If all elements of a
are the same, the minimum absolute difference is -1
.
[5,2,3,7,2]
is |2 - 3| = 1
. Note that it is not 0
because a[i]
and a[j]
must be different.You are given an integer array nums
and the array queries
where queries[i] = [li, ri]
. For each query i
, compute the minimum absolute difference of the subarray nums[li...ri]
containing the elements of nums
between the 0-based indices li
and ri
(inclusive).
Return an array ans
where ans[i]
is the answer to the ith
query.
A subarray is a contiguous sequence of elements in an array.
\n\nThe value of |x|
is defined as:
x
if x >= 0
.-x
if x < 0
.\n
Example 1:
\n\n\nInput: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput: [2,1,4,1]\nExplanation: The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.\n\n\n
Example 2:
\n\n\nInput: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput: [-1,1,1,3]\nExplanation: The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 100
1 <= queries.length <= 2 * 104
0 <= li < ri < nums.length
Table: Accounts
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| account_id | int |\n| income | int |\n+-------------+------+\naccount_id is the primary key (column with unique values) for this table.\nEach row contains information about the monthly income for one bank account.\n\n\n
\n\n
Write a solution to calculate the number of bank accounts for each salary category. The salary categories are:
\n\n"Low Salary"
: All the salaries strictly less than $20000
."Average Salary"
: All the salaries in the inclusive range [$20000, $50000]
."High Salary"
: All the salaries strictly greater than $50000
.The result table must contain all three categories. If there are no accounts in a category, return 0
.
Return the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nAccounts table:\n+------------+--------+\n| account_id | income |\n+------------+--------+\n| 3 | 108939 |\n| 2 | 12747 |\n| 8 | 87709 |\n| 6 | 91796 |\n+------------+--------+\nOutput: \n+----------------+----------------+\n| category | accounts_count |\n+----------------+----------------+\n| Low Salary | 1 |\n| Average Salary | 0 |\n| High Salary | 3 |\n+----------------+----------------+\nExplanation: \nLow Salary: Account 2.\nAverage Salary: No accounts.\nHigh Salary: Accounts 3, 6, and 8.\n\n", - "likes": 526, - "dislikes": 94, - "stats": "{\"totalAccepted\": \"171.6K\", \"totalSubmission\": \"277.6K\", \"totalAcceptedRaw\": 171590, \"totalSubmissionRaw\": 277556, \"acRate\": \"61.8%\"}", + "likes": 587, + "dislikes": 100, + "stats": "{\"totalAccepted\": \"212.5K\", \"totalSubmission\": \"340.2K\", \"totalAcceptedRaw\": 212545, \"totalSubmissionRaw\": 340250, \"acRate\": \"62.5%\"}", "similarQuestions": "[{\"title\": \"Create a Session Bar Chart\", \"titleSlug\": \"create-a-session-bar-chart\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Database", "hints": [], @@ -71956,8 +72061,8 @@ "title": "Game of Nim", "content": null, "likes": 102, - "dislikes": 39, - "stats": "{\"totalAccepted\": \"4.7K\", \"totalSubmission\": \"7.5K\", \"totalAcceptedRaw\": 4740, \"totalSubmissionRaw\": 7521, \"acRate\": \"63.0%\"}", + "dislikes": 40, + "stats": "{\"totalAccepted\": \"4.9K\", \"totalSubmission\": \"7.8K\", \"totalAcceptedRaw\": 4917, \"totalSubmissionRaw\": 7847, \"acRate\": \"62.7%\"}", "similarQuestions": "[{\"title\": \"Subtree Removal Game with Fibonacci Tree\", \"titleSlug\": \"subtree-removal-game-with-fibonacci-tree\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -72003,9 +72108,9 @@ "questionFrontendId": "1909", "title": "Remove One Element to Make the Array Strictly Increasing", "content": "
Given a 0-indexed integer array nums
, return true
if it can be made strictly increasing after removing exactly one element, or false
otherwise. If the array is already strictly increasing, return true
.
The array nums
is strictly increasing if nums[i - 1] < nums[i]
for each index (1 <= i < nums.length).
\n
Example 1:
\n\n\nInput: nums = [1,2,10,5,7]\nOutput: true\nExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,1,2]\nOutput: false\nExplanation:\n[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.\n\n
Example 3:
\n\n\nInput: nums = [1,1,1]\nOutput: false\nExplanation: The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 1000
1 <= nums[i] <= 1000
Given two strings s
and part
, perform the following operation on s
until all occurrences of the substring part
are removed:
part
and remove it from s
.Return s
after removing all occurrences of part
.
A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: s = "daabcbaabcbc", part = "abc"\nOutput: "dab"\nExplanation: The following operations are done:\n- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".\n- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".\n- s = "dababc", remove "abc" starting at index 3, so s = "dab".\nNow s has no occurrences of "abc".\n\n\n
Example 2:
\n\n\nInput: s = "axxxxyyyyb", part = "xy"\nOutput: "ab"\nExplanation: The following operations are done:\n- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".\n- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".\n- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".\n- s = "axyb", remove "xy" starting at index 1 so s = "ab".\nNow s has no occurrences of "xy".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
1 <= part.length <= 1000
s
\u200b\u200b\u200b\u200b\u200b\u200b and part
consists of lowercase English letters.The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
\r\n\r\n[4,2,5,3]
is (4 + 5) - (2 + 3) = 4
.Given an array nums
, return the maximum alternating sum of any subsequence of nums
(after reindexing the elements of the subsequence).
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4]
is a subsequence of [4,2,3,7,2,1,4]
(the underlined elements), while [2,4,2]
is not.
\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [4,2,5,3]\r\nOutput: 7\r\nExplanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [5,6,7,8]\r\nOutput: 8\r\nExplanation: It is optimal to choose the subsequence [8] with alternating sum 8.\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: nums = [6,2,1,2,4,5]\r\nOutput: 10\r\nExplanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= nums.length <= 105
1 <= nums[i] <= 105
You have a movie renting company consisting of n
shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.
Each movie is given as a 2D integer array entries
where entries[i] = [shopi, moviei, pricei]
indicates that there is a copy of movie moviei
at shop shopi
with a rental price of pricei
. Each shop carries at most one copy of a movie moviei
.
The system should support the following functions:
\n\nshopi
should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.res
where res[j] = [shopj, moviej]
describes that the jth
cheapest rented movie moviej
was rented from the shop shopj
. The movies in res
should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj
should appear first, and if there is still tie, the one with the smaller moviej
should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.Implement the MovieRentingSystem
class:
MovieRentingSystem(int n, int[][] entries)
Initializes the MovieRentingSystem
object with n
shops and the movies in entries
.List<Integer> search(int movie)
Returns a list of shops that have an unrented copy of the given movie
as described above.void rent(int shop, int movie)
Rents the given movie
from the given shop
.void drop(int shop, int movie)
Drops off a previously rented movie
at the given shop
.List<List<Integer>> report()
Returns a list of cheapest rented movies as described above.Note: The test cases will be generated such that rent
will only be called if the shop has an unrented copy of the movie, and drop
will only be called if the shop had previously rented out the movie.
\n
Example 1:
\n\n\nInput\n["MovieRentingSystem", "search", "rent", "rent", "report", "drop", "search"]\n[[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]\nOutput\n[null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]\n\nExplanation\nMovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\nmovieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\nmovieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\nmovieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\nmovieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\nmovieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\nmovieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 3 * 105
1 <= entries.length <= 105
0 <= shopi < n
1 <= moviei, pricei <= 104
moviei
.105
calls in total will be made to search
, rent
, drop
and report
.The product difference between two pairs (a, b)
and (c, d)
is defined as (a * b) - (c * d)
.
(5, 6)
and (2, 7)
is (5 * 6) - (2 * 7) = 16
.Given an integer array nums
, choose four distinct indices w
, x
, y
, and z
such that the product difference between pairs (nums[w], nums[x])
and (nums[y], nums[z])
is maximized.
Return the maximum such product difference.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: nums = [5,6,2,7,4]\r\nOutput: 34\r\nExplanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\r\nThe product difference is (6 * 7) - (2 * 4) = 34.\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: nums = [4,2,5,9,7,4,8]\r\nOutput: 64\r\nExplanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\r\nThe product difference is (9 * 8) - (2 * 4) = 64.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n4 <= nums.length <= 104
1 <= nums[i] <= 104
You are given an m x n
integer matrix grid
\u200b\u200b\u200b, where m
and n
are both even integers, and an integer k
.
The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:
\r\n\r\nA cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:
\r\nReturn the matrix after applying k
cyclic rotations to it.
\r\n
Example 1:
\r\n\r\nInput: grid = [[40,10],[30,20]], k = 1\r\nOutput: [[10,20],[40,30]]\r\nExplanation: The figures above represent the grid at every state.\r\n\r\n\r\n
Example 2:
\r\n\r\nInput: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\r\nOutput: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\r\nExplanation: The figures above represent the grid at every state.\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\nm == grid.length
n == grid[i].length
2 <= m, n <= 50
m
and n
are even integers.1 <= grid[i][j] <= 5000
1 <= k <= 109
A wonderful string is a string where at most one letter appears an odd number of times.
\r\n\r\n"ccjjc"
and "abab"
are wonderful, but "ab"
is not.Given a string word
that consists of the first ten lowercase English letters ('a'
through 'j'
), return the number of wonderful non-empty substrings in word
. If the same substring appears multiple times in word
, then count each occurrence separately.
A substring is a contiguous sequence of characters in a string.
\r\n\r\n\r\n
Example 1:
\r\n\r\n\r\nInput: word = "aba"\r\nOutput: 4\r\nExplanation: The four wonderful substrings are underlined below:\r\n- "aba" -> "a"\r\n- "aba" -> "b"\r\n- "aba" -> "a"\r\n- "aba" -> "aba"\r\n\r\n\r\n
Example 2:
\r\n\r\n\r\nInput: word = "aabb"\r\nOutput: 9\r\nExplanation: The nine wonderful substrings are underlined below:\r\n- "aabb" -> "a"\r\n- "aabb" -> "aa"\r\n- "aabb" -> "aab"\r\n- "aabb" -> "aabb"\r\n- "aabb" -> "a"\r\n- "aabb" -> "abb"\r\n- "aabb" -> "b"\r\n- "aabb" -> "bb"\r\n- "aabb" -> "b"\r\n\r\n\r\n
Example 3:
\r\n\r\n\r\nInput: word = "he"\r\nOutput: 2\r\nExplanation: The two wonderful substrings are underlined below:\r\n- "he" -> "h"\r\n- "he" -> "e"\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\n1 <= word.length <= 105
word
consists of lowercase English letters from 'a'
to 'j'
.You are an ant tasked with adding n
new rooms numbered 0
to n-1
to your colony. You are given the expansion plan as a 0-indexed integer array of length n
, prevRoom
, where prevRoom[i]
indicates that you must build room prevRoom[i]
before building room i
, and these two rooms must be connected directly. Room 0
is already built, so prevRoom[0] = -1
. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0
.
You can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.
\r\n\r\nReturn the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7
.
\r\n
Example 1:
\r\n\r\nInput: prevRoom = [-1,0,1]\r\nOutput: 1\r\nExplanation: There is only one way to build the additional rooms: 0 → 1 → 2\r\n\r\n\r\n
Example 2:
\r\n\r\nInput: prevRoom = [-1,0,0,1,2]\r\nOutput: 6\r\nExplanation:\r\nThe 6 ways are:\r\n0 → 1 → 3 → 2 → 4\r\n0 → 2 → 4 → 1 → 3\r\n0 → 1 → 2 → 3 → 4\r\n0 → 1 → 2 → 4 → 3\r\n0 → 2 → 1 → 3 → 4\r\n0 → 2 → 1 → 4 → 3\r\n\r\n\r\n
\r\n
Constraints:
\r\n\r\nn == prevRoom.length
2 <= n <= 105
prevRoom[0] == -1
0 <= prevRoom[i] < n
for all 1 <= i < n
0
once all the rooms are built.Given a zero-based permutation nums
(0-indexed), build an array ans
of the same length where ans[i] = nums[nums[i]]
for each 0 <= i < nums.length
and return it.
A zero-based permutation nums
is an array of distinct integers from 0
to nums.length - 1
(inclusive).
\n
Example 1:
\n\n\nInput: nums = [0,2,1,5,3,4]\nOutput: [0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]\n\n
Example 2:
\n\n\nInput: nums = [5,0,1,2,3,4]\nOutput: [4,5,0,1,2,3]\nExplanation: The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] < nums.length
nums
are distinct.\n
Follow-up: Can you solve it without using an extra space (i.e., O(1)
memory)?
You are playing a video game where you are defending your city from a group of n
monsters. You are given a 0-indexed integer array dist
of size n
, where dist[i]
is the initial distance in kilometers of the ith
monster from the city.
The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed
of size n
, where speed[i]
is the speed of the ith
monster in kilometers per minute.
You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.
\n\nYou lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.
\n\nReturn the maximum number of monsters that you can eliminate before you lose, or n
if you can eliminate all the monsters before they reach the city.
\n
Example 1:
\n\n\nInput: dist = [1,3,4], speed = [1,1,1]\nOutput: 3\nExplanation:\nIn the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.\nAll 3 monsters can be eliminated.\n\n
Example 2:
\n\n\nInput: dist = [1,1,2,3], speed = [1,1,1,1]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.\n\n\n
Example 3:
\n\n\nInput: dist = [3,2,4], speed = [5,3,2]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.\n\n\n
\n
Constraints:
\n\nn == dist.length == speed.length
1 <= n <= 105
1 <= dist[i], speed[i] <= 105
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2
, 3
, 5
, or 7
).
"2582"
is good because the digits (2
and 8
) at even positions are even and the digits (5
and 2
) at odd positions are prime. However, "3245"
is not good because 3
is at an even index but is not even.Given an integer n
, return the total number of good digit strings of length n
. Since the answer may be large, return it modulo 109 + 7
.
A digit string is a string consisting of digits 0
through 9
that may contain leading zeros.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are "0", "2", "4", "6", "8".\n\n\n
Example 2:
\n\n\nInput: n = 4\nOutput: 400\n\n\n
Example 3:
\n\n\nInput: n = 50\nOutput: 564908303\n\n\n
\n
Constraints:
\n\n1 <= n <= 1015
There is a country of n
cities numbered from 0
to n - 1
. In this country, there is a road connecting every pair of cities.
There are m
friends numbered from 0
to m - 1
who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.
Given an integer n
and a 2D integer array paths
where paths[i]
is an integer array representing the path of the ith
friend, return the length of the longest common subpath that is shared by every friend's path, or 0
if there is no common subpath at all.
A subpath of a path is a contiguous sequence of cities within that path.
\n\n\n
Example 1:
\n\n\nInput: n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]\nOutput: 2\nExplanation: The longest common subpath is [2,3].\n\n\n
Example 2:
\n\n\nInput: n = 3, paths = [[0],[1],[2]]\nOutput: 0\nExplanation: There is no common subpath shared by the three paths.\n\n\n
Example 3:
\n\n\nInput: n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]\nOutput: 1\nExplanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.\n\n
\n
Constraints:
\n\n1 <= n <= 105
m == paths.length
2 <= m <= 105
sum(paths[i].length) <= 105
0 <= paths[i][j] < n
paths[i]
.A square triple (a,b,c)
is a triple where a
, b
, and c
are integers and a2 + b2 = c2
.
Given an integer n
, return the number of square triples such that 1 <= a, b, c <= n
.
\n
Example 1:
\n\n\nInput: n = 5\nOutput: 2\nExplanation: The square triples are (3,4,5) and (4,3,5).\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: 4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).\n\n\n
\n
Constraints:
\n\n1 <= n <= 250
You are given an m x n
matrix maze
(0-indexed) with empty cells (represented as '.'
) and walls (represented as '+'
). You are also given the entrance
of the maze, where entrance = [entrancerow, entrancecol]
denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance
. An exit is defined as an empty cell that is at the border of the maze
. The entrance
does not count as an exit.
Return the number of steps in the shortest path from the entrance
to the nearest exit, or -1
if no such path exists.
\n
Example 1:
\n\nInput: maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\n\n\n
Example 2:
\n\nInput: maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\n\n\n
Example 3:
\n\nInput: maze = [[".","+"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n\n\n
\n
Constraints:
\n\nmaze.length == m
maze[i].length == n
1 <= m, n <= 100
maze[i][j]
is either '.'
or '+'
.entrance.length == 2
0 <= entrancerow < m
0 <= entrancecol < n
entrance
will always be an empty cell.Alice and Bob take turns playing a game, with Alice starting first.
\n\nYou are given a string num
of even length consisting of digits and '?'
characters. On each turn, a player will do the following if there is still at least one '?'
in num
:
i
where num[i] == '?'
.num[i]
with any digit between '0'
and '9'
.The game ends when there are no more '?'
characters in num
.
For Bob to win, the sum of the digits in the first half of num
must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.
num = "243801"
, then Bob wins because 2+4+3 = 8+0+1
. If the game ended with num = "243803"
, then Alice wins because 2+4+3 != 8+0+3
.Assuming Alice and Bob play optimally, return true
if Alice will win and false
if Bob will win.
\n
Example 1:
\n\n\nInput: num = "5023"\nOutput: false\nExplanation: There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.\n\n\n
Example 2:
\n\n\nInput: num = "25??"\nOutput: true\nExplanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.\n\n\n
Example 3:
\n\n\nInput: num = "?3295???"\nOutput: false\nExplanation: It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = "93295???".\n- Bob replaces one of the '?' in the right half with '9'. num = "932959??".\n- Alice replaces one of the '?' in the right half with '2'. num = "9329592?".\n- Bob replaces the last '?' in the right half with '7'. num = "93295927".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.\n\n\n
\n
Constraints:
\n\n2 <= num.length <= 105
num.length
is even.num
consists of only digits and '?'
.There is a country of n
cities numbered from 0
to n - 1
where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges
where edges[i] = [xi, yi, timei]
denotes a road between cities xi
and yi
that takes timei
minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees
of length n
where passingFees[j]
is the amount of dollars you must pay when you pass through city j
.
In the beginning, you are at city 0
and want to reach city n - 1
in maxTime
minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).
Given maxTime
, edges
, and passingFees
, return the minimum cost to complete your journey, or -1
if you cannot complete it within maxTime
minutes.
\n
Example 1:
\n\n\nInput: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 11\nExplanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.\n\n\n
Example 2:
\n\n\nInput: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 48\nExplanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.\n\n\n
Example 3:
\n\n\nInput: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: -1\nExplanation: There is no way to reach city 5 from city 0 within 25 minutes.\n\n\n
\n
Constraints:
\n\n1 <= maxTime <= 1000
n == passingFees.length
2 <= n <= 1000
n - 1 <= edges.length <= 1000
0 <= xi, yi <= n - 1
1 <= timei <= 1000
1 <= passingFees[j] <= 1000
Given an integer array nums
of length n
, you want to create an array ans
of length 2n
where ans[i] == nums[i]
and ans[i + n] == nums[i]
for 0 <= i < n
(0-indexed).
Specifically, ans
is the concatenation of two nums
arrays.
Return the array ans
.
\n
Example 1:
\n\n\nInput: nums = [1,2,1]\nOutput: [1,2,1,1,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]\n\n
Example 2:
\n\n\nInput: nums = [1,3,2,1]\nOutput: [1,3,2,1,1,3,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
Given a string s
, return the number of unique palindromes of length three that are a subsequence of s
.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
\n\nA palindrome is a string that reads the same forwards and backwards.
\n\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
\n\n"ace"
is a subsequence of "abcde"
.\n
Example 1:
\n\n\nInput: s = "aabca"\nOutput: 3\nExplanation: The 3 palindromic subsequences of length 3 are:\n- "aba" (subsequence of "aabca")\n- "aaa" (subsequence of "aabca")\n- "aca" (subsequence of "aabca")\n\n\n
Example 2:
\n\n\nInput: s = "adc"\nOutput: 0\nExplanation: There are no palindromic subsequences of length 3 in "adc".\n\n\n
Example 3:
\n\n\nInput: s = "bbcbaba"\nOutput: 4\nExplanation: The 4 palindromic subsequences of length 3 are:\n- "bbb" (subsequence of "bbcbaba")\n- "bcb" (subsequence of "bbcbaba")\n- "bab" (subsequence of "bbcbaba")\n- "aba" (subsequence of "bbcbaba")\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 105
s
consists of only lowercase English letters.You are given two integers m
and n
. Consider an m x n
grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: m = 1, n = 1\nOutput: 3\nExplanation: The three possible colorings are shown in the image above.\n\n\n
Example 2:
\n\nInput: m = 1, n = 2\nOutput: 6\nExplanation: The six possible colorings are shown in the image above.\n\n\n
Example 3:
\n\n\nInput: m = 5, n = 5\nOutput: 580986\n\n\n
\n
Constraints:
\n\n1 <= m <= 5
1 <= n <= 1000
You are given n
BST (binary search tree) root nodes for n
separate BSTs stored in an array trees
(0-indexed). Each BST in trees
has at most 3 nodes, and no two roots have the same value. In one operation, you can:
i
and j
such that the value stored at one of the leaves of trees[i]
is equal to the root value of trees[j]
.trees[i]
with trees[j]
.trees[j]
from trees
.Return the root of the resulting BST if it is possible to form a valid BST after performing n - 1
operations, or null
if it is impossible to create a valid BST.
A BST (binary search tree) is a binary tree where each node satisfies the following property:
\n\nA leaf is a node that has no children.
\n\n\n
Example 1:
\n\nInput: trees = [[2,1],[3,2,5],[5,4]]\nOutput: [3,2,5,1,null,4]\nExplanation:\nIn the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].\n\n\n\nIn the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].\n
\nThe resulting tree, shown above, is a valid BST, so return its root.
Example 2:
\n\nInput: trees = [[5,3,8],[3,2,6]]\nOutput: []\nExplanation:\nPick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].\n\n\n\nThe resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.\n
Example 3:
\n\nInput: trees = [[5,4],[3]]\nOutput: []\nExplanation: It is impossible to perform any operations.\n\n\n
\n
Constraints:
\n\nn == trees.length
1 <= n <= 5 * 104
[1, 3]
.trees
have the same value.1 <= TreeNode.val <= 5 * 104
.Table: Signups
\n+----------------+----------+\n| Column Name | Type |\n+----------------+----------+\n| user_id | int |\n| time_stamp | datetime |\n+----------------+----------+\nuser_id is the column of unique values for this table.\nEach row contains information about the signup time for the user with ID user_id.\n\n\n
\n\n
Table: Confirmations
\n+----------------+----------+\n| Column Name | Type |\n+----------------+----------+\n| user_id | int |\n| time_stamp | datetime |\n| action | ENUM |\n+----------------+----------+\n(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.\nuser_id is a foreign key (reference column) to the Signups table.\naction is an ENUM (category) of the type ('confirmed', 'timeout')\nEach row of this table indicates that the user with ID user_id requested a confirmation message at time_stamp and that confirmation message was either confirmed ('confirmed') or expired without confirming ('timeout').\n\n\n
\n\n
The confirmation rate of a user is the number of 'confirmed'
messages divided by the total number of requested confirmation messages. The confirmation rate of a user that did not request any confirmation messages is 0
. Round the confirmation rate to two decimal places.
Write a solution to find the confirmation rate of each user.
\n\nReturn the result table in any order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nSignups table:\n+---------+---------------------+\n| user_id | time_stamp |\n+---------+---------------------+\n| 3 | 2020-03-21 10:16:13 |\n| 7 | 2020-01-04 13:57:59 |\n| 2 | 2020-07-29 23:09:44 |\n| 6 | 2020-12-09 10:39:37 |\n+---------+---------------------+\nConfirmations table:\n+---------+---------------------+-----------+\n| user_id | time_stamp | action |\n+---------+---------------------+-----------+\n| 3 | 2021-01-06 03:30:46 | timeout |\n| 3 | 2021-07-14 14:00:00 | timeout |\n| 7 | 2021-06-12 11:57:29 | confirmed |\n| 7 | 2021-06-13 12:58:28 | confirmed |\n| 7 | 2021-06-14 13:59:27 | confirmed |\n| 2 | 2021-01-22 00:00:00 | confirmed |\n| 2 | 2021-02-28 23:59:59 | timeout |\n+---------+---------------------+-----------+\nOutput: \n+---------+-------------------+\n| user_id | confirmation_rate |\n+---------+-------------------+\n| 6 | 0.00 |\n| 3 | 0.00 |\n| 7 | 1.00 |\n| 2 | 0.50 |\n+---------+-------------------+\nExplanation: \nUser 6 did not request any confirmation messages. The confirmation rate is 0.\nUser 3 made 2 requests and both timed out. The confirmation rate is 0.\nUser 7 made 3 requests and all were confirmed. The confirmation rate is 1.\nUser 2 made 2 requests where one was confirmed and the other timed out. The confirmation rate is 1 / 2 = 0.5.\n\n", - "likes": 1110, - "dislikes": 100, - "stats": "{\"totalAccepted\": \"352.5K\", \"totalSubmission\": \"583.2K\", \"totalAcceptedRaw\": 352542, \"totalSubmissionRaw\": 583234, \"acRate\": \"60.4%\"}", + "likes": 1270, + "dislikes": 117, + "stats": "{\"totalAccepted\": \"435.1K\", \"totalSubmission\": \"713.8K\", \"totalAcceptedRaw\": 435063, \"totalSubmissionRaw\": 713833, \"acRate\": \"60.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -72959,9 +73073,9 @@ "questionFrontendId": "1935", "title": "Maximum Number of Words You Can Type", "content": "
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.
\n\nGiven a string text
of words separated by a single space (no leading or trailing spaces) and a string brokenLetters
of all distinct letter keys that are broken, return the number of words in text
you can fully type using this keyboard.
\n
Example 1:
\n\n\nInput: text = "hello world", brokenLetters = "ad"\nOutput: 1\nExplanation: We cannot type "world" because the 'd' key is broken.\n\n\n
Example 2:
\n\n\nInput: text = "leet code", brokenLetters = "lt"\nOutput: 1\nExplanation: We cannot type "leet" because the 'l' and 't' keys are broken.\n\n\n
Example 3:
\n\n\nInput: text = "leet code", brokenLetters = "e"\nOutput: 0\nExplanation: We cannot type either word because the 'e' key is broken.\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 104
0 <= brokenLetters.length <= 26
text
consists of words separated by a single space without any leading or trailing spaces.brokenLetters
consists of distinct lowercase English letters.You are given a strictly increasing integer array rungs
that represents the height of rungs on a ladder. You are currently on the floor at height 0
, and you want to reach the last rung.
You are also given an integer dist
. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist
. You are able to insert rungs at any positive integer height if a rung is not already there.
Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.
\n\n\n
Example 1:
\n\n\nInput: rungs = [1,3,5,10], dist = 2\nOutput: 2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].\n\n\n
Example 2:
\n\n\nInput: rungs = [3,6,8,10], dist = 3\nOutput: 0\nExplanation:\nThis ladder can be climbed without adding additional rungs.\n\n\n
Example 3:
\n\n\nInput: rungs = [3,4,6,7], dist = 2\nOutput: 1\nExplanation:\nYou currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].\n\n\n
\n
Constraints:
\n\n1 <= rungs.length <= 105
1 <= rungs[i] <= 109
1 <= dist <= 109
rungs
is strictly increasing.You are given an m x n
integer matrix points
(0-indexed). Starting with 0
points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c)
will add points[r][c]
to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r
and r + 1
(where 0 <= r < m - 1
), picking cells at coordinates (r, c1)
and (r + 1, c2)
will subtract abs(c1 - c2)
from your score.
Return the maximum number of points you can achieve.
\n\nabs(x)
is defined as:
x
for x >= 0
.-x
for x < 0
.\n
Example 1:
\n\nInput: points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput: 9\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.\n\n\n
Example 2:
\n\nInput: points = [[1,5],[2,3],[4,2]]\nOutput: 11\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.\n\n\n
\n
Constraints:
\n\nm == points.length
n == points[r].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= points[r][c] <= 105
There is a rooted tree consisting of n
nodes numbered 0
to n - 1
. Each node's number denotes its unique genetic value (i.e. the genetic value of node x
is x
). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents
, where parents[i]
is the parent for node i
. If node x
is the root of the tree, then parents[x] == -1
.
You are also given the array queries
where queries[i] = [nodei, vali]
. For each query i
, find the maximum genetic difference between vali
and pi
, where pi
is the genetic value of any node that is on the path between nodei
and the root (including nodei
and the root). More formally, you want to maximize vali XOR pi
.
Return an array ans
where ans[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]\nOutput: [2,3,7]\nExplanation: The queries are processed as follows:\n- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n\n\n
Example 2:
\n\nInput: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]\nOutput: [6,14,7]\nExplanation: The queries are processed as follows:\n- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n\n\n
\n
Constraints:
\n\n2 <= parents.length <= 105
0 <= parents[i] <= parents.length - 1
for every node i
that is not the root.parents[root] == -1
1 <= queries.length <= 3 * 104
0 <= nodei <= parents.length - 1
0 <= vali <= 2 * 105
Given a string s
, return true
if s
is a good string, or false
otherwise.
A string s
is good if all the characters that appear in s
have the same number of occurrences (i.e., the same frequency).
\n
Example 1:
\n\n\nInput: s = "abacbc"\nOutput: true\nExplanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.\n\n\n
Example 2:
\n\n\nInput: s = "aaabb"\nOutput: false\nExplanation: The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of lowercase English letters.There is a party where n
friends numbered from 0
to n - 1
are attending. There is an infinite number of chairs in this party that are numbered from 0
to infinity
. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.
0
, 1
, and 5
are occupied when a friend comes, they will sit on chair number 2
.When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
\n\nYou are given a 0-indexed 2D integer array times
where times[i] = [arrivali, leavingi]
, indicating the arrival and leaving times of the ith
friend respectively, and an integer targetFriend
. All arrival times are distinct.
Return the chair number that the friend numbered targetFriend
will sit on.
\n
Example 1:
\n\n\nInput: times = [[1,4],[2,3],[4,6]], targetFriend = 1\nOutput: 1\nExplanation: \n- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.\n\n\n
Example 2:
\n\n\nInput: times = [[3,10],[1,5],[2,6]], targetFriend = 0\nOutput: 2\nExplanation: \n- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.\n\n\n
\n
Constraints:
\n\nn == times.length
2 <= n <= 104
times[i].length == 2
1 <= arrivali < leavingi <= 105
0 <= targetFriend <= n - 1
arrivali
time is distinct.There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments
, where segments[i] = [starti, endi, colori]
represents the half-closed segment [starti, endi)
with colori
as the color.
The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.
\n\n2
, 4
, and 6
are mixed, then the resulting mixed color is {2,4,6}
.For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.
\n\nYou want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting
where painting[j] = [leftj, rightj, mixj]
describes a half-closed segment [leftj, rightj)
with the mixed color sum of mixj
.
segments = [[1,4,5],[1,7,7]]
can be described by painting = [[1,4,12],[4,7,7]]
because:\n\n\t[1,4)
is colored {5,7}
(with a sum of 12
) from both the first and second segments.[4,7)
is colored {7}
from only the second segment.Return the 2D array painting
describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.
A half-closed segment [a, b)
is the section of the number line between points a
and b
including point a
and not including point b
.
\n
Example 1:
\n\nInput: segments = [[1,4,5],[4,7,7],[1,7,9]]\nOutput: [[1,4,14],[4,7,16]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.\n\n\n
Example 2:
\n\nInput: segments = [[1,7,9],[6,8,15],[8,10,7]]\nOutput: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation: The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.\n\n\n
Example 3:
\n\nInput: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput: [[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.\n\n\n
\n
Constraints:
\n\n1 <= segments.length <= 2 * 104
segments[i].length == 3
1 <= starti < endi <= 105
1 <= colori <= 109
colori
is distinct.There are n
people standing in a queue, and they numbered from 0
to n - 1
in left to right order. You are given an array heights
of distinct integers where heights[i]
represents the height of the ith
person.
A person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith
person can see the jth
person if i < j
and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1])
.
Return an array answer
of length n
where answer[i]
is the number of people the ith
person can see to their right in the queue.
\n
Example 1:
\n\n\nInput: heights = [10,6,8,5,11,9]\nOutput: [3,1,2,1,1,0]\nExplanation:\nPerson 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.\n\n\n
Example 2:
\n\n\nInput: heights = [5,1,2,3,10]\nOutput: [4,1,1,1,0]\n\n\n
\n
Constraints:
\n\nn == heights.length
1 <= n <= 105
1 <= heights[i] <= 105
heights
are unique.You are given a string s
consisting of lowercase English letters, and an integer k
. Your task is to convert the string into an integer by a special process, and then transform it by summing its digits repeatedly k
times. More specifically, perform the following steps:
s
into an integer by replacing each letter with its position in the alphabet (i.e. replace 'a'
with 1
, 'b'
with 2
, ..., 'z'
with 26
).k
times in total.For example, if s = "zbax"
and k = 2
, then the resulting integer would be 8
by the following operations:
"zbax" \u279d "(26)(2)(1)(24)" \u279d "262124" \u279d 262124
262124 \u279d 2 + 6 + 2 + 1 + 2 + 4 \u279d 17
17 \u279d 1 + 7 \u279d 8
Return the resulting integer after performing the operations described above.
\n\n\n
Example 1:
\n\nInput: s = "iiii", k = 1
\n\nOutput: 36
\n\nExplanation:
\n\nThe operations are as follows:
\n- Convert: "iiii" \u279d "(9)(9)(9)(9)" \u279d "9999" \u279d 9999
\n- Transform #1: 9999 \u279d 9 + 9 + 9 + 9 \u279d 36
\nThus the resulting integer is 36.
Example 2:
\n\nInput: s = "leetcode", k = 2
\n\nOutput: 6
\n\nExplanation:
\n\nThe operations are as follows:
\n- Convert: "leetcode" \u279d "(12)(5)(5)(20)(3)(15)(4)(5)" \u279d "12552031545" \u279d 12552031545
\n- Transform #1: 12552031545 \u279d 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 \u279d 33
\n- Transform #2: 33 \u279d 3 + 3 \u279d 6
\nThus the resulting integer is 6.
Example 3:
\n\nInput: s = "zbax", k = 2
\n\nOutput: 8
\n\n
Constraints:
\n\n1 <= s.length <= 100
1 <= k <= 10
s
consists of lowercase English letters.You are given a string num
, which represents a large integer. You are also given a 0-indexed integer array change
of length 10
that maps each digit 0-9
to another digit. More formally, digit d
maps to digit change[d]
.
You may choose to mutate a single substring of num
. To mutate a substring, replace each digit num[i]
with the digit it maps to in change
(i.e. replace num[i]
with change[num[i]]
).
Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num
.
A substring is a contiguous sequence of characters within the string.
\n\n\n
Example 1:
\n\n\nInput: num = "132", change = [9,8,5,0,3,6,4,2,6,8]\nOutput: "832"\nExplanation: Replace the substring "1":\n- 1 maps to change[1] = 8.\nThus, "132" becomes "832".\n"832" is the largest number that can be created, so return it.\n\n\n
Example 2:
\n\n\nInput: num = "021", change = [9,4,3,5,7,2,1,9,0,6]\nOutput: "934"\nExplanation: Replace the substring "021":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, "021" becomes "934".\n"934" is the largest number that can be created, so return it.\n\n\n
Example 3:
\n\n\nInput: num = "5", change = [1,4,7,5,3,2,5,6,9,4]\nOutput: "5"\nExplanation: "5" is already the largest number that can be created, so return it.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 105
num
consists of only digits 0-9
.change.length == 10
0 <= change[d] <= 9
There is a survey that consists of n
questions where each question's answer is either 0
(no) or 1
(yes).
The survey was given to m
students numbered from 0
to m - 1
and m
mentors numbered from 0
to m - 1
. The answers of the students are represented by a 2D integer array students
where students[i]
is an integer array that contains the answers of the ith
student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors
where mentors[j]
is an integer array that contains the answers of the jth
mentor (0-indexed).
Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.
\n\n[1, 0, 1]
and the mentor's answers were [0, 0, 1]
, then their compatibility score is 2 because only the second and the third answers are the same.You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.
\n\nGiven students
and mentors
, return the maximum compatibility score sum that can be achieved.
\n
Example 1:
\n\n\nInput: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput: 8\nExplanation: We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.\n\n\n
Example 2:
\n\n\nInput: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput: 0\nExplanation: The compatibility score of any student-mentor pair is 0.\n\n\n
\n
Constraints:
\n\nm == students.length == mentors.length
n == students[i].length == mentors[j].length
1 <= m, n <= 8
students[i][k]
is either 0
or 1
.mentors[j][k]
is either 0
or 1
.Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths
, where paths[i]
is an array representing an absolute path to the ith
folder in the file system.
["one", "two", "three"]
represents the path "/one/two/three"
.Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.
\n\n"/a"
and "/b"
in the file structure below are identical. They (as well as their subfolders) should all be marked:\n\n\t/a
/a/x
/a/x/y
/a/z
/b
/b/x
/b/x/y
/b/z
"/b/w"
, then the folders "/a"
and "/b"
would not be identical. Note that "/a/x"
and "/b/x"
would still be considered identical even with the added folder.Once all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.
\n\nReturn the 2D array ans
containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.
\n
Example 1:
\n\nInput: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]\nOutput: [["d"],["d","a"]]\nExplanation: The file structure is as shown.\nFolders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named "b".\n\n\n
Example 2:
\n\nInput: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]\nOutput: [["c"],["c","b"],["a"],["a","b"]]\nExplanation: The file structure is as shown. \nFolders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".\nNote that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.\n\n\n
Example 3:
\n\nInput: paths = [["a","b"],["c","d"],["c"],["a"]]\nOutput: [["c"],["c","d"],["a"],["a","b"]]\nExplanation: All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter.\n\n\n
\n
Constraints:
\n\n1 <= paths.length <= 2 * 104
1 <= paths[i].length <= 500
1 <= paths[i][j].length <= 10
1 <= sum(paths[i][j].length) <= 2 * 105
path[i][j]
consists of lowercase English letters.Given an integer n
, return true
if n
has exactly three positive divisors. Otherwise, return false
.
An integer m
is a divisor of n
if there exists an integer k
such that n = k * m
.
\n
Example 1:
\n\n\nInput: n = 2\nOutput: false\nExplantion: 2 has only two divisors: 1 and 2.\n\n\n
Example 2:
\n\n\nInput: n = 4\nOutput: true\nExplantion: 4 has three divisors: 1, 2, and 4.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
There are n
projects numbered from 0
to n - 1
. You are given an integer array milestones
where each milestones[i]
denotes the number of milestones the ith
project has.
You can work on the projects following these two rules:
\n\nOnce all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.
\n\nReturn the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
\n\n\n
Example 1:
\n\n\nInput: milestones = [1,2,3]\nOutput: 6\nExplanation: One possible scenario is:\n\u200b\u200b\u200b\u200b- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 2.\n- During the 3rd week, you will work on a milestone of project 1.\n- During the 4th week, you will work on a milestone of project 2.\n- During the 5th week, you will work on a milestone of project 1.\n- During the 6th week, you will work on a milestone of project 2.\nThe total number of weeks is 6.\n\n\n
Example 2:
\n\n\nInput: milestones = [5,2,1]\nOutput: 7\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 1.\n- During the 3rd week, you will work on a milestone of project 0.\n- During the 4th week, you will work on a milestone of project 1.\n- During the 5th week, you will work on a milestone of project 0.\n- During the 6th week, you will work on a milestone of project 2.\n- During the 7th week, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.\n\n\n
\n
Constraints:
\n\nn == milestones.length
1 <= n <= 105
1 <= milestones[i] <= 109
In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j)
has |i| + |j|
apples growing on it.
You will buy an axis-aligned square plot of land that is centered at (0, 0)
.
Given an integer neededApples
, return the minimum perimeter of a plot such that at least neededApples
apples are inside or on the perimeter of that plot.
The value of |x|
is defined as:
x
if x >= 0
-x
if x < 0
\n
Example 1:
\n\nInput: neededApples = 1\nOutput: 8\nExplanation: A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.\n\n\n
Example 2:
\n\n\nInput: neededApples = 13\nOutput: 16\n\n\n
Example 3:
\n\n\nInput: neededApples = 1000000000\nOutput: 5040\n\n\n
\n
Constraints:
\n\n1 <= neededApples <= 1015
A sequence is special if it consists of a positive number of 0
s, followed by a positive number of 1
s, then a positive number of 2
s.
[0,1,2]
and [0,0,1,1,1,2]
are special.[2,1,0]
, [1]
, and [0,1,2,0]
are not special.Given an array nums
(consisting of only integers 0
, 1
, and 2
), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,1,2,2]\nOutput: 3\nExplanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,0,0]\nOutput: 0\nExplanation: There are no special subsequences in [2,2,0,0].\n\n\n
Example 3:
\n\n\nInput: nums = [0,1,2,0,1,2]\nOutput: 7\nExplanation: The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 2
A fancy string is a string where no three consecutive characters are equal.
\n\nGiven a string s
, delete the minimum possible number of characters from s
to make it fancy.
Return the final string after the deletion. It can be shown that the answer will always be unique.
\n\n\n
Example 1:
\n\n\nInput: s = "leeetcode"\nOutput: "leetcode"\nExplanation:\nRemove an 'e' from the first group of 'e's to create "leetcode".\nNo three consecutive characters are equal, so return "leetcode".\n\n\n
Example 2:
\n\n\nInput: s = "aaabaaaa"\nOutput: "aabaa"\nExplanation:\nRemove an 'a' from the first group of 'a's to create "aabaaaa".\nRemove two 'a's from the second group of 'a's to create "aabaa".\nNo three consecutive characters are equal, so return "aabaa".\n\n\n
Example 3:
\n\n\nInput: s = "aab"\nOutput: "aab"\nExplanation: No three consecutive characters are equal, so return "aab".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.You are given a 0-indexed 8 x 8
grid board
, where board[r][c]
represents the cell (r, c)
on a game board. On the board, free cells are represented by '.'
, white cells are represented by 'W'
, and black cells are represented by 'B'
.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).
\n\nA good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:
\nGiven two integers rMove
and cMove
and a character color
representing the color you are playing as (white or black), return true
if changing cell (rMove, cMove)
to color color
is a legal move, or false
if it is not legal.
\n
Example 1:
\n\nInput: board = [[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],[".",".",".","W",".",".",".","."],["W","B","B",".","W","W","W","B"],[".",".",".","B",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","W",".",".",".","."]], rMove = 4, cMove = 3, color = "B"\nOutput: true\nExplanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.\n\n\n
Example 2:
\n\nInput: board = [[".",".",".",".",".",".",".","."],[".","B",".",".","W",".",".","."],[".",".","W",".",".",".",".","."],[".",".",".","W","B",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".","B","W",".","."],[".",".",".",".",".",".","W","."],[".",".",".",".",".",".",".","B"]], rMove = 4, cMove = 4, color = "W"\nOutput: false\nExplanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.\n\n\n
\n
Constraints:
\n\nboard.length == board[r].length == 8
0 <= rMove, cMove < 8
board[rMove][cMove] == '.'
color
is either 'B'
or 'W'
.You are currently designing a dynamic array. You are given a 0-indexed integer array nums
, where nums[i]
is the number of elements that will be in the array at time i
. In addition, you are given an integer k
, the maximum number of times you can resize the array (to any size).
The size of the array at time t
, sizet
, must be at least nums[t]
because there needs to be enough space in the array to hold all the elements. The space wasted at time t
is defined as sizet - nums[t]
, and the total space wasted is the sum of the space wasted across every time t
where 0 <= t < nums.length
.
Return the minimum total space wasted if you can resize the array at most k
times.
Note: The array can have any size at the start and does not count towards the number of resizing operations.
\n\n\n
Example 1:
\n\n\nInput: nums = [10,20], k = 0\nOutput: 10\nExplanation: size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.\n\n\n
Example 2:
\n\n\nInput: nums = [10,20,30], k = 1\nOutput: 10\nExplanation: size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.\n\n\n
Example 3:
\n\n\nInput: nums = [10,20,15,30,20], k = 2\nOutput: 15\nExplanation: size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= 106
0 <= k <= nums.length - 1
You are given a 0-indexed string s
and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.
More formally, you want to choose four integers i
, j
, k
, l
such that 0 <= i <= j < k <= l < s.length
and both the substrings s[i...j]
and s[k...l]
are palindromes and have odd lengths. s[i...j]
denotes a substring from index i
to index j
inclusive.
Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.
\n\nA palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: s = "ababbb"\nOutput: 9\nExplanation: Substrings "aba" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.\n\n\n
Example 2:
\n\n\nInput: s = "zaaaxbbby"\nOutput: 9\nExplanation: Substrings "aaa" and "bbb" are palindromes with odd length. product = 3 * 3 = 9.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 105
s
consists of lowercase English letters.Given a string s
and an array of strings words
, determine whether s
is a prefix string of words
.
A string s
is a prefix string of words
if s
can be made by concatenating the first k
strings in words
for some positive k
no larger than words.length
.
Return true
if s
is a prefix string of words
, or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "iloveleetcode", words = ["i","love","leetcode","apples"]\nOutput: true\nExplanation:\ns can be made by concatenating "i", "love", and "leetcode" together.\n\n\n
Example 2:
\n\n\nInput: s = "iloveleetcode", words = ["apples","i","love","leetcode"]\nOutput: false\nExplanation:\nIt is impossible to make s using a prefix of arr.\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 20
1 <= s.length <= 1000
words[i]
and s
consist of only lowercase English letters.You are given a 0-indexed integer array piles
, where piles[i]
represents the number of stones in the ith
pile, and an integer k
. You should apply the following operation exactly k
times:
piles[i]
and remove floor(piles[i] / 2)
stones from it.Notice that you can apply the operation on the same pile more than once.
\n\nReturn the minimum possible total number of stones remaining after applying the k
operations.
floor(x)
is the greatest integer that is smaller than or equal to x
(i.e., rounds x
down).
\n
Example 1:
\n\n\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\n\n\n
Example 2:
\n\n\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n\n\n
\n
Constraints:
\n\n1 <= piles.length <= 105
1 <= piles[i] <= 104
1 <= k <= 105
You are given a 0-indexed integer array piles
, where piles[i]
represents the number of stones in the ith
pile, and an integer k
. You should apply the following operation exactly k
times:
piles[i]
and remove ceil(piles[i] / 2)
stones from it.Notice that you can apply the operation on the same pile more than once.
\n\nReturn the minimum possible total number of stones remaining after applying the k
operations.
ceil(x)
is the smallest integer that is greater than or equal to x
(i.e., rounds x
up).
\n
Example 1:
\n\n\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\n\n\n
Example 2:
\n\n\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n\n\n
\n
Constraints:
\n\n1 <= piles.length <= 105
1 <= piles[i] <= 104
1 <= k <= 105
You are given a 0-indexed string s
of even length n
. The string consists of exactly n / 2
opening brackets '['
and n / 2
closing brackets ']'
.
A string is called balanced if and only if:
\n\nAB
, where both A
and B
are balanced strings, or[C]
, where C
is a balanced string.You may swap the brackets at any two indices any number of times.
\n\nReturn the minimum number of swaps to make s
balanced.
\n
Example 1:
\n\n\nInput: s = "][]["\nOutput: 1\nExplanation: You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is "[[]]".\n\n\n
Example 2:
\n\n\nInput: s = "]]][[["\nOutput: 2\nExplanation: You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = "[]][][".\n- Swap index 1 with index 5. s = "[[][]]".\nThe resulting string is "[[][]]".\n\n\n
Example 3:
\n\n\nInput: s = "[]"\nOutput: 0\nExplanation: The string is already balanced.\n\n\n
\n
Constraints:
\n\nn == s.length
2 <= n <= 106
n
is even.s[i]
is either '['
or ']'
.'['
equals n / 2
, and the number of closing brackets ']'
equals n / 2
.You want to build some obstacle courses. You are given a 0-indexed integer array obstacles
of length n
, where obstacles[i]
describes the height of the ith
obstacle.
For every index i
between 0
and n - 1
(inclusive), find the length of the longest obstacle course in obstacles
such that:
0
and i
inclusive.ith
obstacle in the course.obstacles
.Return an array ans
of length n
, where ans[i]
is the length of the longest obstacle course for index i
as described above.
\n
Example 1:
\n\n\nInput: obstacles = [1,2,3,2]\nOutput: [1,2,3,3]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.\n\n\n
Example 2:
\n\n\nInput: obstacles = [2,2,1]\nOutput: [1,2,1]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.\n\n\n
Example 3:
\n\n\nInput: obstacles = [3,1,5,6,4,2]\nOutput: [1,1,2,3,2,2]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.\n\n\n
\n
Constraints:
\n\nn == obstacles.length
1 <= n <= 105
1 <= obstacles[i] <= 107
Table: Employees
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| employee_id | int |\n| name | varchar |\n+-------------+---------+\nemployee_id is the column with unique values for this table.\nEach row of this table indicates the name of the employee whose ID is employee_id.\n\n\n
\n\n
Table: Salaries
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| employee_id | int |\n| salary | int |\n+-------------+---------+\nemployee_id is the column with unique values for this table.\nEach row of this table indicates the salary of the employee whose ID is employee_id.\n\n\n
\n\n
Write a solution to report the IDs of all the employees with missing information. The information of an employee is missing if:
\n\nReturn the result table ordered by employee_id
in ascending order.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+-------------+----------+\n| employee_id | name |\n+-------------+----------+\n| 2 | Crew |\n| 4 | Haven |\n| 5 | Kristian |\n+-------------+----------+\nSalaries table:\n+-------------+--------+\n| employee_id | salary |\n+-------------+--------+\n| 5 | 76071 |\n| 1 | 22517 |\n| 4 | 63539 |\n+-------------+--------+\nOutput: \n+-------------+\n| employee_id |\n+-------------+\n| 1 |\n| 2 |\n+-------------+\nExplanation: \nEmployees 1, 2, 4, and 5 are working at this company.\nThe name of employee 1 is missing.\nThe salary of employee 2 is missing.\n\n", - "likes": 728, - "dislikes": 37, - "stats": "{\"totalAccepted\": \"139.4K\", \"totalSubmission\": \"191.8K\", \"totalAcceptedRaw\": 139379, \"totalSubmissionRaw\": 191784, \"acRate\": \"72.7%\"}", + "likes": 747, + "dislikes": 39, + "stats": "{\"totalAccepted\": \"150.5K\", \"totalSubmission\": \"206.3K\", \"totalAcceptedRaw\": 150471, \"totalSubmissionRaw\": 206329, \"acRate\": \"72.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -74110,9 +74224,9 @@ "questionFrontendId": "1966", "title": "Binary Searchable Numbers in an Unsorted Array", "content": null, - "likes": 74, + "likes": 75, "dislikes": 12, - "stats": "{\"totalAccepted\": \"3K\", \"totalSubmission\": \"4.8K\", \"totalAcceptedRaw\": 3020, \"totalSubmissionRaw\": 4814, \"acRate\": \"62.7%\"}", + "stats": "{\"totalAccepted\": \"3.1K\", \"totalSubmission\": \"5K\", \"totalAcceptedRaw\": 3116, \"totalSubmissionRaw\": 4984, \"acRate\": \"62.5%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -74145,9 +74259,9 @@ "questionFrontendId": "1967", "title": "Number of Strings That Appear as Substrings in Word", "content": "
Given an array of strings patterns
and a string word
, return the number of strings in patterns
that exist as a substring in word
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: patterns = ["a","abc","bc","d"], word = "abc"\nOutput: 3\nExplanation:\n- "a" appears as a substring in "abc".\n- "abc" appears as a substring in "abc".\n- "bc" appears as a substring in "abc".\n- "d" does not appear as a substring in "abc".\n3 of the strings in patterns appear as a substring in word.\n\n\n
Example 2:
\n\n\nInput: patterns = ["a","b","c"], word = "aaaaabbbbb"\nOutput: 2\nExplanation:\n- "a" appears as a substring in "aaaaabbbbb".\n- "b" appears as a substring in "aaaaabbbbb".\n- "c" does not appear as a substring in "aaaaabbbbb".\n2 of the strings in patterns appear as a substring in word.\n\n\n
Example 3:
\n\n\nInput: patterns = ["a","a","a"], word = "ab"\nOutput: 3\nExplanation: Each of the patterns appears as a substring in word "ab".\n\n\n
\n
Constraints:
\n\n1 <= patterns.length <= 100
1 <= patterns[i].length <= 100
1 <= word.length <= 100
patterns[i]
and word
consist of lowercase English letters.You are given a 0-indexed array nums
of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i
in the range 1 <= i < nums.length - 1
, (nums[i-1] + nums[i+1]) / 2
is not equal to nums[i]
.
Return any rearrangement of nums
that meets the requirements.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n\n\n
Example 2:
\n\n\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
0 <= nums[i] <= 105
You are given a 0-indexed array nums
of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.
More formally, the rearranged array should have the property such that for every i
in the range 1 <= i < nums.length - 1
, (nums[i-1] + nums[i+1]) / 2
is not equal to nums[i]
.
Return any rearrangement of nums
that meets the requirements.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n\n\n
Example 2:
\n\n\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\nNote that the original array [6,2,0,9,7] also satisfies the conditions.\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
0 <= nums[i] <= 105
You are given a positive integer p
. Consider an array nums
(1-indexed) that consists of the integers in the inclusive range [1, 2p - 1]
in their binary representations. You are allowed to do the following operation any number of times:
x
and y
from nums
.x
and swap it with its corresponding bit in y
. Corresponding bit refers to the bit that is in the same position in the other integer.For example, if x = 1101
and y = 0011
, after swapping the 2nd
bit from the right, we have x = 1111
and y = 0001
.
Find the minimum non-zero product of nums
after performing the above operation any number of times. Return this product modulo 109 + 7
.
Note: The answer should be the minimum product before the modulo operation is done.
\n\n\n
Example 1:
\n\n\nInput: p = 1\nOutput: 1\nExplanation: nums = [1].\nThere is only one element, so the product equals that element.\n\n\n
Example 2:
\n\n\nInput: p = 2\nOutput: 6\nExplanation: nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.\n\n\n
Example 3:
\n\n\nInput: p = 3\nOutput: 1512\nExplanation: nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001, 110, 011, 100, 001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.\n\n\n
\n
Constraints:
\n\n1 <= p <= 60
There is a 1-based binary matrix where 0
represents land and 1
represents water. You are given integers row
and col
representing the number of rows and columns in the matrix, respectively.
Initially on day 0
, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells
, where cells[i] = [ri, ci]
represents that on the ith
day, the cell on the rith
row and cith
column (1-based coordinates) will be covered with water (i.e., changed to 1
).
You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).
\n\nReturn the last day where it is possible to walk from the top to the bottom by only walking on land cells.
\n\n\n
Example 1:
\n\nInput: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]\nOutput: 2\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 2.\n\n\n
Example 2:
\n\nInput: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]\nOutput: 1\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 1.\n\n\n
Example 3:
\n\nInput: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]\nOutput: 3\nExplanation: The above image depicts how the matrix changes each day starting from day 0.\nThe last day where it is possible to cross from top to bottom is on day 3.\n\n\n
\n
Constraints:
\n\n2 <= row, col <= 2 * 104
4 <= row * col <= 2 * 104
cells.length == row * col
1 <= ri <= row
1 <= ci <= col
cells
are unique.There is a bi-directional graph with n
vertices, where each vertex is labeled from 0
to n - 1
(inclusive). The edges in the graph are represented as a 2D integer array edges
, where each edges[i] = [ui, vi]
denotes a bi-directional edge between vertex ui
and vertex vi
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
You want to determine if there is a valid path that exists from vertex source
to vertex destination
.
Given edges
and the integers n
, source
, and destination
, return true
if there is a valid path from source
to destination
, or false
otherwise.
\n
Example 1:
\n\nInput: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2\nOutput: true\nExplanation: There are two paths from vertex 0 to vertex 2:\n- 0 → 1 → 2\n- 0 → 2\n\n\n
Example 2:
\n\nInput: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\nOutput: false\nExplanation: There is no path from vertex 0 to vertex 5.\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ui, vi <= n - 1
ui != vi
0 <= source, destination <= n - 1
There is a special typewriter with lowercase English letters 'a'
to 'z'
arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'
.
Each second, you may perform one of the following operations:
\n\nGiven a string word
, return the minimum number of seconds to type out the characters in word
.
\n
Example 1:
\n\n\nInput: word = "abc"\nOutput: 5\nExplanation: \nThe characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.\n\n\n
Example 2:
\n\n\nInput: word = "bza"\nOutput: 7\nExplanation:\nThe characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.\n\n\n
Example 3:
\n\n\nInput: word = "zjpc"\nOutput: 34\nExplanation:\nThe characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 100
word
consists of lowercase English letters.You are given an n x n
integer matrix
. You can do the following operation any number of times:
matrix
and multiply each of them by -1
.Two elements are considered adjacent if and only if they share a border.
\n\nYour goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
\n\n\n
Example 1:
\n\nInput: matrix = [[1,-1],[-1,1]]\nOutput: 4\nExplanation: We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.\n\n\n
Example 2:
\n\nInput: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput: 16\nExplanation: We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.\n\n\n
\n
Constraints:
\n\nn == matrix.length == matrix[i].length
2 <= n <= 250
-105 <= matrix[i][j] <= 105
You are in a city that consists of n
intersections numbered from 0
to n - 1
with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n
and a 2D integer array roads
where roads[i] = [ui, vi, timei]
means that there is a road between intersections ui
and vi
that takes timei
minutes to travel. You want to know in how many ways you can travel from intersection 0
to intersection n - 1
in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 \u279d 6\n- 0 \u279d 4 \u279d 6\n- 0 \u279d 1 \u279d 2 \u279d 5 \u279d 6\n- 0 \u279d 1 \u279d 3 \u279d 5 \u279d 6\n\n\n
Example 2:
\n\n\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n\n\n
\n
Constraints:
\n\n1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
You are in a city that consists of n
intersections numbered from 0
to n - 1
with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n
and a 2D integer array roads
where roads[i] = [ui, vi, timei]
means that there is a road between intersections ui
and vi
that takes timei
minutes to travel. You want to know in how many ways you can travel from intersection 0
to intersection n - 1
in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 \u279d 6\n- 0 \u279d 4 \u279d 6\n- 0 \u279d 1 \u279d 2 \u279d 5 \u279d 6\n- 0 \u279d 1 \u279d 3 \u279d 5 \u279d 6\n\n\n
Example 2:
\n\n\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n\n\n
\n
Constraints:
\n\n1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
You wrote down many positive integers in a string called num
. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.
Return the number of possible lists of integers that you could have written down to get the string num
. Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: num = "327"\nOutput: 2\nExplanation: You could have written down the numbers:\n3, 27\n327\n\n\n
Example 2:
\n\n\nInput: num = "094"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\n\n\n
Example 3:
\n\n\nInput: num = "0"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 3500
num
consists of digits '0'
through '9'
.Table: Employees
\n+-------------+----------+\n| Column Name | Type |\n+-------------+----------+\n| employee_id | int |\n| name | varchar |\n| manager_id | int |\n| salary | int |\n+-------------+----------+\nIn SQL, employee_id is the primary key for this table.\nThis table contains information about the employees, their salary, and the ID of their manager. Some employees do not have a manager (manager_id is null). \n\n\n
\n\n
Find the IDs of the employees whose salary is strictly less than $30000
and whose manager left the company. When a manager leaves the company, their information is deleted from the Employees
table, but the reports still have their manager_id
set to the manager that left.
Return the result table ordered by employee_id
.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nEmployees table:\n+-------------+-----------+------------+--------+\n| employee_id | name | manager_id | salary |\n+-------------+-----------+------------+--------+\n| 3 | Mila | 9 | 60301 |\n| 12 | Antonella | null | 31000 |\n| 13 | Emery | null | 67084 |\n| 1 | Kalel | 11 | 21241 |\n| 9 | Mikaela | null | 50937 |\n| 11 | Joziah | 6 | 28485 |\n+-------------+-----------+------------+--------+\nOutput: \n+-------------+\n| employee_id |\n+-------------+\n| 11 |\n+-------------+\n\nExplanation: \nThe employees with a salary less than $30000 are 1 (Kalel) and 11 (Joziah).\nKalel's manager is employee 11, who is still in the company (Joziah).\nJoziah's manager is employee 6, who left the company because there is no row for employee 6 as it was deleted.\n\n", - "likes": 442, - "dislikes": 38, - "stats": "{\"totalAccepted\": \"203.6K\", \"totalSubmission\": \"416.6K\", \"totalAcceptedRaw\": 203610, \"totalSubmissionRaw\": 416577, \"acRate\": \"48.9%\"}", + "likes": 491, + "dislikes": 41, + "stats": "{\"totalAccepted\": \"251.4K\", \"totalSubmission\": \"514.6K\", \"totalAcceptedRaw\": 251386, \"totalSubmissionRaw\": 514638, \"acRate\": \"48.8%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -74592,9 +74709,9 @@ "questionFrontendId": "1979", "title": "Find Greatest Common Divisor of Array", "content": "
Given an integer array nums
, return the greatest common divisor of the smallest number and largest number in nums
.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,5,6,9,10]\nOutput: 2\nExplanation:\nThe smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [7,5,6,8,3]\nOutput: 1\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.\n\n\n
Example 3:
\n\n\nInput: nums = [3,3]\nOutput: 3\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 1000
1 <= nums[i] <= 1000
Given an array of strings nums
containing n
unique binary strings each of length n
, return a binary string of length n
that does not appear in nums
. If there are multiple answers, you may return any of them.
\n
Example 1:
\n\n\nInput: nums = ["01","10"]\nOutput: "11"\nExplanation: "11" does not appear in nums. "00" would also be correct.\n\n\n
Example 2:
\n\n\nInput: nums = ["00","01"]\nOutput: "11"\nExplanation: "11" does not appear in nums. "10" would also be correct.\n\n\n
Example 3:
\n\n\nInput: nums = ["111","011","001"]\nOutput: "101"\nExplanation: "101" does not appear in nums. "000", "010", "100", and "110" would also be correct.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 16
nums[i].length == n
nums[i]
is either '0'
or '1'
.nums
are unique.You are given an m x n
integer matrix mat
and an integer target
.
Choose one integer from each row in the matrix such that the absolute difference between target
and the sum of the chosen elements is minimized.
Return the minimum absolute difference.
\n\nThe absolute difference between two numbers a
and b
is the absolute value of a - b
.
\n
Example 1:
\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput: 0\nExplanation: One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.\n\n\n
Example 2:
\n\nInput: mat = [[1],[2],[3]], target = 100\nOutput: 94\nExplanation: The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.\n\n\n
Example 3:
\n\nInput: mat = [[1,2,9,8,7]], target = 6\nOutput: 1\nExplanation: The best choice is to choose 7 from the first row.\nThe absolute difference is 1.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 70
1 <= mat[i][j] <= 70
1 <= target <= 800
You are given an integer n
representing the length of an unknown array that you are trying to recover. You are also given an array sums
containing the values of all 2n
subset sums of the unknown array (in no particular order).
Return the array ans
of length n
representing the unknown array. If multiple answers exist, return any of them.
An array sub
is a subset of an array arr
if sub
can be obtained from arr
by deleting some (possibly zero or all) elements of arr
. The sum of the elements in sub
is one possible subset sum of arr
. The sum of an empty array is considered to be 0
.
Note: Test cases are generated such that there will always be at least one correct answer.
\n\n\n
Example 1:
\n\n\nInput: n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput: [1,2,-3]\nExplanation: [1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.\n\n\n
Example 2:
\n\n\nInput: n = 2, sums = [0,0,0,0]\nOutput: [0,0]\nExplanation: The only correct answer is [0,0].\n\n\n
Example 3:
\n\n\nInput: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput: [0,-1,4,5]\nExplanation: [0,-1,4,5] is able to achieve the given subset sums.\n\n\n
\n
Constraints:
\n\n1 <= n <= 15
sums.length == 2n
-104 <= sums[i] <= 104
You are given a 0-indexed integer array nums
, where nums[i]
represents the score of the ith
student. You are also given an integer k
.
Pick the scores of any k
students from the array so that the difference between the highest and the lowest of the k
scores is minimized.
Return the minimum possible difference.
\n\n\n
Example 1:
\n\n\nInput: nums = [90], k = 1\nOutput: 0\nExplanation: There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.\n\n\n
Example 2:
\n\n\nInput: nums = [9,4,1,7], k = 2\nOutput: 2\nExplanation: There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 1000
0 <= nums[i] <= 105
You are given an array of strings nums
and an integer k
. Each string in nums
represents an integer without leading zeros.
Return the string that represents the kth
largest integer in nums
.
Note: Duplicate numbers should be counted distinctly. For example, if nums
is ["1","2","2"]
, "2"
is the first largest integer, "2"
is the second-largest integer, and "1"
is the third-largest integer.
\n
Example 1:
\n\n\nInput: nums = ["3","6","7","10"], k = 4\nOutput: "3"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are ["3","6","7","10"].\nThe 4th largest integer in nums is "3".\n\n\n
Example 2:
\n\n\nInput: nums = ["2","21","12","1"], k = 3\nOutput: "2"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are ["1","2","12","21"].\nThe 3rd largest integer in nums is "2".\n\n\n
Example 3:
\n\n\nInput: nums = ["0","0"], k = 2\nOutput: "0"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are ["0","0"].\nThe 2nd largest integer in nums is "0".\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 104
1 <= nums[i].length <= 100
nums[i]
consists of only digits.nums[i]
will not have any leading zeros.There are n
tasks assigned to you. The task times are represented as an integer array tasks
of length n
, where the ith
task takes tasks[i]
hours to finish. A work session is when you work for at most sessionTime
consecutive hours and then take a break.
You should finish the given tasks in a way that satisfies the following conditions:
\n\nGiven tasks
and sessionTime
, return the minimum number of work sessions needed to finish all the tasks following the conditions above.
The tests are generated such that sessionTime
is greater than or equal to the maximum element in tasks[i]
.
\n
Example 1:
\n\n\nInput: tasks = [1,2,3], sessionTime = 3\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.\n\n\n
Example 2:
\n\n\nInput: tasks = [3,1,3,1,1], sessionTime = 8\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.\n\n\n
Example 3:
\n\n\nInput: tasks = [1,2,3,4,5], sessionTime = 15\nOutput: 1\nExplanation: You can finish all the tasks in one work session.\n\n\n
\n
Constraints:
\n\nn == tasks.length
1 <= n <= 14
1 <= tasks[i] <= 10
max(tasks[i]) <= sessionTime <= 15
You are given a binary string binary
. A subsequence of binary
is considered good if it is not empty and has no leading zeros (with the exception of "0"
).
Find the number of unique good subsequences of binary
.
binary = "001"
, then all the good subsequences are ["0", "0", "1"]
, so the unique good subsequences are "0"
and "1"
. Note that subsequences "00"
, "01"
, and "001"
are not good because they have leading zeros.Return the number of unique good subsequences of binary
. Since the answer may be very large, return it modulo 109 + 7
.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: binary = "001"\nOutput: 2\nExplanation: The good subsequences of binary are ["0", "0", "1"].\nThe unique good subsequences are "0" and "1".\n\n\n
Example 2:
\n\n\nInput: binary = "11"\nOutput: 2\nExplanation: The good subsequences of binary are ["1", "1", "11"].\nThe unique good subsequences are "1" and "11".\n\n
Example 3:
\n\n\nInput: binary = "101"\nOutput: 5\nExplanation: The good subsequences of binary are ["1", "0", "1", "10", "11", "101"]. \nThe unique good subsequences are "0", "1", "10", "11", and "101".\n\n\n
\n
Constraints:
\n\n1 <= binary.length <= 105
binary
consists of only '0'
s and '1'
s.Given a 0-indexed integer array nums
, find the leftmost middleIndex
(i.e., the smallest amongst all the possible ones).
A middleIndex
is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]
.
If middleIndex == 0
, the left side sum is considered to be 0
. Similarly, if middleIndex == nums.length - 1
, the right side sum is considered to be 0
.
Return the leftmost middleIndex
that satisfies the condition, or -1
if there is no such index.
\n
Example 1:
\n\n\nInput: nums = [2,3,-1,8,4]\nOutput: 3\nExplanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4\n\n\n
Example 2:
\n\n\nInput: nums = [1,-1,4]\nOutput: 2\nExplanation: The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\n\n\n
Example 3:
\n\n\nInput: nums = [2,5]\nOutput: -1\nExplanation: There is no valid middleIndex.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
-1000 <= nums[i] <= 1000
\n
Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/
\n", - "likes": 1433, - "dislikes": 71, - "stats": "{\"totalAccepted\": \"119K\", \"totalSubmission\": \"175.3K\", \"totalAcceptedRaw\": 118981, \"totalSubmissionRaw\": 175322, \"acRate\": \"67.9%\"}", + "likes": 1462, + "dislikes": 74, + "stats": "{\"totalAccepted\": \"131.4K\", \"totalSubmission\": \"192.9K\", \"totalAcceptedRaw\": 131400, \"totalSubmissionRaw\": 192924, \"acRate\": \"68.1%\"}", "similarQuestions": "[{\"title\": \"Find Pivot Index\", \"titleSlug\": \"find-pivot-index\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Partition Array Into Three Parts With Equal Sum\", \"titleSlug\": \"partition-array-into-three-parts-with-equal-sum\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Number of Ways to Split Array\", \"titleSlug\": \"number-of-ways-to-split-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Sum Score of Array\", \"titleSlug\": \"maximum-sum-score-of-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Left and Right Sum Differences\", \"titleSlug\": \"left-and-right-sum-differences\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -75077,9 +75194,9 @@ "questionFrontendId": "1992", "title": "Find All Groups of Farmland", "content": "You are given a 0-indexed m x n
binary matrix land
where a 0
represents a hectare of forested land and a 1
represents a hectare of farmland.
To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.
\n\nland
can be represented by a coordinate system where the top left corner of land
is (0, 0)
and the bottom right corner of land
is (m-1, n-1)
. Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1)
and a bottom right corner at (r2, c2)
is represented by the 4-length array [r1, c1, r2, c2].
Return a 2D array containing the 4-length arrays described above for each group of farmland in land
. If there are no groups of farmland, return an empty array. You may return the answer in any order.
\n
Example 1:
\n\nInput: land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput: [[0,0,0,0],[1,1,2,2]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].\n\n\n
Example 2:
\n\nInput: land = [[1,1],[1,1]]\nOutput: [[0,0,1,1]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].\n\n\n
Example 3:
\n\nInput: land = [[0]]\nOutput: []\nExplanation:\nThere are no groups of farmland.\n\n\n
\n
Constraints:
\n\nm == land.length
n == land[i].length
1 <= m, n <= 300
land
consists of only 0
's and 1
's.You are given a tree with n
nodes numbered from 0
to n - 1
in the form of a parent array parent
where parent[i]
is the parent of the ith
node. The root of the tree is node 0
, so parent[0] = -1
since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.
The data structure should support the following functions:
\n\nImplement the LockingTree
class:
LockingTree(int[] parent)
initializes the data structure with the parent array.lock(int num, int user)
returns true
if it is possible for the user with id user
to lock the node num
, or false
otherwise. If it is possible, the node num
will become locked by the user with id user
.unlock(int num, int user)
returns true
if it is possible for the user with id user
to unlock the node num
, or false
otherwise. If it is possible, the node num
will become unlocked.upgrade(int num, int user)
returns true
if it is possible for the user with id user
to upgrade the node num
, or false
otherwise. If it is possible, the node num
will be upgraded.\n
Example 1:
\n\nInput\n["LockingTree", "lock", "unlock", "unlock", "lock", "upgrade", "lock"]\n[[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]\nOutput\n[null, true, false, true, true, true, false]\n\nExplanation\nLockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\nlockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\nlockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\nlockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\nlockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\nlockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\nlockingTree.lock(0, 1); // return false because node 0 is already locked.\n\n\n
\n
Constraints:
\n\nn == parent.length
2 <= n <= 2000
0 <= parent[i] <= n - 1
for i != 0
parent[0] == -1
0 <= num <= n - 1
1 <= user <= 104
parent
represents a valid tree.2000
calls in total will be made to lock
, unlock
, and upgrade
.You are given an integer array nums
. We call a subset of nums
good if its product can be represented as a product of one or more distinct prime numbers.
nums = [1, 2, 3, 4]
:\n\n\t[2, 3]
, [1, 2, 3]
, and [1, 3]
are good subsets with products 6 = 2*3
, 6 = 2*3
, and 3 = 3
respectively.[1, 4]
and [4]
are not good subsets with products 4 = 2*2
and 4 = 2*2
respectively.Return the number of different good subsets in nums
modulo 109 + 7
.
A subset of nums
is any array that can be obtained by deleting some (possibly none or all) elements from nums
. Two subsets are different if and only if the chosen indices to delete are different.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 6\nExplanation: The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.\n\n\n
Example 2:
\n\n\nInput: nums = [4,2,3,15]\nOutput: 5\nExplanation: The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 30
Given a 0-indexed integer array nums
, return the number of distinct quadruplets (a, b, c, d)
such that:
nums[a] + nums[b] + nums[c] == nums[d]
, anda < b < c < d
\n
Example 1:
\n\n\nInput: nums = [1,2,3,6]\nOutput: 1\nExplanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.\n\n\n
Example 2:
\n\n\nInput: nums = [3,3,6,4,5]\nOutput: 0\nExplanation: There are no such quadruplets in [3,3,6,4,5].\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,1,3,5]\nOutput: 4\nExplanation: The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5\n\n\n
\n
Constraints:
\n\n4 <= nums.length <= 50
1 <= nums[i] <= 100
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties
where properties[i] = [attacki, defensei]
represents the properties of the ith
character in the game.
A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i
is said to be weak if there exists another character j
where attackj > attacki
and defensej > defensei
.
Return the number of weak characters.
\n\n\n
Example 1:
\n\n\nInput: properties = [[5,5],[6,3],[3,6]]\nOutput: 0\nExplanation: No character has strictly greater attack and defense than the other.\n\n\n
Example 2:
\n\n\nInput: properties = [[2,2],[3,3]]\nOutput: 1\nExplanation: The first character is weak because the second character has a strictly greater attack and defense.\n\n\n
Example 3:
\n\n\nInput: properties = [[1,5],[10,4],[4,3]]\nOutput: 1\nExplanation: The third character is weak because the second character has a strictly greater attack and defense.\n\n\n
\n
Constraints:
\n\n2 <= properties.length <= 105
properties[i].length == 2
1 <= attacki, defensei <= 105
There are n
rooms you need to visit, labeled from 0
to n - 1
. Each day is labeled, starting from 0
. You will go in and visit one room a day.
Initially on day 0
, you visit room 0
. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit
of length n
:
i
,i
an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i]
where 0 <= nextVisit[i] <= i
;i
an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n
.Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nextVisit = [0,0]\nOutput: 2\nExplanation:\n- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n On the next day you will visit room nextVisit[0] = 0\n- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n On the next day you will visit room (0 + 1) mod 2 = 1\n- On day 2, you visit room 1. This is the first day where you have been in all the rooms.\n\n\n
Example 2:
\n\n\nInput: nextVisit = [0,0,2]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,0,0,1,2,...].\nDay 6 is the first day where you have been in all the rooms.\n\n\n
Example 3:
\n\n\nInput: nextVisit = [0,1,2,0]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,1,2,2,3,...].\nDay 6 is the first day where you have been in all the rooms.\n\n\n
\n
Constraints:
\n\nn == nextVisit.length
2 <= n <= 105
0 <= nextVisit[i] <= i
You are given an integer array nums
, and you can perform the following operation any number of times on nums
:
nums[i]
and nums[j]
if gcd(nums[i], nums[j]) > 1
where gcd(nums[i], nums[j])
is the greatest common divisor of nums[i]
and nums[j]
.Return true
if it is possible to sort nums
in non-decreasing order using the above swap method, or false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [7,21,3]\nOutput: true\nExplanation: We can sort [7,21,3] by performing the following operations:\n- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]\n- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]\n\n\n
Example 2:
\n\n\nInput: nums = [5,2,6,2]\nOutput: false\nExplanation: It is impossible to sort the array because 5 cannot be swapped with any other element.\n\n\n
Example 3:
\n\n\nInput: nums = [10,5,9,3,15]\nOutput: true\nWe can sort [10,5,9,3,15] by performing the following operations:\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]\n- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]\n- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 3 * 104
2 <= nums[i] <= 105
Given a 0-indexed string word
and a character ch
, reverse the segment of word
that starts at index 0
and ends at the index of the first occurrence of ch
(inclusive). If the character ch
does not exist in word
, do nothing.
word = "abcdefd"
and ch = "d"
, then you should reverse the segment that starts at 0
and ends at 3
(inclusive). The resulting string will be "dcbaefd"
.Return the resulting string.
\n\n\n
Example 1:
\n\n\nInput: word = "abcdefd", ch = "d"\nOutput: "dcbaefd"\nExplanation: The first occurrence of "d" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".\n\n\n
Example 2:
\n\n\nInput: word = "xyxzxe", ch = "z"\nOutput: "zxyxxe"\nExplanation: The first and only occurrence of "z" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".\n\n\n
Example 3:
\n\n\nInput: word = "abcd", ch = "z"\nOutput: "abcd"\nExplanation: "z" does not exist in word.\nYou should not do any reverse operation, the resulting string is "abcd".\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 250
word
consists of lowercase English letters.ch
is a lowercase English letter.You are given n
rectangles represented by a 0-indexed 2D integer array rectangles
, where rectangles[i] = [widthi, heighti]
denotes the width and height of the ith
rectangle.
Two rectangles i
and j
(i < j
) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj
(using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles
.
\n
Example 1:
\n\n\nInput: rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput: 6\nExplanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.\n\n\n
Example 2:
\n\n\nInput: rectangles = [[4,5],[7,8]]\nOutput: 0\nExplanation: There are no interchangeable pairs of rectangles.\n\n\n
\n
Constraints:
\n\nn == rectangles.length
1 <= n <= 105
rectangles[i].length == 2
1 <= widthi, heighti <= 105
Given a string s
, find two disjoint palindromic subsequences of s
such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.
Return the maximum possible product of the lengths of the two palindromic subsequences.
\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
\n\n\n
Example 1:
\n\nInput: s = "leetcodecom"\nOutput: 9\nExplanation: An optimal solution is to choose "ete" for the 1st subsequence and "cdc" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.\n\n\n
Example 2:
\n\n\nInput: s = "bb"\nOutput: 1\nExplanation: An optimal solution is to choose "b" (the first character) for the 1st subsequence and "b" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.\n\n\n
Example 3:
\n\n\nInput: s = "accbcaxxcxx"\nOutput: 25\nExplanation: An optimal solution is to choose "accca" for the 1st subsequence and "xxcxx" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 12
s
consists of lowercase English letters only.There is a family tree rooted at 0
consisting of n
nodes numbered 0
to n - 1
. You are given a 0-indexed integer array parents
, where parents[i]
is the parent for node i
. Since node 0
is the root, parents[0] == -1
.
There are 105
genetic values, each represented by an integer in the inclusive range [1, 105]
. You are given a 0-indexed integer array nums
, where nums[i]
is a distinct genetic value for node i
.
Return an array ans
of length n
where ans[i]
is the smallest genetic value that is missing from the subtree rooted at node i
.
The subtree rooted at a node x
contains node x
and all of its descendant nodes.
\n
Example 1:
\n\nInput: parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput: [5,1,1,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\n\n\n
Example 2:
\n\nInput: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput: [7,1,1,4,2,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\n\n\n
Example 3:
\n\n\nInput: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput: [1,1,1,1,1,1,1]\nExplanation: The value 1 is missing from all the subtrees.\n\n\n
\n
Constraints:
\n\nn == parents.length == nums.length
2 <= n <= 105
0 <= parents[i] <= n - 1
for i != 0
parents[0] == -1
parents
represents a valid tree.1 <= nums[i] <= 105
nums[i]
is distinct.Given an integer array nums
and an integer k
, return the number of pairs (i, j)
where i < j
such that |nums[i] - nums[j]| == k
.
The value of |x|
is defined as:
x
if x >= 0
.-x
if x < 0
.\n
Example 1:
\n\n\nInput: nums = [1,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n\n\n
Example 2:
\n\n\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= 100
1 <= k <= 99
An integer array original
is transformed into a doubled array changed
by appending twice the value of every element in original
, and then randomly shuffling the resulting array.
Given an array changed
, return original
if changed
is a doubled array. If changed
is not a doubled array, return an empty array. The elements in original
may be returned in any order.
\n
Example 1:
\n\n\nInput: changed = [1,3,4,2,6,8]\nOutput: [1,3,4]\nExplanation: One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].\n\n\n
Example 2:
\n\n\nInput: changed = [6,3,0,1]\nOutput: []\nExplanation: changed is not a doubled array.\n\n\n
Example 3:
\n\n\nInput: changed = [1]\nOutput: []\nExplanation: changed is not a doubled array.\n\n\n
\n
Constraints:
\n\n1 <= changed.length <= 105
0 <= changed[i] <= 105
There are n
points on a road you are driving your taxi on. The n
points on the road are labeled from 1
to n
in the direction you are going, and you want to drive from point 1
to point n
to make money by picking up passengers. You cannot change the direction of the taxi.
The passengers are represented by a 0-indexed 2D integer array rides
, where rides[i] = [starti, endi, tipi]
denotes the ith
passenger requesting a ride from point starti
to point endi
who is willing to give a tipi
dollar tip.
For each passenger i
you pick up, you earn endi - starti + tipi
dollars. You may only drive at most one passenger at a time.
Given n
and rides
, return the maximum number of dollars you can earn by picking up the passengers optimally.
Note: You may drop off a passenger and pick up a different passenger at the same point.
\n\n\n
Example 1:
\n\n\nInput: n = 5, rides = [[2,5,4],[1,5,1]]\nOutput: 7\nExplanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.\n\n\n
Example 2:
\n\n\nInput: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\nOutput: 20\nExplanation: We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= rides.length <= 3 * 104
rides[i].length == 3
1 <= starti < endi <= n
1 <= tipi <= 105
You are given an integer array nums
. In one operation, you can replace any element in nums
with any integer.
nums
is considered continuous if both of the following conditions are fulfilled:
nums
are unique.nums
equals nums.length - 1
.For example, nums = [4, 2, 5, 3]
is continuous, but nums = [1, 2, 3, 5, 6]
is not continuous.
Return the minimum number of operations to make nums
continuous.
\n
Example 1:
\n\n\nInput: nums = [4,2,5,3]\nOutput: 0\nExplanation: nums is already continuous.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,5,6]\nOutput: 1\nExplanation: One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.\n\n\n
Example 3:
\n\n\nInput: nums = [1,10,100,1000]\nOutput: 3\nExplanation: One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
There is a programming language with only four operations and one variable X
:
++X
and X++
increments the value of the variable X
by 1
.--X
and X--
decrements the value of the variable X
by 1
.Initially, the value of X
is 0
.
Given an array of strings operations
containing a list of operations, return the final value of X
after performing all the operations.
\n
Example 1:
\n\n\nInput: operations = ["--X","X++","X++"]\nOutput: 1\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X = 0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n\n\n
Example 2:
\n\n\nInput: operations = ["++X","++X","X++"]\nOutput: 3\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.\n\n\n
Example 3:
\n\n\nInput: operations = ["X++","++X","--X","X--"]\nOutput: 0\nExplanation: The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.\n\n\n
\n
Constraints:
\n\n1 <= operations.length <= 100
operations[i]
will be either "++X"
, "X++"
, "--X"
, or "X--"
.You are given a 0-indexed integer array nums
. For each index i
(1 <= i <= nums.length - 2
) the beauty of nums[i]
equals:
2
, if nums[j] < nums[i] < nums[k]
, for all 0 <= j < i
and for all i < k <= nums.length - 1
.1
, if nums[i - 1] < nums[i] < nums[i + 1]
, and the previous condition is not satisfied.0
, if none of the previous conditions holds.Return the sum of beauty of all nums[i]
where 1 <= i <= nums.length - 2
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,6,4]\nOutput: 1\nExplanation: For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
1 <= nums[i] <= 105
You are given a stream of points on the X-Y plane. Design an algorithm that:
\n\nAn axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.
\n\nImplement the DetectSquares
class:
DetectSquares()
Initializes the object with an empty data structure.void add(int[] point)
Adds a new point point = [x, y]
to the data structure.int count(int[] point)
Counts the number of ways to form axis-aligned squares with point point = [x, y]
as described above.\n
Example 1:
\n\nInput\n["DetectSquares", "add", "add", "add", "count", "count", "add", "count"]\n[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]\nOutput\n[null, null, null, null, 1, 0, null, 2]\n\nExplanation\nDetectSquares detectSquares = new DetectSquares();\ndetectSquares.add([3, 10]);\ndetectSquares.add([11, 2]);\ndetectSquares.add([3, 2]);\ndetectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\ndetectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\ndetectSquares.add([11, 2]); // Adding duplicate points is allowed.\ndetectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points\n\n\n
\n
Constraints:
\n\npoint.length == 2
0 <= x, y <= 1000
3000
calls in total will be made to add
and count
.You are given a string s
of length n
, and an integer k
. You are tasked to find the longest subsequence repeated k
times in string s
.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
\n\nA subsequence seq
is repeated k
times in the string s
if seq * k
is a subsequence of s
, where seq * k
represents a string constructed by concatenating seq
k
times.
"bba"
is repeated 2
times in the string "bababcba"
, because the string "bbabba"
, constructed by concatenating "bba"
2
times, is a subsequence of the string "bababcba"
.Return the longest subsequence repeated k
times in string s
. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
\n
Example 1:
\n\nInput: s = "letsleetcode", k = 2\nOutput: "let"\nExplanation: There are two longest subsequences repeated 2 times: "let" and "ete".\n"let" is the lexicographically largest one.\n\n\n
Example 2:
\n\n\nInput: s = "bb", k = 2\nOutput: "b"\nExplanation: The longest subsequence repeated 2 times is "b".\n\n\n
Example 3:
\n\n\nInput: s = "ab", k = 2\nOutput: ""\nExplanation: There is no subsequence repeated 2 times. Empty string is returned.\n\n\n
\n
Constraints:
\n\nn == s.length
2 <= n, k <= 2000
2 <= n < k * 8
s
consists of lowercase English letters.Given a 0-indexed integer array nums
of size n
, find the maximum difference between nums[i]
and nums[j]
(i.e., nums[j] - nums[i]
), such that 0 <= i < j < n
and nums[i] < nums[j]
.
Return the maximum difference. If no such i
and j
exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [7,1,5,4]\nOutput: 4\nExplanation:\nThe maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.\n\n\n
Example 2:
\n\n\nInput: nums = [9,4,3,2]\nOutput: -1\nExplanation:\nThere is no i and j such that i < j and nums[i] < nums[j].\n\n\n
Example 3:
\n\n\nInput: nums = [1,5,2,10]\nOutput: 9\nExplanation:\nThe maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109
You are given a 0-indexed 2D array grid
of size 2 x n
, where grid[r][c]
represents the number of points at position (r, c)
on the matrix. Two robots are playing a game on this matrix.
Both robots initially start at (0, 0)
and want to reach (1, n-1)
. Each robot may only move to the right ((r, c)
to (r, c + 1)
) or down ((r, c)
to (r + 1, c)
).
At the start of the game, the first robot moves from (0, 0)
to (1, n-1)
, collecting all the points from the cells on its path. For all cells (r, c)
traversed on the path, grid[r][c]
is set to 0
. Then, the second robot moves from (0, 0)
to (1, n-1)
, collecting the points on its path. Note that their paths may intersect with one another.
The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
\n\n\n
Example 1:
\n\nInput: grid = [[2,5,4],[1,5,1]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points.\n\n\n
Example 2:
\n\nInput: grid = [[3,3,1],[8,5,2]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points.\n\n\n
Example 3:
\n\nInput: grid = [[1,3,1,15],[1,3,3,1]]\nOutput: 7\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.\n\n\n
\n
Constraints:
\n\ngrid.length == 2
n == grid[r].length
1 <= n <= 5 * 104
1 <= grid[r][c] <= 105
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 right to left) or vertically (top to bottom or bottom to top) in the board if:
\n\n'#'
.' '
(empty) or match the letter already on the board
.' '
or other lowercase letters directly left or right of the word if the word was placed horizontally.' '
or other lowercase letters directly above or below the word if the word was placed vertically.Given a string word
, return true
if word
can be placed in board
, or false
otherwise.
\n
Example 1:
\n\nInput: board = [["#", " ", "#"], [" ", " ", "#"], ["#", "c", " "]], word = "abc"\nOutput: true\nExplanation: The word "abc" can be placed as shown above (top to bottom).\n\n\n
Example 2:
\n\nInput: board = [[" ", "#", "a"], [" ", "#", "c"], [" ", "#", "a"]], word = "ac"\nOutput: false\nExplanation: It is impossible to place the word because there will always be a space/letter above or below it.\n\n
Example 3:
\n\nInput: board = [["#", " ", "#"], [" ", " ", "#"], ["#", " ", "c"]], word = "ca"\nOutput: true\nExplanation: The word "ca" can be placed as shown above (right to left). \n\n\n
\n
Constraints:
\n\nm == board.length
n == board[i].length
1 <= m * n <= 2 * 105
board[i][j]
will be ' '
, '#'
, or a lowercase English letter.1 <= word.length <= max(m, n)
word
will contain only lowercase English letters.You are given a string s
that contains digits 0-9
, addition symbols '+'
, and multiplication symbols '*'
only, representing a valid math expression of single digit numbers (e.g., 3+5*2
). This expression was given to n
elementary school students. The students were instructed to get the answer of the expression by following this order of operations:
You are given an integer array answers
of length n
, which are the submitted answers of the students in no particular order. You are asked to grade the answers
, by following these rules:
5
points;2
points;0
points.Return the sum of the points of the students.
\n\n\n
Example 1:
\n\nInput: s = "7+3*1*2", answers = [20,13,42]\nOutput: 7\nExplanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\n\n\n
Example 2:
\n\n\nInput: s = "3+5*2", answers = [13,0,10,13,13,16,16]\nOutput: 19\nExplanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\n\n\n
Example 3:
\n\n\nInput: s = "6+0*1", answers = [12,9,6,4,8,6]\nOutput: 10\nExplanation: The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 31
s
represents a valid expression that contains only digits 0-9
, '+'
, and '*'
only.[0, 9]
.1 <=
The count of all operators ('+'
and '*'
) in the math expression <= 15
[0, 1000]
.n == answers.length
1 <= n <= 104
0 <= answers[i] <= 1000
You are given a 0-indexed 1-dimensional (1D) integer array original
, and two integers, m
and n
. You are tasked with creating a 2-dimensional (2D) array with m
rows and n
columns using all the elements from original
.
The elements from indices 0
to n - 1
(inclusive) of original
should form the first row of the constructed 2D array, the elements from indices n
to 2 * n - 1
(inclusive) should form the second row of the constructed 2D array, and so on.
Return an m x n
2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
\n
Example 1:
\n\nInput: original = [1,2,3,4], m = 2, n = 2\nOutput: [[1,2],[3,4]]\nExplanation: The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\n\n\n
Example 2:
\n\n\nInput: original = [1,2,3], m = 1, n = 3\nOutput: [[1,2,3]]\nExplanation: The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.\n\n\n
Example 3:
\n\n\nInput: original = [1,2], m = 1, n = 1\nOutput: []\nExplanation: There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n\n\n
\n
Constraints:
\n\n1 <= original.length <= 5 * 104
1 <= original[i] <= 105
1 <= m, n <= 4 * 104
Given an array of digit strings nums
and a digit string target
, return the number of pairs of indices (i, j)
(where i != j
) such that the concatenation of nums[i] + nums[j]
equals target
.
\n
Example 1:
\n\n\nInput: nums = ["777","7","77","77"], target = "7777"\nOutput: 4\nExplanation: Valid pairs are:\n- (0, 1): "777" + "7"\n- (1, 0): "7" + "777"\n- (2, 3): "77" + "77"\n- (3, 2): "77" + "77"\n\n\n
Example 2:
\n\n\nInput: nums = ["123","4","12","34"], target = "1234"\nOutput: 2\nExplanation: Valid pairs are:\n- (0, 1): "123" + "4"\n- (2, 3): "12" + "34"\n\n\n
Example 3:
\n\n\nInput: nums = ["1","1","1"], target = "11"\nOutput: 6\nExplanation: Valid pairs are:\n- (0, 1): "1" + "1"\n- (1, 0): "1" + "1"\n- (0, 2): "1" + "1"\n- (2, 0): "1" + "1"\n- (1, 2): "1" + "1"\n- (2, 1): "1" + "1"\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i].length <= 100
2 <= target.length <= 100
nums[i]
and target
consist of digits.nums[i]
and target
do not have leading zeros.A teacher is writing a test with n
true/false questions, with 'T'
denoting true and 'F'
denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey
, where answerKey[i]
is the original answer to the ith
question. In addition, you are given an integer k
, the maximum number of times you may perform the following operation:
'T'
or 'F'
(i.e., set answerKey[i]
to 'T'
or 'F'
).Return the maximum number of consecutive 'T'
s or 'F'
s in the answer key after performing the operation at most k
times.
\n
Example 1:
\n\n\nInput: answerKey = "TTFF", k = 2\nOutput: 4\nExplanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT".\nThere are four consecutive 'T's.\n\n\n
Example 2:
\n\n\nInput: answerKey = "TFFT", k = 1\nOutput: 3\nExplanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF".\nIn both cases, there are three consecutive 'F's.\n\n\n
Example 3:
\n\n\nInput: answerKey = "TTFTTFTT", k = 1\nOutput: 5\nExplanation: We can replace the first 'F' to make answerKey = "TTTTTFTT"\nAlternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". \nIn both cases, there are five consecutive 'T's.\n\n\n
\n
Constraints:
\n\nn == answerKey.length
1 <= n <= 5 * 104
answerKey[i]
is either 'T'
or 'F'
1 <= k <= n
You are given a 0-indexed integer array nums
of length n
. The number of ways to partition nums
is the number of pivot
indices that satisfy both conditions:
1 <= pivot < n
nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]
You are also given an integer k
. You can choose to change the value of one element of nums
to k
, or to leave the array unchanged.
Return the maximum possible number of ways to partition nums
to satisfy both conditions after changing at most one element.
\n
Example 1:
\n\n\nInput: nums = [2,-1,2], k = 3\nOutput: 1\nExplanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,0], k = 1\nOutput: 2\nExplanation: The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\n\n\n
Example 3:
\n\n\nInput: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput: 4\nExplanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 105
-105 <= k, nums[i] <= 105
You are given a string s
consisting of n
characters which are either 'X'
or 'O'
.
A move is defined as selecting three consecutive characters of s
and converting them to 'O'
. Note that if a move is applied to the character 'O'
, it will stay the same.
Return the minimum number of moves required so that all the characters of s
are converted to 'O'
.
\n
Example 1:
\n\n\nInput: s = "XXX"\nOutput: 1\nExplanation: XXX -> OOO\nWe select all the 3 characters and convert them in one move.\n\n\n
Example 2:
\n\n\nInput: s = "XXOX"\nOutput: 2\nExplanation: XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to\n\n'O'
.\nThen we select the last 3 characters and convert them so that the final string contains all'O'
s.
Example 3:
\n\n\nInput: s = "OOOO"\nOutput: 0\nExplanation: There are no\n\n'X's
ins
to convert.\n
\n
Constraints:
\n\n3 <= s.length <= 1000
s[i]
is either 'X'
or 'O'
.You have observations of n + m
6-sided dice rolls with each face numbered from 1
to 6
. n
of the observations went missing, and you only have the observations of m
rolls. Fortunately, you have also calculated the average value of the n + m
rolls.
You are given an integer array rolls
of length m
where rolls[i]
is the value of the ith
observation. You are also given the two integers mean
and n
.
Return an array of length n
containing the missing observations such that the average value of the n + m
rolls is exactly mean
. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.
The average value of a set of k
numbers is the sum of the numbers divided by k
.
Note that mean
is an integer, so the sum of the n + m
rolls should be divisible by n + m
.
\n
Example 1:
\n\n\nInput: rolls = [3,2,4,3], mean = 4, n = 2\nOutput: [6,6]\nExplanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\n\n\n
Example 2:
\n\n\nInput: rolls = [1,5,6], mean = 3, n = 4\nOutput: [2,3,2,2]\nExplanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\n\n\n
Example 3:
\n\n\nInput: rolls = [1,2,3,4], mean = 6, n = 4\nOutput: []\nExplanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n\n\n
\n
Constraints:
\n\nm == rolls.length
1 <= n, m <= 105
1 <= rolls[i], mean <= 6
Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones
, where stones[i]
is the value of the ith
stone.
Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones
. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3
. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).
Assuming both players play optimally, return true
if Alice wins and false
if Bob wins.
\n
Example 1:
\n\n\nInput: stones = [2,1]\nOutput: true\nExplanation: The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.\n\n\n
Example 2:
\n\n\nInput: stones = [2]\nOutput: false\nExplanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.\n\n\n
Example 3:
\n\n\nInput: stones = [5,1,2,4,3]\nOutput: false\nExplanation: Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.\n\n\n
\n
Constraints:
\n\n1 <= stones.length <= 105
1 <= stones[i] <= 104
You are given a string s
, an integer k
, a letter letter
, and an integer repetition
.
Return the lexicographically smallest subsequence of s
of length k
that has the letter letter
appear at least repetition
times. The test cases are generated so that the letter
appears in s
at least repetition
times.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
\n\nA string a
is lexicographically smaller than a string b
if in the first position where a
and b
differ, string a
has a letter that appears earlier in the alphabet than the corresponding letter in b
.
\n
Example 1:
\n\n\nInput: s = "leet", k = 3, letter = "e", repetition = 1\nOutput: "eet"\nExplanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n- "lee" (from "leet")\n- "let" (from "leet")\n- "let" (from "leet")\n- "eet" (from "leet")\nThe lexicographically smallest subsequence among them is "eet".\n\n\n
Example 2:
\n\nInput: s = "leetcode", k = 4, letter = "e", repetition = 2\nOutput: "ecde"\nExplanation: "ecde" is the lexicographically smallest subsequence of length 4 that has the letter "e" appear at least 2 times.\n\n\n
Example 3:
\n\n\nInput: s = "bb", k = 2, letter = "b", repetition = 2\nOutput: "bb"\nExplanation: "bb" is the only subsequence of length 2 that has the letter "b" appear at least 2 times.\n\n\n
\n
Constraints:
\n\n1 <= repetition <= k <= s.length <= 5 * 104
s
consists of lowercase English letters.letter
is a lowercase English letter, and appears in s
at least repetition
times.nums1
, nums2
, and nums3
, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.\n\n
Example 1:
\n\n\nInput: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput: [3,2]\nExplanation: The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.\n\n\n
Example 2:
\n\n\nInput: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput: [2,3,1]\nExplanation: The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput: []\nExplanation: No value is present in at least two arrays.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length, nums3.length <= 100
1 <= nums1[i], nums2[j], nums3[k] <= 100
You are given a 2D integer grid
of size m x n
and an integer x
. In one operation, you can add x
to or subtract x
from any element in the grid
.
A uni-value grid is a grid where all the elements of it are equal.
\n\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1
.
\n
Example 1:
\n\nInput: grid = [[2,4],[6,8]], x = 2\nOutput: 4\nExplanation: We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.\n\n\n
Example 2:
\n\nInput: grid = [[1,5],[2,3]], x = 1\nOutput: 5\nExplanation: We can make every element equal to 3.\n\n\n
Example 3:
\n\nInput: grid = [[1,2],[3,4]], x = 2\nOutput: -1\nExplanation: It is impossible to make every element equal.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= x, grid[i][j] <= 104
You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.
\n\nUnfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.
\n\nDesign an algorithm that:
\n\nImplement the StockPrice
class:
StockPrice()
Initializes the object with no price records.void update(int timestamp, int price)
Updates the price
of the stock at the given timestamp
.int current()
Returns the latest price of the stock.int maximum()
Returns the maximum price of the stock.int minimum()
Returns the minimum price of the stock.\n
Example 1:
\n\n\nInput\n["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]\n[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]\nOutput\n[null, null, null, 5, 10, null, 5, null, 2]\n\nExplanation\nStockPrice stockPrice = new StockPrice();\nstockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\nstockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\nstockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\nstockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\nstockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\nstockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\nstockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\nstockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.\n\n\n
\n
Constraints:
\n\n1 <= timestamp, price <= 109
105
calls will be made in total to update
, current
, maximum
, and minimum
.current
, maximum
, and minimum
will be called only after update
has been called at least once.You are given an integer array nums
of 2 * n
integers. You need to partition nums
into two arrays of length n
to minimize the absolute difference of the sums of the arrays. To partition nums
, put each element of nums
into one of the two arrays.
Return the minimum possible absolute difference.
\n\n\n
Example 1:
\n\nInput: nums = [3,9,7,3]\nOutput: 2\nExplanation: One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.\n\n\n
Example 2:
\n\n\nInput: nums = [-36,36]\nOutput: 72\nExplanation: One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.\n\n\n
Example 3:
\n\nInput: nums = [2,-1,0,4,-2,-9]\nOutput: 0\nExplanation: One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.\n\n\n
\n
Constraints:
\n\n1 <= n <= 15
nums.length == 2 * n
-107 <= nums[i] <= 107
There are n
availabe seats and n
students standing in a room. You are given an array seats
of length n
, where seats[i]
is the position of the ith
seat. You are also given the array students
of length n
, where students[j]
is the position of the jth
student.
You may perform the following move any number of times:
\n\nith
student by 1
(i.e., moving the ith
student from position x
to x + 1
or x - 1
)Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
\n\nNote that there may be multiple seats or students in the same position at the beginning.
\n\n\n
Example 1:
\n\n\nInput: seats = [3,1,5], students = [2,7,4]\nOutput: 4\nExplanation: The students are moved as follows:\n- The first student is moved from position 2 to position 1 using 1 move.\n- The second student is moved from position 7 to position 5 using 2 moves.\n- The third student is moved from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.\n\n\n
Example 2:
\n\n\nInput: seats = [4,1,5,9], students = [1,3,2,6]\nOutput: 7\nExplanation: The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from position 3 to position 4 using 1 move.\n- The third student is moved from position 2 to position 5 using 3 moves.\n- The fourth student is moved from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.\n\n\n
Example 3:
\n\n\nInput: seats = [2,2,6,6], students = [1,3,2,6]\nOutput: 4\nExplanation: Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from position 1 to position 2 using 1 move.\n- The second student is moved from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.\n\n\n
\n
Constraints:
\n\nn == seats.length == students.length
1 <= n <= 100
1 <= seats[i], students[j] <= 100
There are n
pieces arranged in a line, and each piece is colored either by 'A'
or by 'B'
. You are given a string colors
of length n
where colors[i]
is the color of the ith
piece.
Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.
\n\n'A'
if both its neighbors are also colored 'A'
. She is not allowed to remove pieces that are colored 'B'
.'B'
if both its neighbors are also colored 'B'
. He is not allowed to remove pieces that are colored 'A'
.Assuming Alice and Bob play optimally, return true
if Alice wins, or return false
if Bob wins.
\n
Example 1:
\n\n\nInput: colors = "AAABABB"\nOutput: true\nExplanation:\nAAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.\n\n\n
Example 2:
\n\n\nInput: colors = "AA"\nOutput: false\nExplanation:\nAlice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.\n\n\n
Example 3:
\n\n\nInput: colors = "ABBBBBBBAAA"\nOutput: false\nExplanation:\nABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.\n\n\n
\n
Constraints:
\n\n1 <= colors.length <= 105
colors
consists of only the letters 'A'
and 'B'
There is a network of n
servers, labeled from 0
to n - 1
. You are given a 2D integer array edges
, where edges[i] = [ui, vi]
indicates there is a message channel between servers ui
and vi
, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience
of length n
.
All servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.
\n\nThe server labeled 0
is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.
At the beginning of second 0
, each data server sends its message to be processed. Starting from second 1
, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:
i
will resend the message every patience[i]
second(s), i.e., the data server i
will resend the message if patience[i]
second(s) have elapsed since the last time the message was sent from this server.The network becomes idle when there are no messages passing between servers or arriving at servers.
\n\nReturn the earliest second starting from which the network becomes idle.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput: 8\nExplanation:\nAt (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.\n\n\n
Example 2:
\n\nInput: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput: 3\nExplanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.\n\n\n
\n
Constraints:
\n\nn == patience.length
2 <= n <= 105
patience[0] == 0
1 <= patience[i] <= 105
for 1 <= i < n
1 <= edges.length <= min(105, n * (n - 1) / 2)
edges[i].length == 2
0 <= ui, vi < n
ui != vi
nums1
and nums2
as well as an integer k
, return the kth
(1-based) smallest product of nums1[i] * nums2[j]
where 0 <= i < nums1.length
and 0 <= j < nums2.length
.\n\n
Example 1:
\n\n\nInput: nums1 = [2,5], nums2 = [3,4], k = 2\nOutput: 8\nExplanation: The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2nd smallest product is 8.\n\n\n
Example 2:
\n\n\nInput: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\nOutput: 0\nExplanation: The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6th smallest product is 0.\n\n\n
Example 3:
\n\n\nInput: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\nOutput: -6\nExplanation: The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rd smallest product is -6.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 5 * 104
-105 <= nums1[i], nums2[j] <= 105
1 <= k <= nums1.length * nums2.length
nums1
and nums2
are sorted.A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9
with no leading zeros, or a word consisting of lowercase English letters.
"a puppy has 2 eyes 4 legs"
is a sentence with seven tokens: "2"
and "4"
are numbers and the other tokens such as "puppy"
are words.Given a string s
representing a sentence, you need to check if all the numbers in s
are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s
).
Return true
if so, or false
otherwise.
\n
Example 1:
\n\nInput: s = "1 box has 3 blue 4 red 6 green and 12 yellow marbles"\nOutput: true\nExplanation: The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.\n\n\n
Example 2:
\n\n\nInput: s = "hello world 5 x 5"\nOutput: false\nExplanation: The numbers in s are: 5, 5. They are not strictly increasing.\n\n\n
Example 3:
\n\nInput: s = "sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s"\nOutput: false\nExplanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 200
s
consists of lowercase English letters, spaces, and digits from 0
to 9
, inclusive.s
is between 2
and 100
, inclusive.s
are separated by a single space.s
.s
is a positive number less than 100
, with no leading zeros.s
contains no leading or trailing spaces.You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n
accounts numbered from 1
to n
. The initial balance of each account is stored in a 0-indexed integer array balance
, with the (i + 1)th
account having an initial balance of balance[i]
.
Execute all the valid transactions. A transaction is valid if:
\n\n1
and n
, andImplement the Bank
class:
Bank(long[] balance)
Initializes the object with the 0-indexed integer array balance
.boolean transfer(int account1, int account2, long money)
Transfers money
dollars from the account numbered account1
to the account numbered account2
. Return true
if the transaction was successful, false
otherwise.boolean deposit(int account, long money)
Deposit money
dollars into the account numbered account
. Return true
if the transaction was successful, false
otherwise.boolean withdraw(int account, long money)
Withdraw money
dollars from the account numbered account
. Return true
if the transaction was successful, false
otherwise.\n
Example 1:
\n\n\nInput\n["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"]\n[[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]\nOutput\n[null, true, true, true, false, false]\n\nExplanation\nBank bank = new Bank([10, 100, 20, 50, 30]);\nbank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\nbank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\nbank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\nbank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\nbank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.\n\n\n
\n
Constraints:
\n\nn == balance.length
1 <= n, account, account1, account2 <= 105
0 <= balance[i], money <= 1012
104
calls will be made to each function transfer
, deposit
, withdraw
.Given an integer array nums
, find the maximum possible bitwise OR of a subset of nums
and return the number of different non-empty subsets with the maximum bitwise OR.
An array a
is a subset of an array b
if a
can be obtained from b
by deleting some (possibly zero) elements of b
. Two subsets are considered different if the indices of the elements chosen are different.
The bitwise OR of an array a
is equal to a[0] OR a[1] OR ... OR a[a.length - 1]
(0-indexed).
\n
Example 1:
\n\n\nInput: nums = [3,1]\nOutput: 2\nExplanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2]\nOutput: 7\nExplanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,1,5]\nOutput: 6\nExplanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]\n\n
\n
Constraints:
\n\n1 <= nums.length <= 16
1 <= nums[i] <= 105
A city is represented as a bi-directional connected graph with n
vertices where each vertex is labeled from 1
to n
(inclusive). The edges in the graph are represented as a 2D integer array edges
, where each edges[i] = [ui, vi]
denotes a bi-directional edge between vertex ui
and vertex vi
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time
minutes.
Each vertex has a traffic signal which changes its color from green to red and vice versa every change
minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than the minimum value.
\n\n[2, 3, 4]
is 3
, and the second minimum value of [2, 2, 4]
is 4
.Given n
, edges
, time
, and change
, return the second minimum time it will take to go from vertex 1
to vertex n
.
Notes:
\n\n1
and n
.\n
Example 1:
\n\nInput: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5\nOutput: 13\nExplanation:\nThe figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes. \n\n\n
Example 2:
\n\nInput: n = 2, edges = [[1,2]], time = 3, change = 2\nOutput: 11\nExplanation:\nThe minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.\n\n
\n
Constraints:
\n\n2 <= n <= 104
n - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
1 <= time, change <= 103
A sentence consists of lowercase letters ('a'
to 'z'
), digits ('0'
to '9'
), hyphens ('-'
), punctuation marks ('!'
, '.'
, and ','
), and spaces (' '
) only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '
.
A token is a valid word if all three of the following are true:
\n\n'-'
. If present, it must be surrounded by lowercase characters ("a-b"
is valid, but "-ab"
and "ab-"
are not valid)."ab,"
, "cd!"
, and "."
are valid, but "a!b"
and "c.,"
are not valid).Examples of valid words include "a-b."
, "afad"
, "ba-c"
, "a!"
, and "!"
.
Given a string sentence
, return the number of valid words in sentence
.
\n
Example 1:
\n\n\nInput: sentence = "cat and dog"\nOutput: 3\nExplanation: The valid words in the sentence are "cat", "and", and "dog".\n\n\n
Example 2:
\n\n\nInput: sentence = "!this 1-s b8d!"\nOutput: 0\nExplanation: There are no valid words in the sentence.\n"!this" is invalid because it starts with a punctuation mark.\n"1-s" and "b8d" are invalid because they contain digits.\n\n\n
Example 3:
\n\n\nInput: sentence = "alice and bob are playing stone-game10"\nOutput: 5\nExplanation: The valid words in the sentence are "alice", "and", "bob", "are", and "playing".\n"stone-game10" is invalid because it contains digits.\n\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 1000
sentence
only contains lowercase English letters, digits, ' '
, '-'
, '!'
, '.'
, and ','
.1
token.An integer x
is numerically balanced if for every digit d
in the number x
, there are exactly d
occurrences of that digit in x
.
Given an integer n
, return the smallest numerically balanced number strictly greater than n
.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 22\nExplanation: \n22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.\n\n\n
Example 2:
\n\n\nInput: n = 1000\nOutput: 1333\nExplanation: \n1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.\n\n\n
Example 3:
\n\n\nInput: n = 3000\nOutput: 3133\nExplanation: \n3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.\n\n\n
\n
Constraints:
\n\n0 <= n <= 106
There is a binary tree rooted at 0
consisting of n
nodes. The nodes are labeled from 0
to n - 1
. You are given a 0-indexed integer array parents
representing the tree, where parents[i]
is the parent of node i
. Since node 0
is the root, parents[0] == -1
.
Each node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.
\n\nReturn the number of nodes that have the highest score.
\n\n\n
Example 1:
\n\nInput: parents = [-1,2,0,2,0]\nOutput: 3\nExplanation:\n- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.\n\n\n
Example 2:
\n\nInput: parents = [-1,2,0]\nOutput: 2\nExplanation:\n- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.\n\n\n
\n
Constraints:
\n\nn == parents.length
2 <= n <= 105
parents[0] == -1
0 <= parents[i] <= n - 1
for i != 0
parents
represents a valid binary tree.You are given an integer n
, which indicates that there are n
courses labeled from 1
to n
. You are also given a 2D integer array relations
where relations[j] = [prevCoursej, nextCoursej]
denotes that course prevCoursej
has to be completed before course nextCoursej
(prerequisite relationship). Furthermore, you are given a 0-indexed integer array time
where time[i]
denotes how many months it takes to complete the (i+1)th
course.
You must find the minimum number of months needed to complete all the courses following these rules:
\n\nReturn the minimum number of months needed to complete all the courses.
\n\nNote: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).
\n\n\n
Example 1:
\n\nInput: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\nOutput: 8\nExplanation: The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.\n\n\n
Example 2:
\n\nInput: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\nOutput: 12\nExplanation: The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.\n\n\n
\n
Constraints:
\n\n1 <= n <= 5 * 104
0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)
relations[j].length == 2
1 <= prevCoursej, nextCoursej <= n
prevCoursej != nextCoursej
[prevCoursej, nextCoursej]
are unique.time.length == n
1 <= time[i] <= 104
A distinct string is a string that is present only once in an array.
\n\nGiven an array of strings arr
, and an integer k
, return the kth
distinct string present in arr
. If there are fewer than k
distinct strings, return an empty string ""
.
Note that the strings are considered in the order in which they appear in the array.
\n\n\n
Example 1:
\n\n\nInput: arr = ["d","b","c","b","c","a"], k = 2\nOutput: "a"\nExplanation:\nThe only distinct strings in arr are "d" and "a".\n"d" appears 1st, so it is the 1st distinct string.\n"a" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, "a" is returned. \n\n\n
Example 2:
\n\n\nInput: arr = ["aaa","aa","a"], k = 1\nOutput: "aaa"\nExplanation:\nAll strings in arr are distinct, so the 1st string "aaa" is returned.\n\n\n
Example 3:
\n\n\nInput: arr = ["a","b","a"], k = 3\nOutput: ""\nExplanation:\nThe only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".\n\n\n
\n
Constraints:
\n\n1 <= k <= arr.length <= 1000
1 <= arr[i].length <= 5
arr[i]
consists of lowercase English letters.You are given a 0-indexed 2D integer array of events
where events[i] = [startTimei, endTimei, valuei]
. The ith
event starts at startTimei
and ends at endTimei
, and if you attend this event, you will receive a value of valuei
. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.
Return this maximum sum.
\n\nNote that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t
, the next event must start at or after t + 1
.
\n
Example 1:
\n\nInput: events = [[1,3,2],[4,5,2],[2,4,3]]\nOutput: 4\nExplanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.\n\n\n
Example 2:
\n\nInput: events = [[1,3,2],[4,5,2],[1,5,5]]\nOutput: 5\nExplanation: Choose event 2 for a sum of 5.\n\n\n
Example 3:
\n\nInput: events = [[1,5,3],[1,5,1],[6,6,5]]\nOutput: 8\nExplanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.\n\n
\n
Constraints:
\n\n2 <= events.length <= 105
events[i].length == 3
1 <= startTimei <= endTimei <= 109
1 <= valuei <= 106
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s
consisting of characters '*'
and '|'
only, where a '*'
represents a plate and a '|'
represents a candle.
You are also given a 0-indexed 2D integer array queries
where queries[i] = [lefti, righti]
denotes the substring s[lefti...righti]
(inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.
s = "||**||**|*"
, and a query [3, 8]
denotes the substring "*||**|"
. The number of plates between candles in this substring is 2
, as each of the two plates has at least one candle in the substring to its left and right.Return an integer array answer
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: s = "**|**|***|", queries = [[2,5],[5,9]]\nOutput: [2,3]\nExplanation:\n- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.\n\n\n
Example 2:
\n\nInput: s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\nOutput: [9,0,0,0,0]\nExplanation:\n- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 105
s
consists of '*'
and '|'
characters.1 <= queries.length <= 105
queries[i].length == 2
0 <= lefti <= righti < s.length
There is an 8 x 8
chessboard containing n
pieces (rooks, queens, or bishops). You are given a string array pieces
of length n
, where pieces[i]
describes the type (rook, queen, or bishop) of the ith
piece. In addition, you are given a 2D integer array positions
also of length n
, where positions[i] = [ri, ci]
indicates that the ith
piece is currently at the 1-based coordinate (ri, ci)
on the chessboard.
When making a move for a piece, you choose a destination square that the piece will travel toward and stop on.
\n\n(r, c)
to the direction of (r+1, c)
, (r-1, c)
, (r, c+1)
, or (r, c-1)
.(r, c)
to the direction of (r+1, c)
, (r-1, c)
, (r, c+1)
, (r, c-1)
, (r+1, c+1)
, (r+1, c-1)
, (r-1, c+1)
, (r-1, c-1)
.(r, c)
to the direction of (r+1, c+1)
, (r+1, c-1)
, (r-1, c+1)
, (r-1, c-1)
.You must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th
second. A move combination is invalid if, at a given time, two or more pieces occupy the same square.
Return the number of valid move combinations\u200b\u200b\u200b\u200b\u200b.
\n\nNotes:
\n\n\n
Example 1:
\n\nInput: pieces = ["rook"], positions = [[1,1]]\nOutput: 15\nExplanation: The image above shows the possible squares the piece can move to.\n\n\n
Example 2:
\n\nInput: pieces = ["queen"], positions = [[1,1]]\nOutput: 22\nExplanation: The image above shows the possible squares the piece can move to.\n\n\n
Example 3:
\n\nInput: pieces = ["bishop"], positions = [[4,3]]\nOutput: 12\nExplanation: The image above shows the possible squares the piece can move to.\n\n\n
\n
Constraints:
\n\nn == pieces.length
n == positions.length
1 <= n <= 4
pieces
only contains the strings "rook"
, "queen"
, and "bishop"
.1 <= ri, ci <= 8
positions[i]
is distinct.Given a 0-indexed integer array nums
, return the smallest index i
of nums
such that i mod 10 == nums[i]
, or -1
if such index does not exist.
x mod y
denotes the remainder when x
is divided by y
.
\n
Example 1:
\n\n\nInput: nums = [0,1,2]\nOutput: 0\nExplanation: \ni=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.\n\n\n
Example 2:
\n\n\nInput: nums = [4,3,2,1]\nOutput: 2\nExplanation: \ni=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4,5,6,7,8,9,0]\nOutput: -1\nExplanation: No index satisfies i mod 10 == nums[i].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 9
A critical point in a linked list is defined as either a local maxima or a local minima.
\n\nA node is a local maxima if the current node has a value strictly greater than the previous node and the next node.
\n\nA node is a local minima if the current node has a value strictly smaller than the previous node and the next node.
\n\nNote that a node can only be a local maxima/minima if there exists both a previous node and a next node.
\n\nGiven a linked list head
, return an array of length 2 containing [minDistance, maxDistance]
where minDistance
is the minimum distance between any two distinct critical points and maxDistance
is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1]
.
\n
Example 1:
\n\nInput: head = [3,1]\nOutput: [-1,-1]\nExplanation: There are no critical points in [3,1].\n\n\n
Example 2:
\n\nInput: head = [5,3,1,2,5,1,2]\nOutput: [1,3]\nExplanation: There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.\n\n\n
Example 3:
\n\nInput: head = [1,3,2,2,3,2,2,2,7]\nOutput: [3,3]\nExplanation: There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node.\n\n\n
\n
Constraints:
\n\n[2, 105]
.1 <= Node.val <= 105
You are given a 0-indexed integer array nums
containing distinct numbers, an integer start
, and an integer goal
. There is an integer x
that is initially set to start
, and you want to perform operations on x
such that it is converted to goal
. You can perform the following operation repeatedly on the number x
:
If 0 <= x <= 1000
, then for any index i
in the array (0 <= i < nums.length
), you can set x
to any of the following:
x + nums[i]
x - nums[i]
x ^ nums[i]
(bitwise-XOR)Note that you can use each nums[i]
any number of times in any order. Operations that set x
to be out of the range 0 <= x <= 1000
are valid, but no more operations can be done afterward.
Return the minimum number of operations needed to convert x = start
into goal
, and -1
if it is not possible.
\n
Example 1:
\n\n\nInput: nums = [2,4,12], start = 2, goal = 12\nOutput: 2\nExplanation: We can go from 2 → 14 → 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12\n\n\n
Example 2:
\n\n\nInput: nums = [3,5,7], start = 0, goal = -4\nOutput: 2\nExplanation: We can go from 0 → 3 → -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.\n\n\n
Example 3:
\n\n\nInput: nums = [2,8,16], start = 0, goal = 1\nOutput: -1\nExplanation: There is no way to convert 0 into 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-109 <= nums[i], goal <= 109
0 <= start <= 1000
start != goal
nums
are distinct.An original string, consisting of lowercase English letters, can be encoded by the following steps:
\n\nFor example, one way to encode an original string "abcdefghijklmnop"
might be:
["ab", "cdefghijklmn", "o", "p"]
.["ab", "12", "1", "p"]
."ab121p"
.Given two encoded strings s1
and s2
, consisting of lowercase English letters and digits 1-9
(inclusive), return true
if there exists an original string that could be encoded as both s1
and s2
. Otherwise, return false
.
Note: The test cases are generated such that the number of consecutive digits in s1
and s2
does not exceed 3
.
\n
Example 1:
\n\n\nInput: s1 = "internationalization", s2 = "i18n"\nOutput: true\nExplanation: It is possible that "internationalization" was the original string.\n- "internationalization" \n -> Split: ["internationalization"]\n -> Do not replace any element\n -> Concatenate: "internationalization", which is s1.\n- "internationalization"\n -> Split: ["i", "nternationalizatio", "n"]\n -> Replace: ["i", "18", "n"]\n -> Concatenate: "i18n", which is s2\n\n\n
Example 2:
\n\n\nInput: s1 = "l123e", s2 = "44"\nOutput: true\nExplanation: It is possible that "leetcode" was the original string.\n- "leetcode" \n -> Split: ["l", "e", "et", "cod", "e"]\n -> Replace: ["l", "1", "2", "3", "e"]\n -> Concatenate: "l123e", which is s1.\n- "leetcode" \n -> Split: ["leet", "code"]\n -> Replace: ["4", "4"]\n -> Concatenate: "44", which is s2.\n\n\n
Example 3:
\n\n\nInput: s1 = "a5b", s2 = "c5b"\nOutput: false\nExplanation: It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.\n\n\n
\n
Constraints:
\n\n1 <= s1.length, s2.length <= 40
s1
and s2
consist of digits 1-9
(inclusive), and lowercase English letters only.s1
and s2
does not exceed 3
.A substring is a contiguous (non-empty) sequence of characters within a string.
\n\nA vowel substring is a substring that only consists of vowels ('a'
, 'e'
, 'i'
, 'o'
, and 'u'
) and has all five vowels present in it.
Given a string word
, return the number of vowel substrings in word
.
\n
Example 1:
\n\n\nInput: word = "aeiouu"\nOutput: 2\nExplanation: The vowel substrings of word are as follows (underlined):\n- "aeiouu"\n- "aeiouu"\n\n\n
Example 2:
\n\n\nInput: word = "unicornarihan"\nOutput: 0\nExplanation: Not all 5 vowels are present, so there are no vowel substrings.\n\n\n
Example 3:
\n\n\nInput: word = "cuaieuouac"\nOutput: 7\nExplanation: The vowel substrings of word are as follows (underlined):\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n- "cuaieuouac"\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 100
word
consists of lowercase English letters only.Given a string word
, return the sum of the number of vowels ('a'
, 'e'
, 'i'
, 'o'
, and 'u'
) in every substring of word
.
A substring is a contiguous (non-empty) sequence of characters within a string.
\n\nNote: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.
\n\n\n
Example 1:
\n\n\nInput: word = "aba"\nOutput: 6\nExplanation: \nAll possible substrings are: "a", "ab", "aba", "b", "ba", and "a".\n- "b" has 0 vowels in it\n- "a", "ab", "ba", and "a" have 1 vowel each\n- "aba" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. \n\n\n
Example 2:
\n\n\nInput: word = "abc"\nOutput: 3\nExplanation: \nAll possible substrings are: "a", "ab", "abc", "b", "bc", and "c".\n- "a", "ab", and "abc" have 1 vowel each\n- "b", "bc", and "c" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.\n\n\n
Example 3:
\n\n\nInput: word = "ltcd"\nOutput: 0\nExplanation: There are no vowels in any substring of "ltcd".\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 105
word
consists of lowercase English letters.You are given an integer n
indicating there are n
specialty retail stores. There are m
product types of varying amounts, which are given as a 0-indexed integer array quantities
, where quantities[i]
represents the number of products of the ith
product type.
You need to distribute all products to the retail stores following these rules:
\n\n0
). Let x
represent the maximum number of products given to any store. You want x
to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.Return the minimum possible x
.
\n
Example 1:
\n\n\nInput: n = 6, quantities = [11,6]\nOutput: 3\nExplanation: One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.\n\n\n
Example 2:
\n\n\nInput: n = 7, quantities = [15,10,10]\nOutput: 5\nExplanation: One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.\n\n\n
Example 3:
\n\n\nInput: n = 1, quantities = [100000]\nOutput: 100000\nExplanation: The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.\n\n\n
\n
Constraints:
\n\nm == quantities.length
1 <= m <= n <= 105
1 <= quantities[i] <= 105
There is an undirected graph with n
nodes numbered from 0
to n - 1
(inclusive). You are given a 0-indexed integer array values
where values[i]
is the value of the ith
node. You are also given a 0-indexed 2D integer array edges
, where each edges[j] = [uj, vj, timej]
indicates that there is an undirected edge between the nodes uj
and vj
, and it takes timej
seconds to travel between the two nodes. Finally, you are given an integer maxTime
.
A valid path in the graph is any path that starts at node 0
, ends at node 0
, and takes at most maxTime
seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).
Return the maximum quality of a valid path.
\n\nNote: There are at most four edges connected to each node.
\n\n\n
Example 1:
\n\nInput: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49\nOutput: 75\nExplanation:\nOne possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.\n\n\n
Example 2:
\n\nInput: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\nOutput: 25\nExplanation:\nOne possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.\n\n\n
Example 3:
\n\nInput: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\nOutput: 7\nExplanation:\nOne possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.\n\n\n
\n
Constraints:
\n\nn == values.length
1 <= n <= 1000
0 <= values[i] <= 108
0 <= edges.length <= 2000
edges[j].length == 3
0 <= uj < vj <= n - 1
10 <= timej, maxTime <= 100
[uj, vj]
are unique.Two strings word1
and word2
are considered almost equivalent if the differences between the frequencies of each letter from 'a'
to 'z'
between word1
and word2
is at most 3
.
Given two strings word1
and word2
, each of length n
, return true
if word1
and word2
are almost equivalent, or false
otherwise.
The frequency of a letter x
is the number of times it occurs in the string.
\n
Example 1:
\n\n\nInput: word1 = "aaaa", word2 = "bccb"\nOutput: false\nExplanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb".\nThe difference is 4, which is more than the allowed 3.\n\n\n
Example 2:
\n\n\nInput: word1 = "abcdeef", word2 = "abaaacc"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.\n\n\n
Example 3:
\n\n\nInput: word1 = "cccddabba", word2 = "babababab"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.\n\n\n
\n
Constraints:
\n\nn == word1.length == word2.length
1 <= n <= 100
word1
and word2
consist only of lowercase English letters.A width x height
grid is on an XY-plane with the bottom-left cell at (0, 0)
and the top-right cell at (width - 1, height - 1)
. The grid is aligned with the four cardinal directions ("North"
, "East"
, "South"
, and "West"
). A robot is initially at cell (0, 0)
facing direction "East"
.
The robot can be instructed to move for a specific number of steps. For each step, it does the following.
\n\nAfter the robot finishes moving the number of steps required, it stops and awaits the next instruction.
\n\nImplement the Robot
class:
Robot(int width, int height)
Initializes the width x height
grid with the robot at (0, 0)
facing "East"
.void step(int num)
Instructs the robot to move forward num
steps.int[] getPos()
Returns the current cell the robot is at, as an array of length 2, [x, y]
.String getDir()
Returns the current direction of the robot, "North"
, "East"
, "South"
, or "West"
.\n
Example 1:
\n\nInput\n["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"]\n[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]\nOutput\n[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]\n\nExplanation\nRobot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\nrobot.step(2); // It moves two steps East to (2, 0), and faces East.\nrobot.step(2); // It moves two steps East to (4, 0), and faces East.\nrobot.getPos(); // return [4, 0]\nrobot.getDir(); // return "East"\nrobot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\nrobot.step(1); // It moves one step North to (5, 2), and faces North (not West).\nrobot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\nrobot.getPos(); // return [1, 2]\nrobot.getDir(); // return "West"\n\n\n\n
\n
Constraints:
\n\n2 <= width, height <= 100
1 <= num <= 105
104
calls in total will be made to step
, getPos
, and getDir
.You are given a 2D integer array items
where items[i] = [pricei, beautyi]
denotes the price and beauty of an item respectively.
You are also given a 0-indexed integer array queries
. For each queries[j]
, you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]
. If no such item exists, then the answer to this query is 0
.
Return an array answer
of the same length as queries
where answer[j]
is the answer to the jth
query.
\n
Example 1:
\n\n\nInput: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]\nOutput: [2,4,5,5,6,6]\nExplanation:\n- For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n- For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n- For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n- For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.\n\n\n
Example 2:
\n\n\nInput: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]\nOutput: [4]\nExplanation: \nThe price of every item is equal to 1, so we choose the item with the maximum beauty 4. \nNote that multiple items can have the same price and/or beauty. \n\n\n
Example 3:
\n\n\nInput: items = [[10,1000]], queries = [5]\nOutput: [0]\nExplanation:\nNo item has a price less than or equal to 5, so no item can be chosen.\nHence, the answer to the query is 0.\n\n\n
\n
Constraints:
\n\n1 <= items.length, queries.length <= 105
items[i].length == 2
1 <= pricei, beautyi, queries[j] <= 109
You have n
tasks and m
workers. Each task has a strength requirement stored in a 0-indexed integer array tasks
, with the ith
task requiring tasks[i]
strength to complete. The strength of each worker is stored in a 0-indexed integer array workers
, with the jth
worker having workers[j]
strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]
).
Additionally, you have pills
magical pills that will increase a worker's strength by strength
. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill.
Given the 0-indexed integer arrays tasks
and workers
and the integers pills
and strength
, return the maximum number of tasks that can be completed.
\n
Example 1:
\n\n\nInput: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1\nOutput: 3\nExplanation:\nWe can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)\n\n\n
Example 2:
\n\n\nInput: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5\nOutput: 1\nExplanation:\nWe can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)\n\n\n
Example 3:
\n\n\nInput: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\nOutput: 2\nExplanation:\nWe can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.\n\n\n
\n
Constraints:
\n\nn == tasks.length
m == workers.length
1 <= n, m <= 5 * 104
0 <= pills <= m
0 <= tasks[i], workers[j], strength <= 109
There are n
people in a line queuing to buy tickets, where the 0th
person is at the front of the line and the (n - 1)th
person is at the back of the line.
You are given a 0-indexed integer array tickets
of length n
where the number of tickets that the ith
person would like to buy is tickets[i]
.
Each person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.
\n\nReturn the time taken for the person initially at position k (0-indexed) to finish buying tickets.
\n\n\n
Example 1:
\n\nInput: tickets = [2,3,2], k = 2
\n\nOutput: 6
\n\nExplanation:
\n\nExample 2:
\n\nInput: tickets = [5,1,1,1], k = 0
\n\nOutput: 8
\n\nExplanation:
\n\n\n
Constraints:
\n\nn == tickets.length
1 <= n <= 100
1 <= tickets[i] <= 100
0 <= k < n
You are given the head
of a linked list.
The nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...
). The length of a group is the number of nodes assigned to it. In other words,
1st
node is assigned to the first group.2nd
and the 3rd
nodes are assigned to the second group.4th
, 5th
, and 6th
nodes are assigned to the third group, and so on.Note that the length of the last group may be less than or equal to 1 + the length of the second to last group
.
Reverse the nodes in each group with an even length, and return the head
of the modified linked list.
\n
Example 1:
\n\nInput: head = [5,2,6,3,9,1,7,3,8,4]\nOutput: [5,6,2,3,9,1,4,8,3,7]\nExplanation:\n- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.\n\n\n
Example 2:
\n\nInput: head = [1,1,0,6]\nOutput: [1,0,1,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.\n\n\n
Example 3:
\n\nInput: head = [1,1,0,6,5]\nOutput: [1,0,1,5,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.\n\n\n
\n
Constraints:
\n\n[1, 105]
.0 <= Node.val <= 105
A string originalText
is encoded using a slanted transposition cipher to a string encodedText
with the help of a matrix having a fixed number of rows rows
.
originalText
is placed first in a top-left to bottom-right manner.
The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText
. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '
. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText
.
encodedText
is then formed by appending all characters of the matrix in a row-wise fashion.
The characters in the blue cells are appended first to encodedText
, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.
For example, if originalText = "cipher"
and rows = 3
, then we encode it in the following manner:
The blue arrows depict how originalText
is placed in the matrix, and the red arrows denote the order in which encodedText
is formed. In the above example, encodedText = "ch ie pr"
.
Given the encoded string encodedText
and number of rows rows
, return the original string originalText
.
Note: originalText
does not have any trailing spaces ' '
. The test cases are generated such that there is only one possible originalText
.
\n
Example 1:
\n\n\nInput: encodedText = "ch ie pr", rows = 3\nOutput: "cipher"\nExplanation: This is the same example described in the problem description.\n\n\n
Example 2:
\n\nInput: encodedText = "iveo eed l te olc", rows = 4\nOutput: "i love leetcode"\nExplanation: The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.\n\n\n
Example 3:
\n\nInput: encodedText = "coding", rows = 1\nOutput: "coding"\nExplanation: Since there is only 1 row, both originalText and encodedText are the same.\n\n\n
\n
Constraints:
\n\n0 <= encodedText.length <= 106
encodedText
consists of lowercase English letters and ' '
only.encodedText
is a valid encoding of some originalText
that does not have trailing spaces.1 <= rows <= 1000
originalText
.You are given an integer n
indicating the number of people in a network. Each person is labeled from 0
to n - 1
.
You are also given a 0-indexed 2D integer array restrictions
, where restrictions[i] = [xi, yi]
means that person xi
and person yi
cannot become friends, either directly or indirectly through other people.
Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests
, where requests[j] = [uj, vj]
is a friend request between person uj
and person vj
.
A friend request is successful if uj
and vj
can be friends. Each friend request is processed in the given order (i.e., requests[j]
occurs before requests[j + 1]
), and upon a successful request, uj
and vj
become direct friends for all future friend requests.
Return a boolean array result
, where each result[j]
is true
if the jth
friend request is successful or false
if it is not.
Note: If uj
and vj
are already direct friends, the request is still successful.
\n
Example 1:
\n\n\nInput: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).\n\n\n
Example 2:
\n\n\nInput: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).\n\n\n
Example 3:
\n\n\nInput: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput: [true,false,true,false]\nExplanation:\nRequest 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
0 <= restrictions.length <= 1000
restrictions[i].length == 2
0 <= xi, yi <= n - 1
xi != yi
1 <= requests.length <= 1000
requests[j].length == 2
0 <= uj, vj <= n - 1
uj != vj
There are n
houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors
of length n
, where colors[i]
represents the color of the ith
house.
Return the maximum distance between two houses with different colors.
\n\nThe distance between the ith
and jth
houses is abs(i - j)
, where abs(x)
is the absolute value of x
.
\n
Example 1:
\n\nInput: colors = [1,1,1,6,1,1,1]\nOutput: 3\nExplanation: In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.\n\n\n
Example 2:
\n\nInput: colors = [1,8,3,8,3]\nOutput: 4\nExplanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.\n\n\n
Example 3:
\n\n\nInput: colors = [0,1]\nOutput: 1\nExplanation: The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.\n\n\n
\n
Constraints:
\n\nn == colors.length
2 <= n <= 100
0 <= colors[i] <= 100
You want to water n
plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0
to n - 1
from left to right where the ith
plant is located at x = i
. There is a river at x = -1
that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the plants in the following way:
\n\nYou are initially at the river (i.e., x = -1
). It takes one step to move one unit on the x-axis.
Given a 0-indexed integer array plants
of n
integers, where plants[i]
is the amount of water the ith
plant needs, and an integer capacity
representing the watering can capacity, return the number of steps needed to water all the plants.
\n
Example 1:
\n\n\nInput: plants = [2,2,3,3], capacity = 5\nOutput: 14\nExplanation: Start at the river with a full watering can:\n- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.\n- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.\n- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).\n- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.\n- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).\n- Walk to plant 3 (4 steps) and water it.\nSteps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.\n\n\n
Example 2:
\n\n\nInput: plants = [1,1,1,4,2,3], capacity = 4\nOutput: 30\nExplanation: Start at the river with a full watering can:\n- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).\n- Water plant 3 (4 steps). Return to river (4 steps).\n- Water plant 4 (5 steps). Return to river (5 steps).\n- Water plant 5 (6 steps).\nSteps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.\n\n\n
Example 3:
\n\n\nInput: plants = [7,7,7,7,7,7,7], capacity = 8\nOutput: 49\nExplanation: You have to refill before watering each plant.\nSteps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.\n\n\n
\n
Constraints:
\n\nn == plants.length
1 <= n <= 1000
1 <= plants[i] <= 106
max(plants[i]) <= capacity <= 109
Design a data structure to find the frequency of a given value in a given subarray.
\n\nThe frequency of a value in a subarray is the number of occurrences of that value in the subarray.
\n\nImplement the RangeFreqQuery
class:
RangeFreqQuery(int[] arr)
Constructs an instance of the class with the given 0-indexed integer array arr
.int query(int left, int right, int value)
Returns the frequency of value
in the subarray arr[left...right]
.A subarray is a contiguous sequence of elements within an array. arr[left...right]
denotes the subarray that contains the elements of nums
between indices left
and right
(inclusive).
\n
Example 1:
\n\n\nInput\n["RangeFreqQuery", "query", "query"]\n[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]\nOutput\n[null, 1, 2]\n\nExplanation\nRangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\nrangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\nrangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i], value <= 104
0 <= left <= right < arr.length
105
calls will be made to query
A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.
\n\n9
is a 2-mirror number. The representation of 9
in base-10 and base-2 are 9
and 1001
respectively, which read the same both forward and backward.4
is not a 2-mirror number. The representation of 4
in base-2 is 100
, which does not read the same both forward and backward.Given the base k
and the number n
, return the sum of the n
smallest k-mirror numbers.
\n
Example 1:
\n\n\nInput: k = 2, n = 5\nOutput: 25\nExplanation:\nThe 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25. \n\n\n
Example 2:
\n\n\nInput: k = 3, n = 7\nOutput: 499\nExplanation:\nThe 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.\n\n\n
Example 3:
\n\n\nInput: k = 7, n = 17\nOutput: 20379000\nExplanation: The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596\n\n\n
\n
Constraints:
\n\n2 <= k <= 9
1 <= n <= 30
Given two string arrays words1
and words2
, return the number of strings that appear exactly once in each of the two arrays.
\n
Example 1:
\n\n\nInput: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]\nOutput: 2\nExplanation:\n- "leetcode" appears exactly once in each of the two arrays. We count this string.\n- "amazing" appears exactly once in each of the two arrays. We count this string.\n- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- "as" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.\n\n\n
Example 2:
\n\n\nInput: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]\nOutput: 0\nExplanation: There are no strings that appear in each of the two arrays.\n\n\n
Example 3:
\n\n\nInput: words1 = ["a","ab"], words2 = ["a","a","a","ab"]\nOutput: 1\nExplanation: The only string that appears exactly once in each of the two arrays is "ab".\n\n\n
\n
Constraints:
\n\n1 <= words1.length, words2.length <= 1000
1 <= words1[i].length, words2[j].length <= 30
words1[i]
and words2[j]
consists only of lowercase English letters.You are given a 0-indexed string hamsters
where hamsters[i]
is either:
'H'
indicating that there is a hamster at index i
, or'.'
indicating that index i
is empty.You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i
can be fed if you place a food bucket at index i - 1
and/or at index i + 1
.
Return the minimum number of food buckets you should place at empty indices to feed all the hamsters or -1
if it is impossible to feed all of them.
\n
Example 1:
\n\nInput: hamsters = "H..H"\nOutput: 2\nExplanation: We place two food buckets at indices 1 and 2.\nIt can be shown that if we place only one food bucket, one of the hamsters will not be fed.\n\n\n
Example 2:
\n\nInput: hamsters = ".H.H."\nOutput: 1\nExplanation: We place one food bucket at index 2.\n\n\n
Example 3:
\n\nInput: hamsters = ".HHH."\nOutput: -1\nExplanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.\n\n\n
\n
Constraints:
\n\n1 <= hamsters.length <= 105
hamsters[i]
is either'H'
or '.'
.There is an m x n
grid, where (0, 0)
is the top-left cell and (m - 1, n - 1)
is the bottom-right cell. You are given an integer array startPos
where startPos = [startrow, startcol]
indicates that initially, a robot is at the cell (startrow, startcol)
. You are also given an integer array homePos
where homePos = [homerow, homecol]
indicates that its home is at the cell (homerow, homecol)
.
The robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts
of length m
and colCosts
of length n
.
r
, then this move costs rowCosts[r]
.c
, then this move costs colCosts[c]
.Return the minimum total cost for this robot to return home.
\n\n\n
Example 1:
\n\nInput: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput: 18\nExplanation: One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2, 1). This move costs colCosts[1] = 2.\n-> It goes right to (2, 2). This move costs colCosts[2] = 6.\n-> It goes right to (2, 3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18\n\n
Example 2:
\n\n\nInput: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput: 0\nExplanation: The robot is already at its home. Since no moves occur, the total cost is 0.\n\n\n
\n
Constraints:
\n\nm == rowCosts.length
n == colCosts.length
1 <= m, n <= 105
0 <= rowCosts[r], colCosts[c] <= 104
startPos.length == 2
homePos.length == 2
0 <= startrow, homerow < m
0 <= startcol, homecol < n
A farmer has a rectangular grid of land with m
rows and n
columns that can be divided into unit cells. Each cell is either fertile (represented by a 1
) or barren (represented by a 0
). All cells outside the grid are considered barren.
A pyramidal plot of land can be defined as a set of cells with the following criteria:
\n\n1
and all cells must be fertile.(r, c)
be the apex of the pyramid, and its height be h
. Then, the plot comprises of cells (i, j)
where r <= i <= r + h - 1
and c - (i - r) <= j <= c + (i - r)
.An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:
\n\n1
and all cells must be fertile.(r, c)
be the apex of the pyramid, and its height be h
. Then, the plot comprises of cells (i, j)
where r - h + 1 <= i <= r
and c - (r - i) <= j <= c + (r - i)
.Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.
\nGiven a 0-indexed m x n
binary matrix grid
representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid
.
\n
Example 1:
\n\nInput: grid = [[0,1,1,0],[1,1,1,1]]\nOutput: 2\nExplanation: The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.\n\n\n
Example 2:
\n\nInput: grid = [[1,1,1],[1,1,1]]\nOutput: 2\nExplanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.\n\n\n
Example 3:
\n\nInput: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]\nOutput: 13\nExplanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
grid[i][j]
is either 0
or 1
.You are given a 0-indexed integer array nums
and a target element target
.
A target index is an index i
such that nums[i] == target
.
Return a list of the target indices of nums
after sorting nums
in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.
\n
Example 1:
\n\n\nInput: nums = [1,2,5,2,3], target = 2\nOutput: [1,2]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,5,2,3], target = 3\nOutput: [3]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,5,2,3], target = 5\nOutput: [4]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i], target <= 100
You are given a 0-indexed array nums
of n
integers, and an integer k
.
The k-radius average for a subarray of nums
centered at some index i
with the radius k
is the average of all elements in nums
between the indices i - k
and i + k
(inclusive). If there are less than k
elements before or after the index i
, then the k-radius average is -1
.
Build and return an array avgs
of length n
where avgs[i]
is the k-radius average for the subarray centered at index i
.
The average of x
elements is the sum of the x
elements divided by x
, using integer division. The integer division truncates toward zero, which means losing its fractional part.
2
, 3
, 1
, and 5
is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75
, which truncates to 2
.\n
Example 1:
\n\nInput: nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput: [-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:\n- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.\n\n\n
Example 2:
\n\n\nInput: nums = [100000], k = 0\nOutput: [100000]\nExplanation:\n- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.\n\n\n
Example 3:
\n\n\nInput: nums = [8], k = 100000\nOutput: [-1]\nExplanation: \n- avg[0] is -1 because there are less than k elements before and after index 0.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
0 <= nums[i], k <= 105
You are given a 0-indexed array of distinct integers nums
.
There is an element in nums
that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.
A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.
\n\nReturn the minimum number of deletions it would take to remove both the minimum and maximum element from the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,10,7,5,4,1,8,6]\nOutput: 5\nExplanation: \nThe minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.\n\n\n
Example 2:
\n\n\nInput: nums = [0,-4,19,1,8,-2,-3,5]\nOutput: 3\nExplanation: \nThe minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.\n\n\n
Example 3:
\n\n\nInput: nums = [101]\nOutput: 1\nExplanation: \nThere is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-105 <= nums[i] <= 105
nums
are distinct.You are given an integer n
indicating there are n
people numbered from 0
to n - 1
. You are also given a 0-indexed 2D integer array meetings
where meetings[i] = [xi, yi, timei]
indicates that person xi
and person yi
have a meeting at timei
. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson
.
Person 0
has a secret and initially shares the secret with a person firstPerson
at time 0
. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi
has the secret at timei
, then they will share the secret with person yi
, and vice versa.
The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.
\n\nReturn a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\nOutput: [0,1,2,3,5]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.\u200b\u200b\u200b\u200b\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.\n\n\n
Example 2:
\n\n\nInput: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\nOutput: [0,1,3]\nExplanation:\nAt time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.\n\n\n
Example 3:
\n\n\nInput: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\nOutput: [0,1,2,3,4]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
1 <= meetings.length <= 105
meetings[i].length == 3
0 <= xi, yi <= n - 1
xi != yi
1 <= timei <= 105
1 <= firstPerson <= n - 1
You are given an integer array digits
, where each element is a digit. The array may contain duplicates.
You need to find all the unique integers that follow the given requirements:
\n\ndigits
in any arbitrary order.For example, if the given digits
were [1, 2, 3]
, integers 132
and 312
follow the requirements.
Return a sorted array of the unique integers.
\n\n\n
Example 1:
\n\n\nInput: digits = [2,1,3,0]\nOutput: [102,120,130,132,210,230,302,310,312,320]\nExplanation: All the possible integers that follow the requirements are in the output array. \nNotice that there are no odd integers or integers with leading zeros.\n\n\n
Example 2:
\n\n\nInput: digits = [2,2,8,8,2]\nOutput: [222,228,282,288,822,828,882]\nExplanation: The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882. \n\n\n
Example 3:
\n\n\nInput: digits = [3,7,5]\nOutput: []\nExplanation: No even integers can be formed using the given digits.\n\n\n
\n
Constraints:
\n\n3 <= digits.length <= 100
0 <= digits[i] <= 9
You are given the head
of a linked list. Delete the middle node, and return the head
of the modified linked list.
The middle node of a linked list of size n
is the ⌊n / 2⌋th
node from the start using 0-based indexing, where ⌊x⌋
denotes the largest integer less than or equal to x
.
n
= 1
, 2
, 3
, 4
, and 5
, the middle nodes are 0
, 1
, 1
, 2
, and 2
, respectively.\n
Example 1:
\n\nInput: head = [1,3,4,7,1,2,6]\nOutput: [1,3,4,1,2,6]\nExplanation:\nThe above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node. \n\n\n
Example 2:
\n\nInput: head = [1,2,3,4]\nOutput: [1,2,4]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.\n\n\n
Example 3:
\n\nInput: head = [2,1]\nOutput: [2]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 105
You are given the root
of a binary tree with n
nodes. Each node is uniquely assigned a value from 1
to n
. You are also given an integer startValue
representing the value of the start node s
, and a different integer destValue
representing the value of the destination node t
.
Find the shortest path starting from node s
and ending at node t
. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L'
, 'R'
, and 'U'
. Each letter indicates a specific direction:
'L'
means to go from a node to its left child node.'R'
means to go from a node to its right child node.'U'
means to go from a node to its parent node.Return the step-by-step directions of the shortest path from node s
to node t
.
\n
Example 1:
\n\nInput: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput: "UURL"\nExplanation: The shortest path is: 3 → 1 → 5 → 2 → 6.\n\n\n
Example 2:
\n\nInput: root = [2,1], startValue = 2, destValue = 1\nOutput: "L"\nExplanation: The shortest path is: 2 → 1.\n\n\n
\n
Constraints:
\n\nn
.2 <= n <= 105
1 <= Node.val <= n
1 <= startValue, destValue <= n
startValue != destValue
You are given a 0-indexed 2D integer array pairs
where pairs[i] = [starti, endi]
. An arrangement of pairs
is valid if for every index i
where 1 <= i < pairs.length
, we have endi-1 == starti
.
Return any valid arrangement of pairs
.
Note: The inputs will be generated such that there exists a valid arrangement of pairs
.
\n
Example 1:
\n\n\nInput: pairs = [[5,1],[4,5],[11,9],[9,4]]\nOutput: [[11,9],[9,4],[4,5],[5,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 9 == 9 = start1 \nend1 = 4 == 4 = start2\nend2 = 5 == 5 = start3\n\n\n
Example 2:
\n\n\nInput: pairs = [[1,3],[3,2],[2,1]]\nOutput: [[1,3],[3,2],[2,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 3 == 3 = start1\nend1 = 2 == 2 = start2\nThe arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.\n\n\n
Example 3:
\n\n\nInput: pairs = [[1,2],[1,3],[2,1]]\nOutput: [[1,2],[2,1],[1,3]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 2 == 2 = start1\nend1 = 1 == 1 = start2\n\n\n
\n
Constraints:
\n\n1 <= pairs.length <= 105
pairs[i].length == 2
0 <= starti, endi <= 109
starti != endi
pairs
.You are given an integer array nums
and an integer k
. You want to find a subsequence of nums
of length k
that has the largest sum.
Return any such subsequence as an integer array of length k
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,3,3], k = 2\nOutput: [3,3]\nExplanation:\nThe subsequence has the largest sum of 3 + 3 = 6.\n\n
Example 2:
\n\n\nInput: nums = [-1,-2,3,4], k = 3\nOutput: [-1,3,4]\nExplanation: \nThe subsequence has the largest sum of -1 + 3 + 4 = 6.\n\n\n
Example 3:
\n\n\nInput: nums = [3,4,3,3], k = 2\nOutput: [3,4]\nExplanation:\nThe subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-105 <= nums[i] <= 105
1 <= k <= nums.length
You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security
, where security[i]
is the number of guards on duty on the ith
day. The days are numbered starting from 0
. You are also given an integer time
.
The ith
day is a good day to rob the bank if:
time
days before and after the ith
day,time
days before i
are non-increasing, andtime
days after i
are non-decreasing.More formally, this means day i
is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]
.
Return a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.
\n\n\n
Example 1:
\n\n\nInput: security = [5,3,3,3,5,6,2], time = 2\nOutput: [2,3]\nExplanation:\nOn day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.\n\n\n
Example 2:
\n\n\nInput: security = [1,1,1,1,1], time = 0\nOutput: [0,1,2,3,4]\nExplanation:\nSince time equals 0, every day is a good day to rob the bank, so return every day.\n\n\n
Example 3:
\n\n\nInput: security = [1,2,3,4,5,6], time = 2\nOutput: []\nExplanation:\nNo day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.\n\n\n
\n
Constraints:
\n\n1 <= security.length <= 105
0 <= security[i], time <= 105
You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.
\n\nThe bombs are represented by a 0-indexed 2D integer array bombs
where bombs[i] = [xi, yi, ri]
. xi
and yi
denote the X-coordinate and Y-coordinate of the location of the ith
bomb, whereas ri
denotes the radius of its range.
You may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.
\n\nGiven the list of bombs
, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.
\n
Example 1:
\n\nInput: bombs = [[2,1,3],[6,1,4]]\nOutput: 2\nExplanation:\nThe above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.\n\n\n
Example 2:
\n\nInput: bombs = [[1,1,5],[10,10,5]]\nOutput: 1\nExplanation:\nDetonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.\n\n\n
Example 3:
\n\nInput: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\nOutput: 5\nExplanation:\nThe best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.\n\n\n
\n
Constraints:
\n\n1 <= bombs.length <= 100
bombs[i].length == 3
1 <= xi, yi, ri <= 105
A scenic location is represented by its name
and attractiveness score
, where name
is a unique string among all locations and score
is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better.
You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:
\n\nith
best location of all locations already added, where i
is the number of times the system has been queried (including the current query).\n\t4th
time, it returns the 4th
best location of all locations already added.Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system.
\n\nImplement the SORTracker
class:
SORTracker()
Initializes the tracker system.void add(string name, int score)
Adds a scenic location with name
and score
to the system.string get()
Queries and returns the ith
best location, where i
is the number of times this method has been invoked (including this invocation).\n
Example 1:
\n\n\nInput\n["SORTracker", "add", "add", "get", "add", "get", "add", "get", "add", "get", "add", "get", "get"]\n[[], ["bradford", 2], ["branford", 3], [], ["alps", 2], [], ["orland", 2], [], ["orlando", 3], [], ["alpine", 2], [], []]\nOutput\n[null, null, null, "branford", null, "alps", null, "bradford", null, "bradford", null, "bradford", "orland"]\n\nExplanation\nSORTracker tracker = new SORTracker(); // Initialize the tracker system.\ntracker.add("bradford", 2); // Add location with name="bradford" and score=2 to the system.\ntracker.add("branford", 3); // Add location with name="branford" and score=3 to the system.\ntracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to its higher score (3 > 2).\n // This is the 1st time get() is called, so return the best location: "branford".\ntracker.add("alps", 2); // Add location with name="alps" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because "alps" is lexicographically smaller than "bradford".\n // Return the 2nd best location "alps", as it is the 2nd time get() is called.\ntracker.add("orland", 2); // Add location with name="orland" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return "bradford", as it is the 3rd time get() is called.\ntracker.add("orlando", 3); // Add location with name="orlando" and score=3 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return "bradford".\ntracker.add("alpine", 2); // Add location with name="alpine" and score=2 to the system.\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return "bradford".\ntracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return "orland".\n\n\n
\n
Constraints:
\n\nname
consists of lowercase English letters, and is unique among all locations.1 <= name.length <= 10
1 <= score <= 105
get
does not exceed the number of calls to add
.4 * 104
calls in total will be made to add
and get
.There are n
rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0
to 9
.
You are given a string rings
of length 2n
that describes the n
rings that are placed onto the rods. Every two characters in rings
forms a color-position pair that is used to describe each ring where:
ith
pair denotes the ith
ring's color ('R'
, 'G'
, 'B'
).ith
pair denotes the rod that the ith
ring is placed on ('0'
to '9'
).For example, "R3G2B1"
describes n == 3
rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.
Return the number of rods that have all three colors of rings on them.
\n\n\n
Example 1:
\n\nInput: rings = "B0B6G0R6R0R6G9"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.\n\n\n
Example 2:
\n\nInput: rings = "B0R0G0R9R0B0G0"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.\n\n\n
Example 3:
\n\n\nInput: rings = "G4"\nOutput: 0\nExplanation: \nOnly one ring is given. Thus, no rods have all three colors.\n\n\n
\n
Constraints:
\n\nrings.length == 2 * n
1 <= n <= 100
rings[i]
where i
is even is either 'R'
, 'G'
, or 'B'
(0-indexed).rings[i]
where i
is odd is a digit from '0'
to '9'
(0-indexed).You are given an integer array nums
. The range of a subarray of nums
is the difference between the largest and smallest element in the subarray.
Return the sum of all subarray ranges of nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.\n\n
Example 2:
\n\n\nInput: nums = [1,3,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.\n\n\n
Example 3:
\n\n\nInput: nums = [4,-2,-3,4,1]\nOutput: 59\nExplanation: The sum of all subarray ranges of nums is 59.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-109 <= nums[i] <= 109
\n
Follow-up: Could you find a solution with O(n)
time complexity?
Alice and Bob want to water n
plants in their garden. The plants are arranged in a row and are labeled from 0
to n - 1
from left to right where the ith
plant is located at x = i
.
Each plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:
\n\n0th
plant. Bob waters the plants in order from right to left, starting from the (n - 1)th
plant. They begin watering the plants simultaneously.Given a 0-indexed integer array plants
of n
integers, where plants[i]
is the amount of water the ith
plant needs, and two integers capacityA
and capacityB
representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.
\n
Example 1:
\n\n\nInput: plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput: 1\nExplanation:\n- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.\n\n\n
Example 2:
\n\n\nInput: plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput: 2\nExplanation:\n- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.\n\n\n
Example 3:
\n\n\nInput: plants = [5], capacityA = 10, capacityB = 8\nOutput: 0\nExplanation:\n- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.\n\n\n
\n
Constraints:
\n\nn == plants.length
1 <= n <= 105
1 <= plants[i] <= 106
max(plants[i]) <= capacityA, capacityB <= 109
Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits
where fruits[i] = [positioni, amounti]
depicts amounti
fruits at the position positioni
. fruits
is already sorted by positioni
in ascending order, and each positioni
is unique.
You are also given an integer startPos
and an integer k
. Initially, you are at the position startPos
. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k
steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.
Return the maximum total number of fruits you can harvest.
\n\n\n
Example 1:
\n\nInput: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput: 9\nExplanation: \nThe optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.\n\n\n
Example 2:
\n\nInput: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput: 14\nExplanation: \nYou can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.\n\n\n
Example 3:
\n\nInput: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput: 0\nExplanation:\nYou can move at most k = 2 steps and cannot reach any position with fruits.\n\n\n
\n
Constraints:
\n\n1 <= fruits.length <= 105
fruits[i].length == 2
0 <= startPos, positioni <= 2 * 105
positioni-1 < positioni
for any i > 0
(0-indexed)1 <= amounti <= 104
0 <= k <= 2 * 105
Given an array of strings words
, return the first palindromic string in the array. If there is no such string, return an empty string ""
.
A string is palindromic if it reads the same forward and backward.
\n\n\n
Example 1:
\n\n\nInput: words = ["abc","car","ada","racecar","cool"]\nOutput: "ada"\nExplanation: The first string that is palindromic is "ada".\nNote that "racecar" is also palindromic, but it is not the first.\n\n\n
Example 2:
\n\n\nInput: words = ["notapalindrome","racecar"]\nOutput: "racecar"\nExplanation: The first and only string that is palindromic is "racecar".\n\n\n
Example 3:
\n\n\nInput: words = ["def","ghi"]\nOutput: ""\nExplanation: There are no palindromic strings, so the empty string is returned.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consists only of lowercase English letters.You are given a 0-indexed string s
and a 0-indexed integer array spaces
that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.
s = "EnjoyYourCoffee"
and spaces = [5, 9]
, we place spaces before 'Y'
and 'C'
, which are at indices 5
and 9
respectively. Thus, we obtain "Enjoy Your Coffee"
.Return the modified string after the spaces have been added.
\n\n\n
Example 1:
\n\n\nInput: s = "LeetcodeHelpsMeLearn", spaces = [8,13,15]\nOutput: "Leetcode Helps Me Learn"\nExplanation: \nThe indices 8, 13, and 15 correspond to the underlined characters in "LeetcodeHelpsMeLearn".\nWe then place spaces before those characters.\n\n\n
Example 2:
\n\n\nInput: s = "icodeinpython", spaces = [1,5,7,9]\nOutput: "i code in py thon"\nExplanation:\nThe indices 1, 5, 7, and 9 correspond to the underlined characters in "icodeinpython".\nWe then place spaces before those characters.\n\n\n
Example 3:
\n\n\nInput: s = "spacing", spaces = [0,1,2,3,4,5,6]\nOutput: " s p a c i n g"\nExplanation:\nWe are also able to place spaces before the first character of the string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 3 * 105
s
consists only of lowercase and uppercase English letters.1 <= spaces.length <= 3 * 105
0 <= spaces[i] <= s.length - 1
spaces
are strictly increasing.You are given an integer array prices
representing the daily price history of a stock, where prices[i]
is the stock price on the ith
day.
A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1
. The first day of the period is exempted from this rule.
Return the number of smooth descent periods.
\n\n\n
Example 1:
\n\n\nInput: prices = [3,2,1,4]\nOutput: 7\nExplanation: There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition.\n\n\n
Example 2:
\n\n\nInput: prices = [8,6,7,7]\nOutput: 4\nExplanation: There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.\n\n\n
Example 3:
\n\n\nInput: prices = [1]\nOutput: 1\nExplanation: There is 1 smooth descent period: [1]\n\n\n
\n
Constraints:
\n\n1 <= prices.length <= 105
1 <= prices[i] <= 105
You are given a 0-indexed array arr
consisting of n
positive integers, and a positive integer k
.
The array arr
is called K-increasing if arr[i-k] <= arr[i]
holds for every index i
, where k <= i <= n-1
.
arr = [4, 1, 5, 2, 6, 2]
is K-increasing for k = 2
because:\n\n\tarr[0] <= arr[2] (4 <= 5)
arr[1] <= arr[3] (1 <= 2)
arr[2] <= arr[4] (5 <= 6)
arr[3] <= arr[5] (2 <= 2)
arr
is not K-increasing for k = 1
(because arr[0] > arr[1]
) or k = 3
(because arr[0] > arr[3]
).In one operation, you can choose an index i
and change arr[i]
into any positive integer.
Return the minimum number of operations required to make the array K-increasing for the given k
.
\n
Example 1:
\n\n\nInput: arr = [5,4,3,2,1], k = 1\nOutput: 4\nExplanation:\nFor k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.\n\n\n
Example 2:
\n\n\nInput: arr = [4,1,5,2,6,2], k = 2\nOutput: 0\nExplanation:\nThis is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.\n\n
Example 3:
\n\n\nInput: arr = [4,1,5,2,6,2], k = 3\nOutput: 2\nExplanation:\nIndices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.\n\n\n
\n
Constraints:
\n\n1 <= arr.length <= 105
1 <= arr[i], k <= arr.length
A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
\n\nYou are given an array of strings sentences
, where each sentences[i]
represents a single sentence.
Return the maximum number of words that appear in a single sentence.
\n\n\n
Example 1:
\n\n\nInput: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]\nOutput: 6\nExplanation: \n- The first sentence, "alice and bob love leetcode", has 5 words in total.\n- The second sentence, "i think so too", has 4 words in total.\n- The third sentence, "this is great thanks very much", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.\n\n\n
Example 2:
\n\n\nInput: sentences = ["please wait", "continue to fight", "continue to win"]\nOutput: 3\nExplanation: It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.\n\n\n
\n
Constraints:
\n\n1 <= sentences.length <= 100
1 <= sentences[i].length <= 100
sentences[i]
consists only of lowercase English letters and ' '
only.sentences[i]
does not have leading or trailing spaces.sentences[i]
are separated by a single space.You have information about n
different recipes. You are given a string array recipes
and a 2D string array ingredients
. The ith
recipe has the name recipes[i]
, and you can create it if you have all the needed ingredients from ingredients[i]
. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i]
may contain a string that is in recipes
.
You are also given a string array supplies
containing all the ingredients that you initially have, and you have an infinite supply of all of them.
Return a list of all the recipes that you can create. You may return the answer in any order.
\n\nNote that two recipes may contain each other in their ingredients.
\n\n\n
Example 1:
\n\n\nInput: recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]\nOutput: ["bread"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\n\n\n
Example 2:
\n\n\nInput: recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"]\nOutput: ["bread","sandwich"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\n\n\n
Example 3:
\n\n\nInput: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"]\nOutput: ["bread","sandwich","burger"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\nWe can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich".\n\n\n
\n
Constraints:
\n\nn == recipes.length == ingredients.length
1 <= n <= 100
1 <= ingredients[i].length, supplies.length <= 100
1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10
recipes[i], ingredients[i][j]
, and supplies[k]
consist only of lowercase English letters.recipes
and supplies
combined are unique.ingredients[i]
does not contain any duplicate values.You have information about n
different recipes. You are given a string array recipes
and a 2D string array ingredients
. The ith
recipe has the name recipes[i]
, and you can create it if you have all the needed ingredients from ingredients[i]
. A recipe can also be an ingredient for other recipes, i.e., ingredients[i]
may contain a string that is in recipes
.
You are also given a string array supplies
containing all the ingredients that you initially have, and you have an infinite supply of all of them.
Return a list of all the recipes that you can create. You may return the answer in any order.
\n\nNote that two recipes may contain each other in their ingredients.
\n\n\n
Example 1:
\n\n\nInput: recipes = ["bread"], ingredients = [["yeast","flour"]], supplies = ["yeast","flour","corn"]\nOutput: ["bread"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\n\n\n
Example 2:
\n\n\nInput: recipes = ["bread","sandwich"], ingredients = [["yeast","flour"],["bread","meat"]], supplies = ["yeast","flour","meat"]\nOutput: ["bread","sandwich"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\n\n\n
Example 3:
\n\n\nInput: recipes = ["bread","sandwich","burger"], ingredients = [["yeast","flour"],["bread","meat"],["sandwich","meat","bread"]], supplies = ["yeast","flour","meat"]\nOutput: ["bread","sandwich","burger"]\nExplanation:\nWe can create "bread" since we have the ingredients "yeast" and "flour".\nWe can create "sandwich" since we have the ingredient "meat" and can create the ingredient "bread".\nWe can create "burger" since we have the ingredient "meat" and can create the ingredients "bread" and "sandwich".\n\n\n
\n
Constraints:
\n\nn == recipes.length == ingredients.length
1 <= n <= 100
1 <= ingredients[i].length, supplies.length <= 100
1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10
recipes[i], ingredients[i][j]
, and supplies[k]
consist only of lowercase English letters.recipes
and supplies
combined are unique.ingredients[i]
does not contain any duplicate values.A parentheses string is a non-empty string consisting only of '('
and ')'
. It is valid if any of the following conditions is true:
()
.AB
(A
concatenated with B
), where A
and B
are valid parentheses strings.(A)
, where A
is a valid parentheses string.You are given a parentheses string s
and a string locked
, both of length n
. locked
is a binary string consisting only of '0'
s and '1'
s. For each index i
of locked
,
locked[i]
is '1'
, you cannot change s[i]
.locked[i]
is '0'
, you can change s[i]
to either '('
or ')'
.Return true
if you can make s
a valid parentheses string. Otherwise, return false
.
\n
Example 1:
\n\nInput: s = "))()))", locked = "010100"\nOutput: true\nExplanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.\n\n
Example 2:
\n\n\nInput: s = "()()", locked = "0000"\nOutput: true\nExplanation: We do not need to make any changes because s is already valid.\n\n\n
Example 3:
\n\n\nInput: s = ")", locked = "0"\nOutput: false\nExplanation: locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.\n\n\n
\n
Constraints:
\n\nn == s.length == locked.length
1 <= n <= 105
s[i]
is either '('
or ')'
.locked[i]
is either '0'
or '1'
.A parentheses string is a non-empty string consisting only of '('
and ')'
. It is valid if any of the following conditions is true:
()
.AB
(A
concatenated with B
), where A
and B
are valid parentheses strings.(A)
, where A
is a valid parentheses string.You are given a parentheses string s
and a string locked
, both of length n
. locked
is a binary string consisting only of '0'
s and '1'
s. For each index i
of locked
,
locked[i]
is '1'
, you cannot change s[i]
.locked[i]
is '0'
, you can change s[i]
to either '('
or ')'
.Return true
if you can make s
a valid parentheses string. Otherwise, return false
.
\n
Example 1:
\n\nInput: s = "))()))", locked = "010100"\nOutput: true\nExplanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.\n\n
Example 2:
\n\n\nInput: s = "()()", locked = "0000"\nOutput: true\nExplanation: We do not need to make any changes because s is already valid.\n\n\n
Example 3:
\n\n\nInput: s = ")", locked = "0"\nOutput: false\nExplanation: locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.\n\n\n
Example 4:
\n\n\nInput: s = "(((())(((())", locked = "111111010111"\nOutput: true\nExplanation: locked permits us to change s[6] and s[8]. \nWe change s[6] and s[8] to ')' to make s valid.\n\n\n
\n
Constraints:
\n\nn == s.length == locked.length
1 <= n <= 105
s[i]
is either '('
or ')'
.locked[i]
is either '0'
or '1'
.You are given two positive integers left
and right
with left <= right
. Calculate the product of all integers in the inclusive range [left, right]
.
Since the product may be very large, you will abbreviate it following these steps:
\n\nC
.\n\n\t3
trailing zeros in 1000
, and there are 0
trailing zeros in 546
.d
. If d > 10
, then express the product as <pre>...<suf>
where <pre>
denotes the first 5
digits of the product, and <suf>
denotes the last 5
digits of the product after removing all trailing zeros. If d <= 10
, we keep it unchanged.\n\t1234567654321
as 12345...54321
, but 1234567
is represented as 1234567
."<pre>...<suf>eC"
.\n\t12345678987600000
will be represented as "12345...89876e5"
.Return a string denoting the abbreviated product of all integers in the inclusive range [left, right]
.
\n
Example 1:
\n\n\nInput: left = 1, right = 4\nOutput: "24e0"\nExplanation: The product is 1 × 2 × 3 × 4 = 24.\nThere are no trailing zeros, so 24 remains the same. The abbreviation will end with "e0".\nSince the number of digits is 2, which is less than 10, we do not have to abbreviate it further.\nThus, the final representation is "24e0".\n\n\n
Example 2:
\n\n\nInput: left = 2, right = 11\nOutput: "399168e2"\nExplanation: The product is 39916800.\nThere are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with "e2".\nThe number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.\nHence, the abbreviated product is "399168e2".\n\n\n
Example 3:
\n\n\nInput: left = 371, right = 375\nOutput: "7219856259e3"\nExplanation: The product is 7219856259000.\n\n\n
\n
Constraints:
\n\n1 <= left <= right <= 104
Reversing an integer means to reverse all its digits.
\n\n2021
gives 1202
. Reversing 12300
gives 321
as the leading zeros are not retained.Given an integer num
, reverse num
to get reversed1
, then reverse reversed1
to get reversed2
. Return true
if reversed2
equals num
. Otherwise return false
.
\n
Example 1:
\n\n\nInput: num = 526\nOutput: true\nExplanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.\n\n\n
Example 2:
\n\n\nInput: num = 1800\nOutput: false\nExplanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.\n\n\n
Example 3:
\n\n\nInput: num = 0\nOutput: true\nExplanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.\n\n\n
\n
Constraints:
\n\n0 <= num <= 106
There is an n x n
grid, with the top-left cell at (0, 0)
and the bottom-right cell at (n - 1, n - 1)
. You are given the integer n
and an integer array startPos
where startPos = [startrow, startcol]
indicates that a robot is initially at cell (startrow, startcol)
.
You are also given a 0-indexed string s
of length m
where s[i]
is the ith
instruction for the robot: 'L'
(move left), 'R'
(move right), 'U'
(move up), and 'D'
(move down).
The robot can begin executing from any ith
instruction in s
. It executes the instructions one by one towards the end of s
but it stops if either of these conditions is met:
Return an array answer
of length m
where answer[i]
is the number of instructions the robot can execute if the robot begins executing from the ith
instruction in s
.
\n
Example 1:
\n\nInput: n = 3, startPos = [0,1], s = "RRDDLU"\nOutput: [1,5,4,3,1,0]\nExplanation: Starting from startPos and beginning execution from the ith instruction:\n- 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid.\n- 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th: "LU". Only one instruction "L" can be executed before it moves off the grid.\n- 5th: "U". If moving up, it would move off the grid.\n\n\n
Example 2:
\n\nInput: n = 2, startPos = [1,1], s = "LURD"\nOutput: [4,1,0,0]\nExplanation:\n- 0th: "LURD".\n- 1st: "URD".\n- 2nd: "RD".\n- 3rd: "D".\n\n\n
Example 3:
\n\nInput: n = 1, startPos = [0,0], s = "LRUD"\nOutput: [0,0,0,0]\nExplanation: No matter which instruction the robot begins execution from, it would move off the grid.\n\n\n
\n
Constraints:
\n\nm == s.length
1 <= n, m <= 500
startPos.length == 2
0 <= startrow, startcol < n
s
consists of 'L'
, 'R'
, 'U'
, and 'D'
.You are given a 0-indexed array of n
integers arr
.
The interval between two elements in arr
is defined as the absolute difference between their indices. More formally, the interval between arr[i]
and arr[j]
is |i - j|
.
Return an array intervals
of length n
where intervals[i]
is the sum of intervals between arr[i]
and each element in arr
with the same value as arr[i]
.
Note: |x|
is the absolute value of x
.
\n
Example 1:
\n\n\nInput: arr = [2,1,3,1,2,3,3]\nOutput: [4,2,7,2,4,4,5]\nExplanation:\n- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5\n\n\n
Example 2:
\n\n\nInput: arr = [10,5,10,10]\nOutput: [5,0,3,4]\nExplanation:\n- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4\n\n\n
\n
Constraints:
\n\nn == arr.length
1 <= n <= 105
1 <= arr[i] <= 105
\n
Note: This question is the same as 2615: Sum of Distances.
\n", - "likes": 925, + "likes": 936, "dislikes": 42, - "stats": "{\"totalAccepted\": \"22.5K\", \"totalSubmission\": \"50.4K\", \"totalAcceptedRaw\": 22468, \"totalSubmissionRaw\": 50368, \"acRate\": \"44.6%\"}", + "stats": "{\"totalAccepted\": \"23.9K\", \"totalSubmission\": \"53.1K\", \"totalAcceptedRaw\": 23873, \"totalSubmissionRaw\": 53144, \"acRate\": \"44.9%\"}", "similarQuestions": "[{\"title\": \"Continuous Subarray Sum\", \"titleSlug\": \"continuous-subarray-sum\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -80078,9 +80222,9 @@ "questionFrontendId": "2122", "title": "Recover the Original Array", "content": "Alice had a 0-indexed array arr
consisting of n
positive integers. She chose an arbitrary positive integer k
and created two new 0-indexed integer arrays lower
and higher
in the following manner:
lower[i] = arr[i] - k
, for every index i
where 0 <= i < n
higher[i] = arr[i] + k
, for every index i
where 0 <= i < n
Unfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower
and higher
, but not the array each integer belonged to. Help Alice and recover the original array.
Given an array nums
consisting of 2n
integers, where exactly n
of the integers were present in lower
and the remaining in higher
, return the original array arr
. In case the answer is not unique, return any valid array.
Note: The test cases are generated such that there exists at least one valid array arr
.
\n
Example 1:
\n\n\nInput: nums = [2,10,6,4,8,12]\nOutput: [3,7,11]\nExplanation:\nIf arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. \n\n\n
Example 2:
\n\n\nInput: nums = [1,1,3,3]\nOutput: [2,2]\nExplanation:\nIf arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.\n\n\n
Example 3:
\n\n\nInput: nums = [5,435]\nOutput: [220]\nExplanation:\nThe only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].\n\n\n
\n
Constraints:
\n\n2 * n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 109
arr
.Given a string s
consisting of only the characters 'a'
and 'b'
, return true
if every 'a'
appears before every 'b'
in the string. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: s = "aaabbb"\nOutput: true\nExplanation:\nThe 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.\n\n\n
Example 2:
\n\n\nInput: s = "abab"\nOutput: false\nExplanation:\nThere is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.\n\n\n
Example 3:
\n\n\nInput: s = "bbb"\nOutput: true\nExplanation:\nThere are no 'a's, hence, every 'a' appears before every 'b' and we return true.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s[i]
is either 'a'
or 'b'
.Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank
representing the floor plan of the bank, which is an m x n
2D matrix. bank[i]
represents the ith
row, consisting of '0'
s and '1'
s. '0'
means the cell is empty, while'1'
means the cell has a security device.
There is one laser beam between any two security devices if both conditions are met:
\n\nr1
and r2
, where r1 < r2
.i
where r1 < i < r2
, there are no security devices in the ith
row.Laser beams are independent, i.e., one beam does not interfere nor join with another.
\n\nReturn the total number of laser beams in the bank.
\n\n\n
Example 1:
\n\nInput: bank = ["011001","000000","010100","001000"]\nOutput: 8\nExplanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0th row with any on the 3rd row.\nThis is because the 2nd row contains security devices, which breaks the second condition.\n\n\n
Example 2:
\n\nInput: bank = ["000","111","000"]\nOutput: 0\nExplanation: There does not exist two devices located on two different rows.\n\n\n
\n
Constraints:
\n\nm == bank.length
n == bank[i].length
1 <= m, n <= 500
bank[i][j]
is either '0'
or '1'
.You are given an integer mass
, which represents the original mass of a planet. You are further given an integer array asteroids
, where asteroids[i]
is the mass of the ith
asteroid.
You can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.
\n\nReturn true
if all asteroids can be destroyed. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: mass = 10, asteroids = [3,9,19,5,21]\nOutput: true\nExplanation: One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.\n\n\n
Example 2:
\n\n\nInput: mass = 5, asteroids = [4,9,23,4]\nOutput: false\nExplanation: \nThe planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.\n\n
\n
Constraints:
\n\n1 <= mass <= 105
1 <= asteroids.length <= 105
1 <= asteroids[i] <= 105
A company is organizing a meeting and has a list of n
employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.
The employees are numbered from 0
to n - 1
. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.
Given a 0-indexed integer array favorite
, where favorite[i]
denotes the favorite person of the ith
employee, return the maximum number of employees that can be invited to the meeting.
\n
Example 1:
\n\nInput: favorite = [2,2,1,2]\nOutput: 3\nExplanation:\nThe above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3. \n\n\n
Example 2:
\n\n\nInput: favorite = [1,2,0]\nOutput: 3\nExplanation: \nEach employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.\n\n\n
Example 3:
\n\nInput: favorite = [3,0,1,4,1]\nOutput: 4\nExplanation:\nThe above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.\n\n\n
\n
Constraints:
\n\nn == favorite.length
2 <= n <= 105
0 <= favorite[i] <= n - 1
favorite[i] != i
You are given a string title
consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:
1
or 2
letters, change all letters to lowercase.Return the capitalized title
.
\n
Example 1:
\n\n\nInput: title = "capiTalIze tHe titLe"\nOutput: "Capitalize The Title"\nExplanation:\nSince all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.\n\n\n
Example 2:
\n\n\nInput: title = "First leTTeR of EACH Word"\nOutput: "First Letter of Each Word"\nExplanation:\nThe word "of" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\n\n\n
Example 3:
\n\n\nInput: title = "i lOve leetcode"\nOutput: "i Love Leetcode"\nExplanation:\nThe word "i" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\n\n\n
\n
Constraints:
\n\n1 <= title.length <= 100
title
consists of words separated by a single space without any leading or trailing spaces.In a linked list of size n
, where n
is even, the ith
node (0-indexed) of the linked list is known as the twin of the (n-1-i)th
node, if 0 <= i <= (n / 2) - 1
.
n = 4
, then node 0
is the twin of node 3
, and node 1
is the twin of node 2
. These are the only nodes with twins for n = 4
.The twin sum is defined as the sum of a node and its twin.
\n\nGiven the head
of a linked list with even length, return the maximum twin sum of the linked list.
\n
Example 1:
\n\nInput: head = [5,4,2,1]\nOutput: 6\nExplanation:\nNodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6. \n\n\n
Example 2:
\n\nInput: head = [4,2,2,3]\nOutput: 7\nExplanation:\nThe nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7. \n\n\n
Example 3:
\n\nInput: head = [1,100000]\nOutput: 100001\nExplanation:\nThere is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.\n\n\n
\n
Constraints:
\n\n[2, 105]
.1 <= Node.val <= 105
You are given an array of strings words
. Each element of words
consists of two lowercase English letters.
Create the longest possible palindrome by selecting some elements from words
and concatenating them in any order. Each element can be selected at most once.
Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0
.
A palindrome is a string that reads the same forward and backward.
\n\n\n
Example 1:
\n\n\nInput: words = ["lc","cl","gg"]\nOutput: 6\nExplanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6.\nNote that "clgglc" is another longest palindrome that can be created.\n\n\n
Example 2:
\n\n\nInput: words = ["ab","ty","yt","lc","cl","ab"]\nOutput: 8\nExplanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8.\nNote that "lcyttycl" is another longest palindrome that can be created.\n\n\n
Example 3:
\n\n\nInput: words = ["cc","ll","xx"]\nOutput: 2\nExplanation: One longest palindrome is "cc", of length 2.\nNote that "ll" is another longest palindrome that can be created, and so is "xx".\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 105
words[i].length == 2
words[i]
consists of lowercase English letters.You are given an m x n
binary matrix grid
where each cell is either 0
(empty) or 1
(occupied).
You are then given stamps of size stampHeight x stampWidth
. We want to fit the stamps such that they follow the given restrictions and requirements:
Return true
if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false
.
\n
Example 1:
\n\nInput: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3\nOutput: true\nExplanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.\n\n\n
Example 2:
\n\nInput: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 \nOutput: false \nExplanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[r].length
1 <= m, n <= 105
1 <= m * n <= 2 * 105
grid[r][c]
is either 0
or 1
.1 <= stampHeight, stampWidth <= 105
An n x n
matrix is valid if every row and every column contains all the integers from 1
to n
(inclusive).
Given an n x n
integer matrix matrix
, return true
if the matrix is valid. Otherwise, return false
.
\n
Example 1:
\n\nInput: matrix = [[1,2,3],[3,1,2],[2,3,1]]\nOutput: true\nExplanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.\n\n\n
Example 2:
\n\nInput: matrix = [[1,1,1],[1,2,3],[1,2,3]]\nOutput: false\nExplanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.\n\n\n
\n
Constraints:
\n\nn == matrix.length == matrix[i].length
1 <= n <= 100
1 <= matrix[i][j] <= n
A swap is defined as taking two distinct positions in an array and swapping the values in them.
\n\nA circular array is defined as an array where we consider the first element and the last element to be adjacent.
\n\nGiven a binary circular array nums
, return the minimum number of swaps required to group all 1
's present in the array together at any location.
\n
Example 1:
\n\n\nInput: nums = [0,1,0,1,1,0,0]\nOutput: 1\nExplanation: Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,1,1,0,0,1,1,0]\nOutput: 2\nExplanation: Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,0,0,1]\nOutput: 0\nExplanation: All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.You are given two 0-indexed arrays of strings startWords
and targetWords
. Each string consists of lowercase English letters only.
For each string in targetWords
, check if it is possible to choose a string from startWords
and perform a conversion operation on it to be equal to that from targetWords
.
The conversion operation is described in the following two steps:
\n\n"abc"
, the letters 'd'
, 'e'
, or 'y'
can be added to it, but not 'a'
. If 'd'
is added, the resulting string will be "abcd"
."abcd"
can be rearranged to "acbd"
, "bacd"
, "cbda"
, and so on. Note that it can also be rearranged to "abcd"
itself.Return the number of strings in targetWords
that can be obtained by performing the operations on any string of startWords
.
Note that you will only be verifying if the string in targetWords
can be obtained from a string in startWords
by performing the operations. The strings in startWords
do not actually change during this process.
\n
Example 1:
\n\n\nInput: startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"]\nOutput: 2\nExplanation:\n- In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack".\n- There is no string in startWords that can be used to obtain targetWords[1] = "act".\n Note that "act" does exist in startWords, but we must append one letter to the string before rearranging it.\n- In order to form targetWords[2] = "acti", we use startWords[1] = "act", append 'i' to it, and rearrange "acti" to "acti" itself.\n\n\n
Example 2:
\n\n\nInput: startWords = ["ab","a"], targetWords = ["abc","abcd"]\nOutput: 1\nExplanation:\n- In order to form targetWords[0] = "abc", we use startWords[0] = "ab", add 'c' to it, and rearrange it to "abc".\n- There is no string in startWords that can be used to obtain targetWords[1] = "abcd".\n\n\n
\n
Constraints:
\n\n1 <= startWords.length, targetWords.length <= 5 * 104
1 <= startWords[i].length, targetWords[j].length <= 26
startWords
and targetWords
consists of lowercase English letters only.startWords
or targetWords
.You have n
flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime
and growTime
, of length n
each:
plantTime[i]
is the number of full days it takes you to plant the ith
seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i]
days on planting it in total.growTime[i]
is the number of full days it takes the ith
seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever.From the beginning of day 0
, you can plant the seeds in any order.
Return the earliest possible day where all seeds are blooming.
\n\n\n
Example 1:
\n\nInput: plantTime = [1,4,3], growTime = [2,3,1]\nOutput: 9\nExplanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3.\nOn days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8.\nOn days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.\n\n\n
Example 2:
\n\nInput: plantTime = [1,2,3,2], growTime = [2,1,2,1]\nOutput: 9\nExplanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4.\nOn days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5.\nOn days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8.\nOn days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.\n\n\n
Example 3:
\n\n\nInput: plantTime = [1], growTime = [1]\nOutput: 2\nExplanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2.\nThus, on day 2, all the seeds are blooming.\n\n\n
\n
Constraints:
\n\nn == plantTime.length == growTime.length
1 <= n <= 105
1 <= plantTime[i], growTime[i] <= 104
A string s
can be partitioned into groups of size k
using the following procedure:
k
characters of the string, the second group consists of the next k
characters of the string, and so on. Each character can be a part of exactly one group.k
characters remaining, a character fill
is used to complete the group.Note that the partition is done so that after removing the fill
character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s
.
Given the string s
, the size of each group k
and the character fill
, return a string array denoting the composition of every group s
has been divided into, using the above procedure.
\n
Example 1:
\n\n\nInput: s = "abcdefghi", k = 3, fill = "x"\nOutput: ["abc","def","ghi"]\nExplanation:\nThe first 3 characters "abc" form the first group.\nThe next 3 characters "def" form the second group.\nThe last 3 characters "ghi" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are "abc", "def", and "ghi".\n\n\n
Example 2:
\n\n\nInput: s = "abcdefghij", k = 3, fill = "x"\nOutput: ["abc","def","ghi","jxx"]\nExplanation:\nSimilar to the previous example, we are forming the first three groups "abc", "def", and "ghi".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are "abc", "def", "ghi", and "jxx".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters only.1 <= k <= 100
fill
is a lowercase English letter.A string s
can be partitioned into groups of size k
using the following procedure:
k
characters of the string, the second group consists of the next k
characters of the string, and so on. Each element can be a part of exactly one group.k
characters remaining, a character fill
is used to complete the group.Note that the partition is done so that after removing the fill
character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s
.
Given the string s
, the size of each group k
and the character fill
, return a string array denoting the composition of every group s
has been divided into, using the above procedure.
\n
Example 1:
\n\n\nInput: s = "abcdefghi", k = 3, fill = "x"\nOutput: ["abc","def","ghi"]\nExplanation:\nThe first 3 characters "abc" form the first group.\nThe next 3 characters "def" form the second group.\nThe last 3 characters "ghi" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are "abc", "def", and "ghi".\n\n\n
Example 2:
\n\n\nInput: s = "abcdefghij", k = 3, fill = "x"\nOutput: ["abc","def","ghi","jxx"]\nExplanation:\nSimilar to the previous example, we are forming the first three groups "abc", "def", and "ghi".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are "abc", "def", "ghi", and "jxx".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters only.1 <= k <= 100
fill
is a lowercase English letter.You are playing a game with integers. You start with the integer 1
and you want to reach the integer target
.
In one move, you can either:
\n\nx = x + 1
).x = 2 * x
).You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles
times.
Given the two integers target
and maxDoubles
, return the minimum number of moves needed to reach target
starting with 1
.
\n
Example 1:
\n\n\nInput: target = 5, maxDoubles = 0\nOutput: 4\nExplanation: Keep incrementing by 1 until you reach target.\n\n\n
Example 2:
\n\n\nInput: target = 19, maxDoubles = 2\nOutput: 7\nExplanation: Initially, x = 1\nIncrement 3 times so x = 4\nDouble once so x = 8\nIncrement once so x = 9\nDouble again so x = 18\nIncrement once so x = 19\n\n\n
Example 3:
\n\n\nInput: target = 10, maxDoubles = 4\nOutput: 4\nExplanation: Initially, x = 1\nIncrement once so x = 2\nDouble once so x = 4\nIncrement once so x = 5\nDouble again so x = 10\n\n\n
\n
Constraints:
\n\n1 <= target <= 109
0 <= maxDoubles <= 100
You are given a 0-indexed 2D integer array questions
where questions[i] = [pointsi, brainpoweri]
.
The array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0
) and make a decision whether to solve or skip each question. Solving question i
will earn you pointsi
points but you will be unable to solve each of the next brainpoweri
questions. If you skip question i
, you get to make the decision on the next question.
questions = [[3, 2], [4, 3], [4, 4], [2, 5]]
:\n\n\t0
is solved, you will earn 3
points but you will be unable to solve questions 1
and 2
.0
is skipped and question 1
is solved, you will earn 4
points but you will be unable to solve questions 2
and 3
.Return the maximum points you can earn for the exam.
\n\n\n
Example 1:
\n\n\nInput: questions = [[3,2],[4,3],[4,4],[2,5]]\nOutput: 5\nExplanation: The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.\n\n\n
Example 2:
\n\n\nInput: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput: 7\nExplanation: The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.\n\n\n
\n
Constraints:
\n\n1 <= questions.length <= 105
questions[i].length == 2
1 <= pointsi, brainpoweri <= 105
You have n
computers. You are given the integer n
and a 0-indexed integer array batteries
where the ith
battery can run a computer for batteries[i]
minutes. You are interested in running all n
computers simultaneously using the given batteries.
Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.
\n\nNote that the batteries cannot be recharged.
\n\nReturn the maximum number of minutes you can run all the n
computers simultaneously.
\n
Example 1:
\n\nInput: n = 2, batteries = [3,3,3]\nOutput: 4\nExplanation: \nInitially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.\n\n\n\n
Example 2:
\n\nInput: n = 2, batteries = [1,1,1,1]\nOutput: 2\nExplanation: \nInitially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.\n\n\n
\n
Constraints:
\n\n1 <= n <= batteries.length <= 105
1 <= batteries[i] <= 109
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.
\n\nThe customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.
\n\n4
candies with costs 1
, 2
, 3
, and 4
, and the customer buys candies with costs 2
and 3
, they can take the candy with cost 1
for free, but not the candy with cost 4
.Given a 0-indexed integer array cost
, where cost[i]
denotes the cost of the ith
candy, return the minimum cost of buying all the candies.
\n
Example 1:
\n\n\nInput: cost = [1,2,3]\nOutput: 5\nExplanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.\n\n\n
Example 2:
\n\n\nInput: cost = [6,5,7,9,2,2]\nOutput: 23\nExplanation: The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.\n\n\n
Example 3:
\n\n\nInput: cost = [5,5]\nOutput: 10\nExplanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.\n\n\n
\n
Constraints:
\n\n1 <= cost.length <= 100
1 <= cost[i] <= 100
You are given a 0-indexed array of n
integers differences
, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1)
. More formally, call the hidden sequence hidden
, then we have that differences[i] = hidden[i + 1] - hidden[i]
.
You are further given two integers lower
and upper
that describe the inclusive range of values [lower, upper]
that the hidden sequence can contain.
differences = [1, -3, 4]
, lower = 1
, upper = 6
, the hidden sequence is a sequence of length 4
whose elements are in between 1
and 6
(inclusive).\n\n\t[3, 4, 1, 5]
and [4, 5, 2, 6]
are possible hidden sequences.[5, 6, 3, 7]
is not possible since it contains an element greater than 6
.[1, 2, 3, 4]
is not possible since the differences are not correct.Return the number of possible hidden sequences there are. If there are no possible sequences, return 0
.
\n
Example 1:
\n\n\nInput: differences = [1,-3,4], lower = 1, upper = 6\nOutput: 2\nExplanation: The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.\n\n\n
Example 2:
\n\n\nInput: differences = [3,-4,5,1,-2], lower = -4, upper = 5\nOutput: 4\nExplanation: The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.\n\n\n
Example 3:
\n\n\nInput: differences = [4,-7,2], lower = 3, upper = 6\nOutput: 0\nExplanation: There are no possible hidden sequences. Thus, we return 0.\n\n\n
\n
Constraints:
\n\nn == differences.length
1 <= n <= 105
-105 <= differences[i] <= 105
-105 <= lower <= upper <= 105
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.It takes 1
step to travel between adjacent grid cells.
You are also given integer arrays pricing
and start
where pricing = [low, high]
and start = [row, col]
indicates that you start at the position (row, col)
and are interested only in items with a price in the range of [low, high]
(inclusive). You are further given an integer k
.
You are interested in the positions of the k
highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different:
start
(shorter distance has a higher rank).Return the k
highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k
reachable items within the price range, return all of them.
\n
Example 1:
\n\nInput: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\nOutput: [[0,1],[1,1],[2,1]]\nExplanation: You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).\n\n\n
Example 2:
\n\nInput: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\nOutput: [[2,1],[1,2]]\nExplanation: You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).\n\n\n
Example 3:
\n\nInput: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\nOutput: [[2,1],[2,0]]\nExplanation: You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= grid[i][j] <= 105
pricing.length == 2
2 <= low <= high <= 105
start.length == 2
0 <= row <= m - 1
0 <= col <= n - 1
grid[row][col] > 0
1 <= k <= m * n
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor
of length n
consisting of letters 'S'
and 'P'
where each 'S'
represents a seat and each 'P'
represents a plant.
One room divider has already been installed to the left of index 0
, and another to the right of index n - 1
. Additional room dividers can be installed. For each position between indices i - 1
and i
(1 <= i <= n - 1
), at most one divider can be installed.
Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.
\n\nReturn the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7
. If there is no way, return 0
.
\n
Example 1:
\n\nInput: corridor = "SSPPSPS"\nOutput: 3\nExplanation: There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways, each section has exactly two seats.\n\n\n
Example 2:
\n\nInput: corridor = "PPSPSP"\nOutput: 1\nExplanation: There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.\n\n\n
Example 3:
\n\nInput: corridor = "S"\nOutput: 0\nExplanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.\n\n\n
\n
Constraints:
\n\nn == corridor.length
1 <= n <= 105
corridor[i]
is either 'S'
or 'P'
.Given an integer array nums
, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums
.
\n
Example 1:
\n\n\nInput: nums = [11,7,2,15]\nOutput: 2\nExplanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums
.\n
\n\nExample 2:
\n\n\nInput: nums = [-3,3,3,90]\nOutput: 2\nExplanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums
.\n
\n\n\n
Constraints:
\n\n1 <= nums.length <= 100
-105 <= nums[i] <= 105
You are given a 0-indexed integer array nums
of even length consisting of an equal number of positive and negative integers.
You should return the array of nums such that the the array follows the given conditions:
\n\nnums
is preserved.Return the modified array after rearranging the elements to satisfy the aforementioned conditions.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,-2,-5,2,-4]\nOutput: [3,-2,1,-5,2,-4]\nExplanation:\nThe positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. \n\n\n
Example 2:
\n\n\nInput: nums = [-1,1]\nOutput: [1,-1]\nExplanation:\n1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 2 * 105
nums.length
is even1 <= |nums[i]| <= 105
nums
consists of equal number of positive and negative integers.\nIt is not required to do the modifications in-place.", - "likes": 3509, - "dislikes": 198, - "stats": "{\"totalAccepted\": \"508K\", \"totalSubmission\": \"603.8K\", \"totalAcceptedRaw\": 508007, \"totalSubmissionRaw\": 603848, \"acRate\": \"84.1%\"}", + "likes": 3684, + "dislikes": 205, + "stats": "{\"totalAccepted\": \"597.7K\", \"totalSubmission\": \"708.6K\", \"totalAcceptedRaw\": 597708, \"totalSubmissionRaw\": 708591, \"acRate\": \"84.4%\"}", "similarQuestions": "[{\"title\": \"Wiggle Subsequence\", \"titleSlug\": \"wiggle-subsequence\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Sort Array By Parity II\", \"titleSlug\": \"sort-array-by-parity-ii\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Partition Array According to Given Pivot\", \"titleSlug\": \"partition-array-according-to-given-pivot\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Largest Number After Digit Swaps by Parity\", \"titleSlug\": \"largest-number-after-digit-swaps-by-parity\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -81172,9 +81319,9 @@ "questionFrontendId": "2150", "title": "Find All Lonely Numbers in the Array", "content": "
You are given an integer array nums
. A number x
is lonely when it appears only once, and no adjacent numbers (i.e. x + 1
and x - 1)
appear in the array.
Return all lonely numbers in nums
. You may return the answer in any order.
\n
Example 1:
\n\n\nInput: nums = [10,6,5,8]\nOutput: [10,8]\nExplanation: \n- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,5,3]\nOutput: [1,5]\nExplanation: \n- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 106
There are two types of persons:
\n\nYou are given a 0-indexed 2D integer array statements
of size n x n
that represents the statements made by n
people about each other. More specifically, statements[i][j]
could be one of the following:
0
which represents a statement made by person i
that person j
is a bad person.1
which represents a statement made by person i
that person j
is a good person.2
represents that no statement is made by person i
about person j
.Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2
for all 0 <= i < n
.
Return the maximum number of people who can be good based on the statements made by the n
people.
\n
Example 1:
\n\nInput: statements = [[2,1,2],[1,2,2],[2,0,2]]\nOutput: 2\nExplanation: Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n - Based on the statement made by person 2, person 1 is a bad person.\n - Now we know for sure that person 1 is bad and person 2 is good.\n - Based on the statement made by person 1, and since person 1 is bad, they could be:\n - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n - lying. In this case, person 0 is also a bad person and lied in their statement.\n - Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n - Based on the statement made by person 2, and since person 2 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n - Following that person 2 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Since person 1 is a good person, person 0 is also a good person.\n - Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.\n\n\n
Example 2:
\n\nInput: statements = [[2,0],[0,2]]\nOutput: 1\nExplanation: Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n - Based on the statement made by person 0, person 1 is a bad person and was lying.\n - Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n - Based on the statement made by person 0, and since person 0 is bad, they could be:\n - telling the truth. Following this scenario, person 0 and 1 are both bad.\n - Following that person 0 is bad but told the truth, there will be no good persons in the group.\n - lying. In this case person 1 is a good person.\n - Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.\n\n\n
\n
Constraints:
\n\nn == statements.length == statements[i].length
2 <= n <= 15
statements[i][j]
is either 0
, 1
, or 2
.statements[i][i] == 2
You are given an array of integers nums
. You are also given an integer original
which is the first number that needs to be searched for in nums
.
You then do the following steps:
\n\noriginal
is found in nums
, multiply it by two (i.e., set original = 2 * original
).Return the final value of original
.
\n
Example 1:
\n\n\nInput: nums = [5,3,6,1,12], original = 3\nOutput: 24\nExplanation: \n- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.\n\n\n
Example 2:
\n\n\nInput: nums = [2,7,9], original = 4\nOutput: 4\nExplanation:\n- 4 is not found in nums. Thus, 4 is returned.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i], original <= 1000
You are given a 0-indexed binary array nums
of length n
. nums
can be divided at index i
(where 0 <= i <= n)
into two arrays (possibly empty) numsleft
and numsright
:
numsleft
has all the elements of nums
between index 0
and i - 1
(inclusive), while numsright
has all the elements of nums between index i
and n - 1
(inclusive).i == 0
, numsleft
is empty, while numsright
has all the elements of nums
.i == n
, numsleft
has all the elements of nums, while numsright
is empty.The division score of an index i
is the sum of the number of 0
's in numsleft
and the number of 1
's in numsright
.
Return all distinct indices that have the highest possible division score. You may return the answer in any order.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,0,1,0]\nOutput: [2,4]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3.\n- 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2.\n- 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.\n\n
Example 2:
\n\n\nInput: nums = [0,0,0]\nOutput: [3]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1.\n- 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2.\n- 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1]\nOutput: [0]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2.\n- 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1.\n- 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
nums[i]
is either 0
or 1
.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
.
You are given a string s
and the integers power
, modulo
, k
, and hashValue.
Return sub
, the first substring of s
of length k
such that hash(sub, power, modulo) == hashValue
.
The test cases will be generated such that an answer always exists.
\n\nA substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput: "ee"\nExplanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n"ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".\n\n\n
Example 2:
\n\n\nInput: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput: "fbx"\nExplanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".\nNote that "bxz" also has a hash of 32 but it appears later than "fbx".\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 2 * 104
1 <= power, modulo <= 109
0 <= hashValue < modulo
s
consists of lowercase English letters only.You are given a 0-indexed array of strings words
. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words
.
Two strings s1
and s2
are said to be connected if the set of letters of s2
can be obtained from the set of letters of s1
by any one of the following operations:
s1
.s1
.s1
with any letter, including itself.The array words
can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true:
Note that the strings in words
should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique.
Return an array ans
of size 2
where:
ans[0]
is the maximum number of groups words
can be divided into, andans[1]
is the size of the largest group.\n
Example 1:
\n\n\nInput: words = ["a","b","ab","cde"]\nOutput: [2,3]\nExplanation:\n- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n- words[3] is not connected to any string in words.\nThus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3. \n\n\n
Example 2:
\n\n\nInput: words = ["a","ab","abc"]\nOutput: [1,3]\nExplanation:\n- words[0] is connected to words[1].\n- words[1] is connected to words[0] and words[2].\n- words[2] is connected to words[1].\nSince all strings are connected to each other, they should be grouped together.\nThus, the size of the largest group is 3.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 2 * 104
1 <= words[i].length <= 26
words[i]
consists of lowercase English letters only.words[i]
.You are given a positive integer num
consisting of exactly four digits. Split num
into two new integers new1
and new2
by using the digits found in num
. Leading zeros are allowed in new1
and new2
, and all the digits found in num
must be used.
num = 2932
, you have the following digits: two 2
's, one 9
and one 3
. Some of the possible pairs [new1, new2]
are [22, 93]
, [23, 92]
, [223, 9]
and [2, 329]
.Return the minimum possible sum of new1
and new2
.
\n
Example 1:
\n\n\nInput: num = 2932\nOutput: 52\nExplanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\n\n\n
Example 2:
\n\n\nInput: num = 4009\nOutput: 13\nExplanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n\n\n
\n
Constraints:
\n\n1000 <= num <= 9999
You are given a 0-indexed integer array nums
and an integer pivot
. Rearrange nums
such that the following conditions are satisfied:
pivot
appears before every element greater than pivot
.pivot
appears in between the elements less than and greater than pivot
.pivot
and the elements greater than pivot
is maintained.\n\tpi
, pj
where pi
is the new position of the ith
element and pj
is the new position of the jth
element. For elements less than pivot
, if i < j
and nums[i] < pivot
and nums[j] < pivot
, then pi < pj
. Similarly for elements greater than pivot
, if i < j
and nums[i] > pivot
and nums[j] > pivot
, then pi < pj
.Return nums
after the rearrangement.
\n
Example 1:
\n\n\nInput: nums = [9,12,5,10,14,3,10], pivot = 10\nOutput: [9,5,3,10,10,12,14]\nExplanation: \nThe elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.\n\n\n
Example 2:
\n\n\nInput: nums = [-3,4,3,2], pivot = 2\nOutput: [-3,2,4,3]\nExplanation: \nThe element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-106 <= nums[i] <= 106
pivot
equals to an element of nums
.You are given a 0-indexed integer array nums
and an integer pivot
. Rearrange nums
such that the following conditions are satisfied:
pivot
appears before every element greater than pivot
.pivot
appears in between the elements less than and greater than pivot
.pivot
and the elements greater than pivot
is maintained.\n\tpi
, pj
where pi
is the new position of the ith
element and pj
is the new position of the jth
element. If i < j
and both elements are smaller (or larger) than pivot
, then pi < pj
.Return nums
after the rearrangement.
\n
Example 1:
\n\n\nInput: nums = [9,12,5,10,14,3,10], pivot = 10\nOutput: [9,5,3,10,10,12,14]\nExplanation: \nThe elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.\n\n\n
Example 2:
\n\n\nInput: nums = [-3,4,3,2], pivot = 2\nOutput: [-3,2,4,3]\nExplanation: \nThe element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-106 <= nums[i] <= 106
pivot
equals to an element of nums
.A generic microwave supports cooking times for:
\n\n1
second.99
minutes and 99
seconds.To set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example,
\n\n9
5
4
(three digits). It is normalized as 0954
and interpreted as 9
minutes and 54
seconds.0
0
0
8
(four digits). It is interpreted as 0
minutes and 8
seconds.8
0
9
0
. It is interpreted as 80
minutes and 90
seconds.8
1
3
0
. It is interpreted as 81
minutes and 30
seconds.You are given integers startAt
, moveCost
, pushCost
, and targetSeconds
. Initially, your finger is on the digit startAt
. Moving the finger above any specific digit costs moveCost
units of fatigue. Pushing the digit below the finger once costs pushCost
units of fatigue.
There can be multiple ways to set the microwave to cook for targetSeconds
seconds but you are interested in the way with the minimum cost.
Return the minimum cost to set targetSeconds
seconds of cooking time.
Remember that one minute consists of 60
seconds.
\n
Example 1:
\n\nInput: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600\nOutput: 6\nExplanation: The following are the possible ways to set the cooking time.\n- 1 0 0 0, interpreted as 10 minutes and 0 seconds.\n The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).\n The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost.\n- 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.\n The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12.\n- 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.\n The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.\n\n\n
Example 2:
\n\nInput: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76\nOutput: 6\nExplanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds.\nThe finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6\nNote other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.\n\n\n
\n
Constraints:
\n\n0 <= startAt <= 9
1 <= moveCost, pushCost <= 105
1 <= targetSeconds <= 6039
You are given a 0-indexed integer array nums
consisting of 3 * n
elements.
You are allowed to remove any subsequence of elements of size exactly n
from nums
. The remaining 2 * n
elements will be divided into two equal parts:
n
elements belonging to the first part and their sum is sumfirst
.n
elements belonging to the second part and their sum is sumsecond
.The difference in sums of the two parts is denoted as sumfirst - sumsecond
.
sumfirst = 3
and sumsecond = 2
, their difference is 1
.sumfirst = 2
and sumsecond = 3
, their difference is -1
.Return the minimum difference possible between the sums of the two parts after the removal of n
elements.
\n
Example 1:
\n\n\nInput: nums = [3,1,2]\nOutput: -1\nExplanation: Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1. \n\n\n
Example 2:
\n\n\nInput: nums = [7,9,5,8,1,3]\nOutput: 1\nExplanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.\n\n\n
\n
Constraints:
\n\nnums.length == 3 * n
1 <= n <= 105
1 <= nums[i] <= 105
You are given a 0-indexed integer array nums
. Rearrange the values of nums
according to the following rules:
nums
in non-increasing order.\n\n\tnums = [4,1,2,3]
before this step, it becomes [4,3,2,1]
after. The values at odd indices 1
and 3
are sorted in non-increasing order.nums
in non-decreasing order.\n\tnums = [4,1,2,3]
before this step, it becomes [2,1,4,3]
after. The values at even indices 0
and 2
are sorted in non-decreasing order.Return the array formed after rearranging the values of nums
.
\n
Example 1:
\n\n\nInput: nums = [4,1,2,3]\nOutput: [2,3,4,1]\nExplanation: \nFirst, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].\n\n\n
Example 2:
\n\n\nInput: nums = [2,1]\nOutput: [2,1]\nExplanation: \nSince there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array. \n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given an integer num.
Rearrange the digits of num
such that its value is minimized and it does not contain any leading zeros.
Return the rearranged number with minimal value.
\n\nNote that the sign of the number does not change after rearranging the digits.
\n\n\n
Example 1:
\n\n\nInput: num = 310\nOutput: 103\nExplanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.\n\n\n
Example 2:
\n\n\nInput: num = -7605\nOutput: -7650\nExplanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.\n\n\n
\n
Constraints:
\n\n-1015 <= num <= 1015
A Bitset is a data structure that compactly stores bits.
\n\nImplement the Bitset
class:
Bitset(int size)
Initializes the Bitset with size
bits, all of which are 0
.void fix(int idx)
Updates the value of the bit at the index idx
to 1
. If the value was already 1
, no change occurs.void unfix(int idx)
Updates the value of the bit at the index idx
to 0
. If the value was already 0
, no change occurs.void flip()
Flips the values of each bit in the Bitset. In other words, all bits with value 0
will now have value 1
and vice versa.boolean all()
Checks if the value of each bit in the Bitset is 1
. Returns true
if it satisfies the condition, false
otherwise.boolean one()
Checks if there is at least one bit in the Bitset with value 1
. Returns true
if it satisfies the condition, false
otherwise.int count()
Returns the total number of bits in the Bitset which have value 1
.String toString()
Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith
index should coincide with the value at the ith
bit of the Bitset.\n
Example 1:
\n\n\nInput\n["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"]\n[[5], [3], [1], [], [], [0], [], [], [0], [], []]\nOutput\n[null, null, null, null, false, null, null, true, null, 2, "01010"]\n\nExplanation\nBitset bs = new Bitset(5); // bitset = "00000".\nbs.fix(3); // the value at idx = 3 is updated to 1, so bitset = "00010".\nbs.fix(1); // the value at idx = 1 is updated to 1, so bitset = "01010". \nbs.flip(); // the value of each bit is flipped, so bitset = "10101". \nbs.all(); // return False, as not all values of the bitset are 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "00101".\nbs.flip(); // the value of each bit is flipped, so bitset = "11010". \nbs.one(); // return True, as there is at least 1 index with value 1.\nbs.unfix(0); // the value at idx = 0 is updated to 0, so bitset = "01010".\nbs.count(); // return 2, as there are 2 bits with value 1.\nbs.toString(); // return "01010", which is the composition of bitset.\n\n\n
\n
Constraints:
\n\n1 <= size <= 105
0 <= idx <= size - 1
105
calls will be made in total to fix
, unfix
, flip
, all
, one
, count
, and toString
.all
, one
, count
, or toString
.5
calls will be made to toString
.You are given a 0-indexed binary string s
which represents a sequence of train cars. s[i] = '0'
denotes that the ith
car does not contain illegal goods and s[i] = '1'
denotes that the ith
car does contain illegal goods.
As the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times:
\n\ns[0]
) which takes 1 unit of time.s[s.length - 1]
) which takes 1 unit of time.Return the minimum time to remove all the cars containing illegal goods.
\n\nNote that an empty sequence of cars is considered to have no cars containing illegal goods.
\n\n\n
Example 1:
\n\n\nInput: s = "1100101"\nOutput: 5\nExplanation: \nOne way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.\n\n\n
Example 2:
\n\n\nInput: s = "0010"\nOutput: 2\nExplanation:\nOne way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.\n\n
\n
Constraints:
\n\n1 <= s.length <= 2 * 105
s[i]
is either '0'
or '1'
.You are given two non-negative integers num1
and num2
.
In one operation, if num1 >= num2
, you must subtract num2
from num1
, otherwise subtract num1
from num2
.
num1 = 5
and num2 = 4
, subtract num2
from num1
, thus obtaining num1 = 1
and num2 = 4
. However, if num1 = 4
and num2 = 5
, after one operation, num1 = 4
and num2 = 1
.Return the number of operations required to make either num1 = 0
or num2 = 0
.
\n
Example 1:
\n\n\nInput: num1 = 2, num2 = 3\nOutput: 3\nExplanation: \n- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.\n\n\n
Example 2:
\n\n\nInput: num1 = 10, num2 = 10\nOutput: 1\nExplanation: \n- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.\n\n\n
\n
Constraints:
\n\n0 <= num1, num2 <= 105
You are given a 0-indexed array nums
consisting of n
positive integers.
The array nums
is called alternating if:
nums[i - 2] == nums[i]
, where 2 <= i <= n - 1
.nums[i - 1] != nums[i]
, where 1 <= i <= n - 1
.In one operation, you can choose an index i
and change nums[i]
into any positive integer.
Return the minimum number of operations required to make the array alternating.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,3,2,4,3]\nOutput: 3\nExplanation:\nOne way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations. \n\n\n
Example 2:
\n\n\nInput: nums = [1,2,2,2,2]\nOutput: 2\nExplanation:\nOne way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
You are given an array of positive integers beans
, where each integer represents the number of magic beans found in a particular magic bag.
Remove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.
\n\nReturn the minimum number of magic beans that you have to remove.
\n\n\n
Example 1:
\n\n\nInput: beans = [4,1,6,5]\nOutput: 4\nExplanation: \n- We remove 1 bean from the bag with only 1 bean.\n This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer.\n\n\n
Example 2:
\n\n\nInput: beans = [2,10,3,2]\nOutput: 7\nExplanation:\n- We remove 2 beans from one of the bags with 2 beans.\n This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer.\n\n\n
\n
Constraints:
\n\n1 <= beans.length <= 105
1 <= beans[i] <= 105
You are given an integer array nums
of length n
and an integer numSlots
such that 2 * numSlots >= n
. There are numSlots
slots numbered from 1
to numSlots
.
You have to place all n
integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND
of every number with its respective slot number.
[1, 3]
into slot 1
and [4, 6]
into slot 2
is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4
.Return the maximum possible AND sum of nums
given numSlots
slots.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6], numSlots = 3\nOutput: 9\nExplanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. \nThis gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,10,4,7,1], numSlots = 9\nOutput: 24\nExplanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9.\nThis gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= numSlots <= 9
1 <= n <= 2 * numSlots
1 <= nums[i] <= 15
nums
of length n
and an integer k
, return the number of pairs (i, j)
where 0 <= i < j < n
, such that nums[i] == nums[j]
and (i * j)
is divisible by k
.\n\n
Example 1:
\n\n\nInput: nums = [3,1,2,2,2,1,3], k = 2\nOutput: 4\nExplanation:\nThere are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4], k = 1\nOutput: 0\nExplanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i], k <= 100
Given an integer num
, return three consecutive integers (as a sorted array) that sum to num
. If num
cannot be expressed as the sum of three consecutive integers, return an empty array.
\n
Example 1:
\n\n\nInput: num = 33\nOutput: [10,11,12]\nExplanation: 33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].\n\n\n
Example 2:
\n\n\nInput: num = 4\nOutput: []\nExplanation: There is no way to express 4 as the sum of 3 consecutive integers.\n\n\n
\n
Constraints:
\n\n0 <= num <= 1015
You are given an integer finalSum
. Split it into a sum of a maximum number of unique positive even integers.
finalSum = 12
, the following splits are valid (unique positive even integers summing up to finalSum
): (12)
, (2 + 10)
, (2 + 4 + 6)
, and (4 + 8)
. Among them, (2 + 4 + 6)
contains the maximum number of integers. Note that finalSum
cannot be split into (2 + 2 + 4 + 4)
as all the numbers should be unique.Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum
, return an empty list. You may return the integers in any order.
\n
Example 1:
\n\n\nInput: finalSum = 12\nOutput: [2,4,6]\nExplanation: The following are valid splits:\n\n(12)
,(2 + 10)
,(2 + 4 + 6)
, and(4 + 8)
.\n(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\nNote that [2,6,4], [6,2,4], etc. are also accepted.\n
Example 2:
\n\n\nInput: finalSum = 7\nOutput: []\nExplanation: There are no valid splits for the given finalSum.\nThus, we return an empty array.\n\n\n
Example 3:
\n\n\nInput: finalSum = 28\nOutput: [6,8,2,12]\nExplanation: The following are valid splits:\n\n(2 + 26)
,(6 + 8 + 2 + 12)
, and(4 + 24)
. \n(6 + 8 + 2 + 12)
has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\nNote that [10,2,4,12], [6,2,4,16], etc. are also accepted.\n
\n
Constraints:
\n\n1 <= finalSum <= 1010
You are given two 0-indexed arrays nums1
and nums2
of length n
, both of which are permutations of [0, 1, ..., n - 1]
.
A good triplet is a set of 3
distinct values which are present in increasing order by position both in nums1
and nums2
. In other words, if we consider pos1v
as the index of the value v
in nums1
and pos2v
as the index of the value v
in nums2
, then a good triplet will be a set (x, y, z)
where 0 <= x, y, z <= n - 1
, such that pos1x < pos1y < pos1z
and pos2x < pos2y < pos2z
.
Return the total number of good triplets.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [2,0,1,3], nums2 = [0,1,2,3]\nOutput: 1\nExplanation: \nThere are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet.\n\n\n
Example 2:
\n\n\nInput: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\nOutput: 4\nExplanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
3 <= n <= 105
0 <= nums1[i], nums2[i] <= n - 1
nums1
and nums2
are permutations of [0, 1, ..., n - 1]
.Given a positive integer num
, return the number of positive integers less than or equal to num
whose digit sums are even.
The digit sum of a positive integer is the sum of all its digits.
\n\n\n
Example 1:
\n\n\nInput: num = 4\nOutput: 2\nExplanation:\nThe only integers less than or equal to 4 whose digit sums are even are 2 and 4. \n\n\n
Example 2:
\n\n\nInput: num = 30\nOutput: 14\nExplanation:\nThe 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.\n\n\n
\n
Constraints:
\n\n1 <= num <= 1000
You are given the head
of a linked list, which contains a series of integers separated by 0
's. The beginning and end of the linked list will have Node.val == 0
.
For every two consecutive 0
's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0
's.
Return the head
of the modified linked list.
\n
Example 1:
\n\nInput: head = [0,3,1,0,4,5,2,0]\nOutput: [4,11]\nExplanation: \nThe above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.\n\n\n
Example 2:
\n\nInput: head = [0,1,0,3,0,2,2,0]\nOutput: [1,3,4]\nExplanation: \nThe above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.\n\n\n
\n
Constraints:
\n\n[3, 2 * 105]
.0 <= Node.val <= 1000
Node.val == 0
.Node.val == 0
.You are given a string s
and an integer repeatLimit
. Construct a new string repeatLimitedString
using the characters of s
such that no letter appears more than repeatLimit
times in a row. You do not have to use all characters from s
.
Return the lexicographically largest repeatLimitedString
possible.
A string a
is lexicographically larger than a string b
if in the first position where a
and b
differ, string a
has a letter that appears later in the alphabet than the corresponding letter in b
. If the first min(a.length, b.length)
characters do not differ, then the longer string is the lexicographically larger one.
\n
Example 1:
\n\n\nInput: s = "cczazcc", repeatLimit = 3\nOutput: "zzcccac"\nExplanation: We use all of the characters from s to construct the repeatLimitedString "zzcccac".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".\nNote that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.\n\n\n
Example 2:
\n\n\nInput: s = "aababab", repeatLimit = 2\nOutput: "bbabaa"\nExplanation: We use only some of the characters from s to construct the repeatLimitedString "bbabaa". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".\nNote that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.\n\n\n
\n
Constraints:
\n\n1 <= repeatLimit <= s.length <= 105
s
consists of lowercase English letters.Given a 0-indexed integer array nums
of length n
and an integer k
, return the number of pairs (i, j)
such that:
0 <= i < j <= n - 1
andnums[i] * nums[j]
is divisible by k
.\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5], k = 2\nOutput: 7\nExplanation: \nThe 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. \n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4], k = 5\nOutput: 0\nExplanation: There does not exist any pair of indices whose corresponding product is divisible by 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i], k <= 105
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
.
\n
Example 1:
\n\n\nInput: words = ["pay","attention","practice","attend"], pref
= "at"\nOutput: 2\nExplanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".\n
\n\nExample 2:
\n\n\nInput: words = ["leetcode","win","loops","success"], pref
= "code"\nOutput: 0\nExplanation: There are no strings that contain "code" as a prefix.\n
\n\n\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i]
and pref
consist of lowercase English letters.You are given two strings s
and t
. In one step, you can append any character to either s
or t
.
Return the minimum number of steps to make s
and t
anagrams of each other.
An anagram of a string is a string that contains the same characters with a different (or the same) ordering.
\n\n\n
Example 1:
\n\n\nInput: s = "leetcode", t = "coats"\nOutput: 7\nExplanation: \n- In 2 steps, we can append the letters in "as" onto s = "leetcode", forming s = "leetcodeas".\n- In 5 steps, we can append the letters in "leede" onto t = "coats", forming t = "coatsleede".\n"leetcodeas" and "coatsleede" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.\n\n\n
Example 2:
\n\n\nInput: s = "night", t = "thing"\nOutput: 0\nExplanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 2 * 105
s
and t
consist of lowercase English letters.You are given an array time
where time[i]
denotes the time taken by the ith
bus to complete one trip.
Each bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.
\n\nYou are also given an integer totalTrips
, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips
trips.
\n
Example 1:
\n\n\nInput: time = [1,2,3], totalTrips = 5\nOutput: 3\nExplanation:\n- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.\n\n\n
Example 2:
\n\n\nInput: time = [2], totalTrips = 1\nOutput: 2\nExplanation:\nThere is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.\n\n\n
\n
Constraints:
\n\n1 <= time.length <= 105
1 <= time[i], totalTrips <= 107
You are given a 0-indexed 2D integer array tires
where tires[i] = [fi, ri]
indicates that the ith
tire can finish its xth
successive lap in fi * ri(x-1)
seconds.
fi = 3
and ri = 2
, then the tire would finish its 1st
lap in 3
seconds, its 2nd
lap in 3 * 2 = 6
seconds, its 3rd
lap in 3 * 22 = 12
seconds, etc.You are also given an integer changeTime
and an integer numLaps
.
The race consists of numLaps
laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime
seconds.
Return the minimum time to finish the race.
\n\n\n
Example 1:
\n\n\nInput: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\nOutput: 21\nExplanation: \nLap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.\n\n\n
Example 2:
\n\n\nInput: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\nOutput: 25\nExplanation: \nLap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds. \n\n\n
\n
Constraints:
\n\n1 <= tires.length <= 105
tires[i].length == 2
1 <= fi, changeTime <= 105
2 <= ri <= 105
1 <= numLaps <= 1000
You are given a 0-indexed integer array nums
. You are also given an integer key
, which is present in nums
.
For every unique integer target
in nums
, count the number of times target
immediately follows an occurrence of key
in nums
. In other words, count the number of indices i
such that:
0 <= i <= nums.length - 2
,nums[i] == key
and,nums[i + 1] == target
.Return the target
with the maximum count. The test cases will be generated such that the target
with maximum count is unique.
\n
Example 1:
\n\n\nInput: nums = [1,100,200,1,100], key = 1\nOutput: 100\nExplanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,2,2,3], key = 2\nOutput: 2\nExplanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 1000
1 <= nums[i] <= 1000
You are given a 0-indexed integer array mapping
which represents the mapping rule of a shuffled decimal system. mapping[i] = j
means digit i
should be mapped to digit j
in this system.
The mapped value of an integer is the new integer obtained by replacing each occurrence of digit i
in the integer with mapping[i]
for all 0 <= i <= 9
.
You are also given another integer array nums
. Return the array nums
sorted in non-decreasing order based on the mapped values of its elements.
Notes:
\n\nnums
should only be sorted based on their mapped values and not be replaced by them.\n
Example 1:
\n\n\nInput: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\nOutput: [338,38,991]\nExplanation: \nMap the number 991 as follows:\n1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.\n2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.\nTherefore, the mapped value of 991 is 669.\n338 maps to 007, or 7 after removing the leading zeros.\n38 maps to 07, which is also 7 after removing leading zeros.\nSince 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.\nThus, the sorted array is [338,38,991].\n\n\n
Example 2:
\n\n\nInput: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]\nOutput: [123,456,789]\nExplanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].\n\n\n
\n
Constraints:
\n\nmapping.length == 10
0 <= mapping[i] <= 9
mapping[i]
are unique.1 <= nums.length <= 3 * 104
0 <= nums[i] < 109
You are given a positive integer n
representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0
to n - 1
(inclusive).
You are also given a 2D integer array edges
, where edges[i] = [fromi, toi]
denotes that there is a unidirectional edge from fromi
to toi
in the graph.
Return a list answer
, where answer[i]
is the list of ancestors of the ith
node, sorted in ascending order.
A node u
is an ancestor of another node v
if u
can reach v
via a set of edges.
\n
Example 1:
\n\nInput: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]\nOutput: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]\nExplanation:\nThe above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3.\n\n\n
Example 2:
\n\nInput: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nOutput: [[],[0],[0,1],[0,1,2],[0,1,2,3]]\nExplanation:\nThe above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
0 <= edges.length <= min(2000, n * (n - 1) / 2)
edges[i].length == 2
0 <= fromi, toi <= n - 1
fromi != toi
You are given a string s
consisting only of lowercase English letters.
In one move, you can select any two adjacent characters of s
and swap them.
Return the minimum number of moves needed to make s
a palindrome.
Note that the input will be generated such that s
can always be converted to a palindrome.
\n
Example 1:
\n\n\nInput: s = "aabb"\nOutput: 2\nExplanation:\nWe can obtain two palindromes from s, "abba" and "baab". \n- We can obtain "abba" from s in 2 moves: "aabb" -> "abab" -> "abba".\n- We can obtain "baab" from s in 2 moves: "aabb" -> "abab" -> "baab".\nThus, the minimum number of moves needed to make s a palindrome is 2.\n\n\n
Example 2:
\n\n\nInput: s = "letelt"\nOutput: 2\nExplanation:\nOne of the palindromes we can obtain from s in 2 moves is "lettel".\nOne of the ways we can obtain it is "letelt" -> "letetl" -> "lettel".\nOther palindromes such as "tleelt" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2000
s
consists only of lowercase English letters.s
can be converted to a palindrome using a finite number of moves.A cell (r, c)
of an excel sheet is represented as a string "<col><row>"
where:
<col>
denotes the column number c
of the cell. It is represented by alphabetical letters.\n\n\t1st
column is denoted by 'A'
, the 2nd
by 'B'
, the 3rd
by 'C'
, and so on.<row>
is the row number r
of the cell. The rth
row is represented by the integer r
.You are given a string s
in the format "<col1><row1>:<col2><row2>"
, where <col1>
represents the column c1
, <row1>
represents the row r1
, <col2>
represents the column c2
, and <row2>
represents the row r2
, such that r1 <= r2
and c1 <= c2
.
Return the list of cells (x, y)
such that r1 <= x <= r2
and c1 <= y <= c2
. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.
\n
Example 1:
\n\nInput: s = "K1:L2"\nOutput: ["K1","K2","L1","L2"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.\n\n\n
Example 2:
\n\nInput: s = "A1:F1"\nOutput: ["A1","B1","C1","D1","E1","F1"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.\n\n\n
\n
Constraints:
\n\ns.length == 5
'A' <= s[0] <= s[3] <= 'Z'
'1' <= s[1] <= s[4] <= '9'
s
consists of uppercase English letters, digits and ':'
.You are given an integer array nums
and an integer k
. Append k
unique positive integers that do not appear in nums
to nums
such that the resulting total sum is minimum.
Return the sum of the k
integers appended to nums
.
\n
Example 1:
\n\n\nInput: nums = [1,4,25,10,25], k = 2\nOutput: 5\nExplanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5.\n\n
Example 2:
\n\n\nInput: nums = [5,6], k = 6\nOutput: 25\nExplanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 108
You are given a 2D integer array descriptions
where descriptions[i] = [parenti, childi, isLefti]
indicates that parenti
is the parent of childi
in a binary tree of unique values. Furthermore,
isLefti == 1
, then childi
is the left child of parenti
.isLefti == 0
, then childi
is the right child of parenti
.Construct the binary tree described by descriptions
and return its root.
The test cases will be generated such that the binary tree is valid.
\n\n\n
Example 1:
\n\nInput: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput: [50,20,80,15,17,19]\nExplanation: The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\n
Example 2:
\n\nInput: descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput: [1,2,null,null,3,4]\nExplanation: The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n\n\n
\n
Constraints:
\n\n1 <= descriptions.length <= 104
descriptions[i].length == 3
1 <= parenti, childi <= 105
0 <= isLefti <= 1
descriptions
is valid.You are given an array of integers nums
. Perform the following steps:
nums
that are non-coprime.Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.
\n\nThe test cases are generated such that the values in the final array are less than or equal to 108
.
Two values x
and y
are non-coprime if GCD(x, y) > 1
where GCD(x, y)
is the Greatest Common Divisor of x
and y
.
\n
Example 1:
\n\n\nInput: nums = [6,4,3,2,7,6,2]\nOutput: [12,7,6]\nExplanation: \n- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2,1,1,3,3,3]\nOutput: [2,1,1,3]\nExplanation: \n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
108
.You are given a 0-indexed integer array nums
and two integers key
and k
. A k-distant index is an index i
of nums
for which there exists at least one index j
such that |i - j| <= k
and nums[j] == key
.
Return a list of all k-distant indices sorted in increasing order.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,4,9,1,3,9,5], key = 9, k = 1\nOutput: [1,2,3,4,5,6]\nExplanation: Here,\n\nnums[2] == key
andnums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j
where|0 - j| <= k
andnums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.\n
Thus, we return [1,2,3,4,5,6] which is sorted in increasing order. \n
Example 2:
\n\n\nInput: nums = [2,2,2,2,2], key = 2, k = 2\nOutput: [0,1,2,3,4]\nExplanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
key
is an integer from the array nums
.1 <= k <= nums.length
There is an n x n
0-indexed grid with some artifacts buried in it. You are given the integer n
and a 0-indexed 2D integer array artifacts
describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i]
denotes that the ith
artifact is buried in the subgrid where:
(r1i, c1i)
is the coordinate of the top-left cell of the ith
artifact and(r2i, c2i)
is the coordinate of the bottom-right cell of the ith
artifact.You will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it.
\n\nGiven a 0-indexed 2D integer array dig
where dig[i] = [ri, ci]
indicates that you will excavate the cell (ri, ci)
, return the number of artifacts that you can extract.
The test cases are generated such that:
\n\n4
cells.dig
are unique.\n
Example 1:
\n\nInput: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]\nOutput: 1\nExplanation: \nThe different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.\nThere is 1 artifact that can be extracted, namely the red artifact.\nThe blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.\nThus, we return 1.\n\n\n
Example 2:
\n\nInput: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]\nOutput: 2\nExplanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2. \n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
1 <= artifacts.length, dig.length <= min(n2, 105)
artifacts[i].length == 4
dig[i].length == 2
0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1
r1i <= r2i
c1i <= c2i
4
.dig
are unique.You are given a 0-indexed integer array nums
representing the contents of a pile, where nums[0]
is the topmost element of the pile.
In one move, you can perform either of the following:
\n\nYou are also given an integer k
, which denotes the total number of moves to be made.
Return the maximum value of the topmost element of the pile possible after exactly k
moves. In case it is not possible to obtain a non-empty pile after k
moves, return -1
.
\n
Example 1:
\n\n\nInput: nums = [5,2,2,4,0,6], k = 4\nOutput: 5\nExplanation:\nOne of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.\n\n\n
Example 2:
\n\n\nInput: nums = [2], k = 1\nOutput: -1\nExplanation: \nIn the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i], k <= 109
You are given an integer n
denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0
to n - 1
.
You are also given a 2D integer array edges
where edges[i] = [fromi, toi, weighti]
denotes that there exists a directed edge from fromi
to toi
with weight weighti
.
Lastly, you are given three distinct integers src1
, src2
, and dest
denoting three distinct nodes of the graph.
Return the minimum weight of a subgraph of the graph such that it is possible to reach dest
from both src1
and src2
via a set of edges of this subgraph. In case such a subgraph does not exist, return -1
.
A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.
\n\n\n
Example 1:
\n\nInput: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5\nOutput: 9\nExplanation:\nThe above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.\n\n\n
Example 2:
\n\nInput: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2\nOutput: -1\nExplanation:\nThe above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
0 <= edges.length <= 105
edges[i].length == 3
0 <= fromi, toi, src1, src2, dest <= n - 1
fromi != toi
src1
, src2
, and dest
are pairwise distinct.1 <= weight[i] <= 105
You are given an integer array nums
consisting of 2 * n
integers.
You need to divide nums
into n
pairs such that:
Return true
if nums can be divided into n
pairs, otherwise return false
.
\n
Example 1:
\n\n\nInput: nums = [3,2,3,2,2,2]\nOutput: true\nExplanation: \nThere are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: false\nExplanation: \nThere is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.\n\n\n
\n
Constraints:
\n\nnums.length == 2 * n
1 <= n <= 500
1 <= nums[i] <= 500
You are given a 0-indexed string text
and another 0-indexed string pattern
of length 2
, both of which consist of only lowercase English letters.
You can add either pattern[0]
or pattern[1]
anywhere in text
exactly once. Note that the character can be added even at the beginning or at the end of text
.
Return the maximum number of times pattern
can occur as a subsequence of the modified text
.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
\n\n\n
Example 1:
\n\n\nInput: text = "abdcdbc", pattern = "ac"\nOutput: 4\nExplanation:\nIf we add pattern[0] = 'a' in between text[1] and text[2], we get "abadcdbc". Now, the number of times "ac" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences "ac" after adding a character to text are "aabdcdbc" and "abdacdbc".\nHowever, strings such as "abdcadbc", "abdccdbc", and "abdcdbcc", although obtainable, have only 3 subsequences "ac" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences "ac" by adding only one character.\n\n\n
Example 2:
\n\n\nInput: text = "aabb", pattern = "ab"\nOutput: 6\nExplanation:\nSome of the strings which can be obtained from text and have 6 subsequences "ab" are "aaabb", "aaabb", and "aabbb".\n\n\n
\n
Constraints:
\n\n1 <= text.length <= 105
pattern.length == 2
text
and pattern
consist only of lowercase English letters.You are given an array nums
of positive integers. In one operation, you can choose any number from nums
and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)
Return the minimum number of operations to reduce the sum of nums
by at least half.
\n
Example 1:
\n\n\nInput: nums = [5,19,8,1]\nOutput: 3\nExplanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\n
Example 2:
\n\n\nInput: nums = [3,8,20]\nOutput: 3\nExplanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 107
You are given a 0-indexed binary string floor
, which represents the colors of tiles on a floor:
floor[i] = '0'
denotes that the ith
tile of the floor is colored black.floor[i] = '1'
denotes that the ith
tile of the floor is colored white.You are also given numCarpets
and carpetLen
. You have numCarpets
black carpets, each of length carpetLen
tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.
Return the minimum number of white tiles still visible.
\n\n\n
Example 1:
\n\nInput: floor = "10110101", numCarpets = 2, carpetLen = 2\nOutput: 2\nExplanation: \nThe figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.\n\n\n
Example 2:
\n\nInput: floor = "11111", numCarpets = 2, carpetLen = 3\nOutput: 0\nExplanation: \nThe figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.\n\n\n
\n
Constraints:
\n\n1 <= carpetLen <= floor.length <= 1000
floor[i]
is either '0'
or '1'
.1 <= numCarpets <= 1000
You are given a 0-indexed integer array nums
. An index i
is part of a hill in nums
if the closest non-equal neighbors of i
are smaller than nums[i]
. Similarly, an index i
is part of a valley in nums
if the closest non-equal neighbors of i
are larger than nums[i]
. Adjacent indices i
and j
are part of the same hill or valley if nums[i] == nums[j]
.
Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.
\n\nReturn the number of hills and valleys in nums
.
\n
Example 1:
\n\n\nInput: nums = [2,4,1,1,6,5]\nOutput: 3\nExplanation:\nAt index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.\n\n\n
Example 2:
\n\n\nInput: nums = [6,6,5,5,4,1]\nOutput: 0\nExplanation:\nAt index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 100
1 <= nums[i] <= 100
There are n
cars on an infinitely long road. The cars are numbered from 0
to n - 1
from left to right and each car is present at a unique point.
You are given a 0-indexed string directions
of length n
. directions[i]
can be either 'L'
, 'R'
, or 'S'
denoting whether the ith
car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.
The number of collisions can be calculated as follows:
\n\n2
.1
.After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.
\n\nReturn the total number of collisions that will happen on the road.
\n\n\n
Example 1:
\n\n\nInput: directions = "RLRSLL"\nOutput: 5\nExplanation:\nThe collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5. \n\n\n
Example 2:
\n\n\nInput: directions = "LLRR"\nOutput: 0\nExplanation:\nNo cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.\n\n
\n
Constraints:
\n\n1 <= directions.length <= 105
directions[i]
is either 'L'
, 'R'
, or 'S'
.Alice and Bob are opponents in an archery competition. The competition has set the following rules:
\n\nnumArrows
arrows and then Bob shoots numArrows
arrows.0
to 11
inclusive.k
(in between 0
to 11
), say Alice and Bob have shot ak
and bk
arrows on that section respectively. If ak >= bk
, then Alice takes k
points. If ak < bk
, then Bob takes k
points.ak == bk == 0
, then nobody takes k
points.For example, if Alice and Bob both shot 2
arrows on the section with score 11
, then Alice takes 11
points. On the other hand, if Alice shot 0
arrows on the section with score 11
and Bob shot 2
arrows on that same section, then Bob takes 11
points.
You are given the integer numArrows
and an integer array aliceArrows
of size 12
, which represents the number of arrows Alice shot on each scoring section from 0
to 11
. Now, Bob wants to maximize the total number of points he can obtain.
Return the array bobArrows
which represents the number of arrows Bob shot on each scoring section from 0
to 11
. The sum of the values in bobArrows
should equal numArrows
.
If there are multiple ways for Bob to earn the maximum total points, return any one of them.
\n\n\n
Example 1:
\n\nInput: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\nOutput: [0,0,0,0,1,1,0,0,1,2,3,1]\nExplanation: The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.\n\n\n
Example 2:
\n\nInput: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\nOutput: [0,0,0,0,0,0,0,0,1,1,1,0]\nExplanation: The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.\n\n\n
\n
Constraints:
\n\n1 <= numArrows <= 105
aliceArrows.length == bobArrows.length == 12
0 <= aliceArrows[i], bobArrows[i] <= numArrows
sum(aliceArrows[i]) == numArrows
You are given a 0-indexed string s
. You are also given a 0-indexed string queryCharacters
of length k
and a 0-indexed array of integer indices queryIndices
of length k
, both of which are used to describe k
queries.
The ith
query updates the character in s
at index queryIndices[i]
to the character queryCharacters[i]
.
Return an array lengths
of length k
where lengths[i]
is the length of the longest substring of s
consisting of only one repeating character after the ith
query is performed.
\n
Example 1:
\n\n\nInput: s = "babacc", queryCharacters = "bcb", queryIndices = [1,3,3]\nOutput: [3,3,4]\nExplanation: \n- 1st query updates s = "bbbacc". The longest substring consisting of one repeating character is "bbb" with length 3.\n- 2nd query updates s = "bbbccc". \n The longest substring consisting of one repeating character can be "bbb" or "ccc" with length 3.\n- 3rd query updates s = "bbbbcc". The longest substring consisting of one repeating character is "bbbb" with length 4.\nThus, we return [3,3,4].\n\n\n
Example 2:
\n\n\nInput: s = "abyzz", queryCharacters = "aa", queryIndices = [2,1]\nOutput: [2,3]\nExplanation:\n- 1st query updates s = "abazz". The longest substring consisting of one repeating character is "zz" with length 2.\n- 2nd query updates s = "aaazz". The longest substring consisting of one repeating character is "aaa" with length 3.\nThus, we return [2,3].\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.k == queryCharacters.length == queryIndices.length
1 <= k <= 105
queryCharacters
consists of lowercase English letters.0 <= queryIndices[i] < s.length
Given two 0-indexed integer arrays nums1
and nums2
, return a list answer
of size 2
where:
answer[0]
is a list of all distinct integers in nums1
which are not present in nums2
.answer[1]
is a list of all distinct integers in nums2
which are not present in nums1
.Note that the integers in the lists may be returned in any order.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [1,2,3], nums2 = [2,4,6]\nOutput: [[1,3],[4,6]]\nExplanation:\nFor nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].\n\n
Example 2:
\n\n\nInput: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput: [[3],[]]\nExplanation:\nFor nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
-1000 <= nums1[i], nums2[i] <= 1000
Given two 0-indexed integer arrays nums1
and nums2
, return a list answer
of size 2
where:
answer[0]
is a list of all distinct integers in nums1
which are not present in nums2
.answer[1]
is a list of all distinct integers in nums2
which are not present in nums1
.Note that the integers in the lists may be returned in any order.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [1,2,3], nums2 = [2,4,6]\nOutput: [[1,3],[4,6]]\nExplanation:\nFor nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums1. Therefore, answer[1] = [4,6].\n\n
Example 2:
\n\n\nInput: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput: [[3],[]]\nExplanation:\nFor nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 1000
-1000 <= nums1[i], nums2[i] <= 1000
You are given a 0-indexed integer array nums
. The array nums
is beautiful if:
nums.length
is even.nums[i] != nums[i + 1]
for all i % 2 == 0
.Note that an empty array is considered beautiful.
\n\nYou can delete any number of elements from nums
. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.
Return the minimum number of elements to delete from nums
to make it beautiful.
\n
Example 1:
\n\n\nInput: nums = [1,1,2,3,5]\nOutput: 1\nExplanation: You can delete either\n\nnums[0]
ornums[1]
to makenums
= [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to makenums
beautiful.\n
Example 2:
\n\n\nInput: nums = [1,1,2,2,3,3]\nOutput: 2\nExplanation: You can delete\n\nnums[0]
andnums[5]
to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
Given an integer array queries
and a positive integer intLength
, return an array answer
where answer[i]
is either the queries[i]th
smallest positive palindrome of length intLength
or -1
if no such palindrome exists.
A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.
\n\n\n
Example 1:
\n\n\nInput: queries = [1,2,3,4,5,90], intLength = 3\nOutput: [101,111,121,131,141,999]\nExplanation:\nThe first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90th palindrome of length 3 is 999.\n\n\n
Example 2:
\n\n\nInput: queries = [2,4,6], intLength = 4\nOutput: [1111,1331,1551]\nExplanation:\nThe first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.\n\n\n
\n
Constraints:
\n\n1 <= queries.length <= 5 * 104
1 <= queries[i] <= 109
1 <= intLength <= 15
There are n
piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.
In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.
\n\nGiven a list piles
, where piles[i]
is a list of integers denoting the composition of the ith
pile from top to bottom, and a positive integer k
, return the maximum total value of coins you can have in your wallet if you choose exactly k
coins optimally.
\n
Example 1:
\n\nInput: piles = [[1,100,3],[7,8,9]], k = 2\nOutput: 101\nExplanation:\nThe above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.\n\n\n
Example 2:
\n\n\nInput: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput: 706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.\n\n\n
\n
Constraints:
\n\nn == piles.length
1 <= n <= 1000
1 <= piles[i][j] <= 105
1 <= k <= sum(piles[i].length) <= 2000
A bit flip of a number x
is choosing a bit in the binary representation of x
and flipping it from either 0
to 1
or 1
to 0
.
x = 7
, the binary representation is 111
and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110
, flip the second bit from the right to get 101
, flip the fifth bit from the right (a leading zero) to get 10111
, etc.Given two integers start
and goal
, return the minimum number of bit flips to convert start
to goal
.
\n
Example 1:
\n\n\nInput: start = 10, goal = 7\nOutput: 3\nExplanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010 -> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right: 1111 -> 0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.\n\n
Example 2:
\n\n\nInput: start = 3, goal = 4\nOutput: 3\nExplanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011 -> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right: 000 -> 100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.\n\n\n
\n
Constraints:
\n\n0 <= start, goal <= 109
\n
Note: This question is the same as 461: Hamming Distance.
\n", - "likes": 1399, - "dislikes": 32, - "stats": "{\"totalAccepted\": \"274.1K\", \"totalSubmission\": \"313.4K\", \"totalAcceptedRaw\": 274137, \"totalSubmissionRaw\": 313363, \"acRate\": \"87.5%\"}", + "likes": 1449, + "dislikes": 33, + "stats": "{\"totalAccepted\": \"299.4K\", \"totalSubmission\": \"341.9K\", \"totalAcceptedRaw\": 299420, \"totalSubmissionRaw\": 341935, \"acRate\": \"87.6%\"}", "similarQuestions": "[{\"title\": \"Minimum Flips to Make a OR b Equal to c\", \"titleSlug\": \"minimum-flips-to-make-a-or-b-equal-to-c\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Number of Operations to Make Array XOR Equal to K\", \"titleSlug\": \"minimum-number-of-operations-to-make-array-xor-equal-to-k\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Smallest Number With All Set Bits\", \"titleSlug\": \"smallest-number-with-all-set-bits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -83834,9 +83993,9 @@ "questionFrontendId": "2221", "title": "Find Triangular Sum of an Array", "content": "You are given a 0-indexed integer array nums
, where nums[i]
is a digit between 0
and 9
(inclusive).
The triangular sum of nums
is the value of the only element present in nums
after the following process terminates:
nums
comprise of n
elements. If n == 1
, end the process. Otherwise, create a new 0-indexed integer array newNums
of length n - 1
.i
, where 0 <= i < n - 1
, assign the value of newNums[i]
as (nums[i] + nums[i+1]) % 10
, where %
denotes modulo operator.nums
with newNums
.Return the triangular sum of nums
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,5]\nOutput: 8\nExplanation:\nThe above diagram depicts the process from which we obtain the triangular sum of the array.\n\n
Example 2:
\n\n\nInput: nums = [5]\nOutput: 5\nExplanation:\nSince there is only one element in nums, the triangular sum is the value of that element itself.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] <= 9
You are given a 0-indexed binary string s
which represents the types of buildings along a street where:
s[i] = '0'
denotes that the ith
building is an office ands[i] = '1'
denotes that the ith
building is a restaurant.As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.
\n\ns = "001101"
, we cannot select the 1st
, 3rd
, and 5th
buildings as that would form "011"
which is not allowed due to having two consecutive buildings of the same type.Return the number of valid ways to select 3 buildings.
\n\n\n
Example 1:
\n\n\nInput: s = "001101"\nOutput: 6\nExplanation: \nThe following sets of indices selected are valid:\n- [0,2,4] from "001101" forms "010"\n- [0,3,4] from "001101" forms "010"\n- [1,2,4] from "001101" forms "010"\n- [1,3,4] from "001101" forms "010"\n- [2,4,5] from "001101" forms "101"\n- [3,4,5] from "001101" forms "101"\nNo other selection is valid. Thus, there are 6 total ways.\n\n\n
Example 2:
\n\n\nInput: s = "11100"\nOutput: 0\nExplanation: It can be shown that there are no valid selections.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 105
s[i]
is either '0'
or '1'
.You are building a string s
of length n
one character at a time, prepending each new character to the front of the string. The strings are labeled from 1
to n
, where the string with length i
is labeled si
.
s = "abaca"
, s1 == "a"
, s2 == "ca"
, s3 == "aca"
, etc.The score of si
is the length of the longest common prefix between si
and sn
(Note that s == sn
).
Given the final string s
, return the sum of the score of every si
.
\n
Example 1:
\n\n\nInput: s = "babab"\nOutput: 9\nExplanation:\nFor s1 == "b", the longest common prefix is "b" which has a score of 1.\nFor s2 == "ab", there is no common prefix so the score is 0.\nFor s3 == "bab", the longest common prefix is "bab" which has a score of 3.\nFor s4 == "abab", there is no common prefix so the score is 0.\nFor s5 == "babab", the longest common prefix is "babab" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.\n\n
Example 2:
\n\n\nInput: s = "azbazbzaz"\nOutput: 14\nExplanation: \nFor s2 == "az", the longest common prefix is "az" which has a score of 2.\nFor s6 == "azbzaz", the longest common prefix is "azb" which has a score of 3.\nFor s9 == "azbazbzaz", the longest common prefix is "azbazbzaz" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.You are given two strings current
and correct
representing two 24-hour times.
24-hour times are formatted as "HH:MM"
, where HH
is between 00
and 23
, and MM
is between 00
and 59
. The earliest 24-hour time is 00:00
, and the latest is 23:59
.
In one operation you can increase the time current
by 1
, 5
, 15
, or 60
minutes. You can perform this operation any number of times.
Return the minimum number of operations needed to convert current
to correct
.
\n
Example 1:
\n\n\nInput: current = "02:30", correct = "04:35"\nOutput: 3\nExplanation:\nWe can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes "03:30".\n- Add 60 minutes to current. current becomes "04:30".\n- Add 5 minutes to current. current becomes "04:35".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.\n\n
Example 2:
\n\n\nInput: current = "11:00", correct = "11:01"\nOutput: 1\nExplanation: We only have to add one minute to current, so the minimum number of operations needed is 1.\n\n\n
\n
Constraints:
\n\ncurrent
and correct
are in the format "HH:MM"
current <= correct
You are given an integer array matches
where matches[i] = [winneri, loseri]
indicates that the player winneri
defeated player loseri
in a match.
Return a list answer
of size 2
where:
answer[0]
is a list of all players that have not lost any matches.answer[1]
is a list of all players that have lost exactly one match.The values in the two lists should be returned in increasing order.
\n\nNote:
\n\n\n
Example 1:
\n\n\nInput: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\nOutput: [[1,2,10],[4,5,7,8]]\nExplanation:\nPlayers 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].\n\n\n
Example 2:
\n\n\nInput: matches = [[2,3],[1,3],[5,4],[6,4]]\nOutput: [[1,2,5,6],[]]\nExplanation:\nPlayers 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].\n\n\n
\n
Constraints:
\n\n1 <= matches.length <= 105
matches[i].length == 2
1 <= winneri, loseri <= 105
winneri != loseri
matches[i]
are unique.You are given a 0-indexed integer array candies
. Each element in the array denotes a pile of candies of size candies[i]
. You can divide each pile into any number of sub piles, but you cannot merge two piles together.
You are also given an integer k
. You should allocate piles of candies to k
children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.
Return the maximum number of candies each child can get.
\n\n
Example 1:
\n\n\nInput: candies = [5,8,6], k = 3\nOutput: 5\nExplanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.\n\n\n
Example 2:
\n\n\nInput: candies = [2,5], k = 11\nOutput: 0\nExplanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.\n\n\n
\n
Constraints:
\n\n1 <= candies.length <= 105
1 <= candies[i] <= 107
1 <= k <= 1012
You are given a 0-indexed integer array candies
. Each element in the array denotes a pile of candies of size candies[i]
. You can divide each pile into any number of sub piles, but you cannot merge two piles together.
You are also given an integer k
. You should allocate piles of candies to k
children such that each child gets the same number of candies. Each child can be allocated candies from only one pile of candies and some piles of candies may go unused.
Return the maximum number of candies each child can get.
\n\n\n
Example 1:
\n\n\nInput: candies = [5,8,6], k = 3\nOutput: 5\nExplanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.\n\n\n
Example 2:
\n\n\nInput: candies = [2,5], k = 11\nOutput: 0\nExplanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.\n\n\n
\n
Constraints:
\n\n1 <= candies.length <= 105
1 <= candies[i] <= 107
1 <= k <= 1012
You are given a character array keys
containing unique characters and a string array values
containing strings of length 2. You are also given another string array dictionary
that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.
A string is encrypted with the following process:
\n\nc
in the string, we find the index i
satisfying keys[i] == c
in keys
.c
with values[i]
in the string.Note that in case a character of the string is not present in keys
, the encryption process cannot be carried out, and an empty string ""
is returned.
A string is decrypted with the following process:
\n\ns
of length 2 occurring at an even index in the string, we find an i
such that values[i] == s
. If there are multiple valid i
, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.s
with keys[i]
in the string.Implement the Encrypter
class:
Encrypter(char[] keys, String[] values, String[] dictionary)
Initializes the Encrypter
class with keys, values
, and dictionary
.String encrypt(String word1)
Encrypts word1
with the encryption process described above and returns the encrypted string.int decrypt(String word2)
Returns the number of possible strings word2
could decrypt to that also appear in dictionary
.\n
Example 1:
\n\n\nInput\n["Encrypter", "encrypt", "decrypt"]\n[[['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]], ["abcd"], ["eizfeiam"]]\nOutput\n[null, "eizfeiam", 2]\n\nExplanation\nEncrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], ["ei", "zf", "ei", "am"], ["abcd", "acbd", "adbc", "badc", "dacb", "cadb", "cbda", "abad"]);\nencrypter.encrypt("abcd"); // return "eizfeiam". \n // 'a' maps to "ei", 'b' maps to "zf", 'c' maps to "ei", and 'd' maps to "am".\nencrypter.decrypt("eizfeiam"); // return 2. \n // "ei" can map to 'a' or 'c', "zf" maps to 'b', and "am" maps to 'd'. \n // Thus, the possible strings after decryption are "abad", "cbad", "abcd", and "cbcd". \n // 2 of those strings, "abad" and "abcd", appear in dictionary, so the answer is 2.\n\n\n
\n
Constraints:
\n\n1 <= keys.length == values.length <= 26
values[i].length == 2
1 <= dictionary.length <= 100
1 <= dictionary[i].length <= 100
keys[i]
and dictionary[i]
are unique.1 <= word1.length <= 2000
2 <= word2.length <= 200
word1[i]
appear in keys
.word2.length
is even.keys
, values[i]
, dictionary[i]
, word1
, and word2
only contain lowercase English letters.200
calls will be made to encrypt
and decrypt
in total.You are given a positive integer num
. You may swap any two digits of num
that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num
after any number of swaps.
\n
Example 1:
\n\n\nInput: num = 1234\nOutput: 3412\nExplanation: Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.\n\n\n
Example 2:
\n\n\nInput: num = 65875\nOutput: 87655\nExplanation: Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.\n\n\n
\n
Constraints:
\n\n1 <= num <= 109
You are given a 0-indexed string expression
of the form "<num1>+<num2>"
where <num1>
and <num2>
represent positive integers.
Add a pair of parentheses to expression
such that after the addition of parentheses, expression
is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+'
and the right parenthesis must be added to the right of '+'
.
Return expression
after adding a pair of parentheses such that expression
evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.
The input has been generated such that the original value of expression
, and the value of expression
after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.
\n
Example 1:
\n\n\nInput: expression = "247+38"\nOutput: "2(47+38)"\nExplanation: The\n\nexpression
evaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that "2(4)7+38" is invalid because the right parenthesis must be to the right of the'+'
.\nIt can be shown that 170 is the smallest possible value.\n
Example 2:
\n\n\nInput: expression = "12+34"\nOutput: "1(2+3)4"\nExplanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.\n\n\n
Example 3:
\n\n\nInput: expression = "999+999"\nOutput: "(999+999)"\nExplanation: The expression
evaluates to 999 + 999 = 1998.\n
\n\n\n
Constraints:
\n\n3 <= expression.length <= 10
expression
consists of digits from '1'
to '9'
and '+'
.expression
starts and ends with digits.expression
contains exactly one '+'
.expression
, and the value of expression
after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.You are given an array of non-negative integers nums
and an integer k
. In one operation, you may choose any element from nums
and increment it by 1
.
Return the maximum product of nums
after at most k
operations. Since the answer may be very large, return it modulo 109 + 7
. Note that you should maximize the product before taking the modulo.
\n
Example 1:
\n\n\nInput: nums = [0,4], k = 5\nOutput: 20\nExplanation: Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\n
Example 2:
\n\n\nInput: nums = [6,3,3,2], k = 2\nOutput: 216\nExplanation: Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.\n\n\n
\n
Constraints:
\n\n1 <= nums.length, k <= 105
0 <= nums[i] <= 106
Alice is a caretaker of n
gardens and she wants to plant flowers to maximize the total beauty of all her gardens.
You are given a 0-indexed integer array flowers
of size n
, where flowers[i]
is the number of flowers already planted in the ith
garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers
, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target
, full
, and partial
.
A garden is considered complete if it has at least target
flowers. The total beauty of the gardens is then determined as the sum of the following:
full
.partial
. If there are no incomplete gardens, then this value will be 0
.Return the maximum total beauty that Alice can obtain after planting at most newFlowers
flowers.
\n
Example 1:
\n\n\nInput: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1\nOutput: 14\nExplanation: Alice can plant\n- 2 flowers in the 0th garden\n- 3 flowers in the 1st garden\n- 1 flower in the 2nd garden\n- 1 flower in the 3rd garden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.\n\n\n
Example 2:
\n\n\nInput: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6\nOutput: 30\nExplanation: Alice can plant\n- 3 flowers in the 0th garden\n- 0 flowers in the 1st garden\n- 0 flowers in the 2nd garden\n- 2 flowers in the 3rd garden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.\n\n\n
\n
Constraints:
\n\n1 <= flowers.length <= 105
1 <= flowers[i], target <= 105
1 <= newFlowers <= 1010
1 <= full, partial <= 105
num1
and num2
, return the sum of the two integers.\n\n
Example 1:
\n\n\nInput: num1 = 12, num2 = 5\nOutput: 17\nExplanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.\n\n\n
Example 2:
\n\n\nInput: num1 = -10, num2 = 4\nOutput: -6\nExplanation: num1 + num2 = -6, so -6 is returned.\n\n\n
\n
Constraints:
\n\n-100 <= num1, num2 <= 100
You are given the root
of a binary tree that consists of exactly 3
nodes: the root, its left child, and its right child.
Return true
if the value of the root is equal to the sum of the values of its two children, or false
otherwise.
\n
Example 1:
\n\nInput: root = [10,4,6]\nOutput: true\nExplanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.\n\n\n
Example 2:
\n\nInput: root = [5,3,1]\nOutput: false\nExplanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.\n\n\n
\n
Constraints:
\n\n-100 <= Node.val <= 100
Given an integer array nums
of size n
, return the number with the value closest to 0
in nums
. If there are multiple answers, return the number with the largest value.
\n
Example 1:
\n\n\nInput: nums = [-4,-2,1,4,8]\nOutput: 1\nExplanation:\nThe distance from -4 to 0 is |-4| = 4.\nThe distance from -2 to 0 is |-2| = 2.\nThe distance from 1 to 0 is |1| = 1.\nThe distance from 4 to 0 is |4| = 4.\nThe distance from 8 to 0 is |8| = 8.\nThus, the closest number to 0 in the array is 1.\n\n\n
Example 2:
\n\n\nInput: nums = [2,-1,1]\nOutput: 1\nExplanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
-105 <= nums[i] <= 105
You are given an integer total
indicating the amount of money you have. You are also given two integers cost1
and cost2
indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil.
Return the number of distinct ways you can buy some number of pens and pencils.
\n\n\n
Example 1:
\n\n\nInput: total = 20, cost1 = 10, cost2 = 5\nOutput: 9\nExplanation: The price of a pen is 10 and the price of a pencil is 5.\n- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.\n- If you buy 1 pen, you can buy 0, 1, or 2 pencils.\n- If you buy 2 pens, you cannot buy any pencils.\nThe total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.\n\n\n
Example 2:
\n\n\nInput: total = 5, cost1 = 10, cost2 = 10\nOutput: 1\nExplanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.\n\n\n
\n
Constraints:
\n\n1 <= total, cost1, cost2 <= 106
There is an ATM machine that stores banknotes of 5
denominations: 20
, 50
, 100
, 200
, and 500
dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.
When withdrawing, the machine prioritizes using banknotes of larger values.
\n\n$300
and there are 2
$50
banknotes, 1
$100
banknote, and 1
$200
banknote, then the machine will use the $100
and $200
banknotes.$600
and there are 3
$200
banknotes and 1
$500
banknote, then the withdraw request will be rejected because the machine will first try to use the $500
banknote and then be unable to use banknotes to complete the remaining $100
. Note that the machine is not allowed to use the $200
banknotes instead of the $500
banknote.Implement the ATM class:
\n\nATM()
Initializes the ATM object.void deposit(int[] banknotesCount)
Deposits new banknotes in the order $20
, $50
, $100
, $200
, and $500
.int[] withdraw(int amount)
Returns an array of length 5
of the number of banknotes that will be handed to the user in the order $20
, $50
, $100
, $200
, and $500
, and update the number of banknotes in the ATM after withdrawing. Returns [-1]
if it is not possible (do not withdraw any banknotes in this case).\n
Example 1:
\n\n\nInput\n["ATM", "deposit", "withdraw", "deposit", "withdraw", "withdraw"]\n[[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]\nOutput\n[null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]\n\nExplanation\nATM atm = new ATM();\natm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n // and 1 $500 banknote.\natm.withdraw(600); // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n // and 1 $500 banknote. The banknotes left over in the\n // machine are [0,0,0,2,0].\natm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n // The banknotes in the machine are now [0,1,0,3,1].\natm.withdraw(600); // Returns [-1]. The machine will try to use a $500 banknote\n // and then be unable to complete the remaining $100,\n // so the withdraw request will be rejected.\n // Since the request is rejected, the number of banknotes\n // in the machine is not modified.\natm.withdraw(550); // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n // and 1 $500 banknote.\n\n
\n
Constraints:
\n\nbanknotesCount.length == 5
0 <= banknotesCount[i] <= 109
1 <= amount <= 109
5000
calls in total will be made to withdraw
and deposit
.withdraw
and deposit
.banknotesCount[i]
in all deposits doesn't exceed 109
There is an undirected graph with n
nodes, numbered from 0
to n - 1
.
You are given a 0-indexed integer array scores
of length n
where scores[i]
denotes the score of node i
. You are also given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
A node sequence is valid if it meets the following conditions:
\n\nThe score of a node sequence is defined as the sum of the scores of the nodes in the sequence.
\n\nReturn the maximum score of a valid node sequence with a length of 4
. If no such sequence exists, return -1
.
\n
Example 1:
\n\nInput: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput: 24\nExplanation: The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.\n\n\n
Example 2:
\n\nInput: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]\nOutput: -1\nExplanation: The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.\n\n\n
\n
Constraints:
\n\nn == scores.length
4 <= n <= 5 * 104
1 <= scores[i] <= 108
0 <= edges.length <= 5 * 104
edges[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
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:
s
into consecutive groups of size k
such that the first k
characters are in the first group, the next k
characters are in the second group, and so on. Note that the size of the last group can be smaller than k
.s
with a string representing the sum of all its digits. For example, "346"
is replaced with "13"
because 3 + 4 + 6 = 13
.k
, repeat from step 1
.Return s
after all rounds have been completed.
\n
Example 1:
\n\n\nInput: s = "11111222223", k = 3\nOutput: "135"\nExplanation: \n- For the first round, we divide s into groups of size 3: "111", "112", "222", and "23".\n \u200b\u200b\u200b\u200b\u200bThen we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n So, s becomes "3" + "4" + "6" + "5" = "3465" after the first round.\n- For the second round, we divide s into "346" and "5".\n Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n So, s becomes "13" + "5" = "135" after second round. \nNow, s.length <= k, so we return "135" as the answer.\n\n\n
Example 2:
\n\n\nInput: s = "00000000", k = 3\nOutput: "000"\nExplanation: \nWe divide s into "000", "000", and "00".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes "0" + "0" + "0" = "000", whose length is equal to k, so we return "000".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
2 <= k <= 100
s
consists of digits only.You are given a 0-indexed integer array tasks
, where tasks[i]
represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.
Return the minimum rounds required to complete all the tasks, or -1
if it is not possible to complete all the tasks.
\n
Example 1:
\n\n\nInput: tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput: 4\nExplanation: To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4. \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.\n\n\n
Example 2:
\n\n\nInput: tasks = [2,3,3]\nOutput: -1\nExplanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= tasks.length <= 105
1 <= tasks[i] <= 109
\n
Note: This question is the same as 2870: Minimum Number of Operations to Make Array Empty.
\n", - "likes": 2801, + "likes": 2815, "dislikes": 83, - "stats": "{\"totalAccepted\": \"158.1K\", \"totalSubmission\": \"251.4K\", \"totalAcceptedRaw\": 158128, \"totalSubmissionRaw\": 251386, \"acRate\": \"62.9%\"}", + "stats": "{\"totalAccepted\": \"162.2K\", \"totalSubmission\": \"257.7K\", \"totalAcceptedRaw\": 162204, \"totalSubmissionRaw\": 257686, \"acRate\": \"62.9%\"}", "similarQuestions": "[{\"title\": \"Climbing Stairs\", \"titleSlug\": \"climbing-stairs\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Odd String Difference\", \"titleSlug\": \"odd-string-difference\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Levels to Gain More Points\", \"titleSlug\": \"minimum-levels-to-gain-more-points\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -84699,9 +84867,9 @@ "questionFrontendId": "2245", "title": "Maximum Trailing Zeros in a Cornered Path", "content": "You are given a 2D integer array grid
of size m x n
, where each cell contains a positive integer.
A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.
\n\nThe product of a path is defined as the product of all the values in the path.
\n\nReturn the maximum number of trailing zeros in the product of a cornered path found in grid
.
Note:
\n\n\n
Example 1:
\n\nInput: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput: 3\nExplanation: The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.\n\n\n
Example 2:
\n\nInput: grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput: 0\nExplanation: The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= grid[i][j] <= 1000
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0
consisting of n
nodes numbered from 0
to n - 1
. The tree is represented by a 0-indexed array parent
of size n
, where parent[i]
is the parent of node i
. Since node 0
is the root, parent[0] == -1
.
You are also given a string s
of length n
, where s[i]
is the character assigned to node i
.
Return the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.
\n\n\n
Example 1:
\n\nInput: parent = [-1,0,0,1,1,2], s = "abacbe"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions. \n\n\n
Example 2:
\n\nInput: parent = [-1,0,0,0], s = "aabc"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.\n\n\n
\n
Constraints:
\n\nn == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1
for all i >= 1
parent[0] == -1
parent
represents a valid tree.s
consists of only lowercase English letters.nums
where nums[i]
is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums
sorted in ascending order.\n\n
Example 1:
\n\n\nInput: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\nOutput: [3,4]\nExplanation: \nThe only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].\n\n
Example 2:
\n\n\nInput: nums = [[1,2,3],[4,5,6]]\nOutput: []\nExplanation: \nThere does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= sum(nums[i].length) <= 1000
1 <= nums[i][j] <= 1000
nums[i]
are unique.Given a 2D integer array circles
where circles[i] = [xi, yi, ri]
represents the center (xi, yi)
and radius ri
of the ith
circle drawn on a grid, return the number of lattice points that are present inside at least one circle.
Note:
\n\n\n
Example 1:
\n\nInput: circles = [[2,2,1]]\nOutput: 5\nExplanation:\nThe figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.\n\n
Example 2:
\n\nInput: circles = [[2,2,2],[3,4,1]]\nOutput: 16\nExplanation:\nThe figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).\n\n\n
\n
Constraints:
\n\n1 <= circles.length <= 200
circles[i].length == 3
1 <= xi, yi <= 100
1 <= ri <= min(xi, yi)
You are given a 2D integer array rectangles
where rectangles[i] = [li, hi]
indicates that ith
rectangle has a length of li
and a height of hi
. You are also given a 2D integer array points
where points[j] = [xj, yj]
is a point with coordinates (xj, yj)
.
The ith
rectangle has its bottom-left corner point at the coordinates (0, 0)
and its top-right corner point at (li, hi)
.
Return an integer array count
of length points.length
where count[j]
is the number of rectangles that contain the jth
point.
The ith
rectangle contains the jth
point if 0 <= xj <= li
and 0 <= yj <= hi
. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.
\n
Example 1:
\n\nInput: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\nOutput: [2,1]\nExplanation: \nThe first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].\n\n\n
Example 2:
\n\nInput: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\nOutput: [1,3]\nExplanation:\nThe first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].\n\n\n
\n
Constraints:
\n\n1 <= rectangles.length, points.length <= 5 * 104
rectangles[i].length == points[j].length == 2
1 <= li, xj <= 109
1 <= hi, yj <= 100
rectangles
are unique.points
are unique.You are given a 0-indexed 2D integer array flowers
, where flowers[i] = [starti, endi]
means the ith
flower will be in full bloom from starti
to endi
(inclusive). You are also given a 0-indexed integer array people
of size n
, where people[i]
is the time that the ith
person will arrive to see the flowers.
Return an integer array answer
of size n
, where answer[i]
is the number of flowers that are in full bloom when the ith
person arrives.
\n
Example 1:
\n\nInput: flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]\nOutput: [1,2,2,2]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\n
Example 2:
\n\nInput: flowers = [[1,10],[3,3]], people = [3,3,2]\nOutput: [2,2,1]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n\n\n
\n
Constraints:
\n\n1 <= flowers.length <= 5 * 104
flowers[i].length == 2
1 <= starti <= endi <= 109
1 <= people.length <= 5 * 104
1 <= people[i] <= 109
You are given a string array words
and a string s
, where words[i]
and s
comprise only of lowercase English letters.
Return the number of strings in words
that are a prefix of s
.
A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: words = ["a","b","c","ab","bc","abc"], s = "abc"\nOutput: 3\nExplanation:\nThe strings in words which are a prefix of s = "abc" are:\n"a", "ab", and "abc".\nThus the number of strings in words which are a prefix of s is 3.\n\n
Example 2:
\n\n\nInput: words = ["a","a"], s = "aa"\nOutput: 2\nExplanation:\nBoth of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length, s.length <= 10
words[i]
and s
consist of lowercase English letters only.You are given a 0-indexed integer array nums
of length n
.
The average difference of the index i
is the absolute difference between the average of the first i + 1
elements of nums
and the average of the last n - i - 1
elements. Both averages should be rounded down to the nearest integer.
Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.
\n\nNote:
\n\nn
elements is the sum of the n
elements divided (integer division) by n
.0
elements is considered to be 0
.\n
Example 1:
\n\n\nInput: nums = [2,5,3,9,5,3]\nOutput: 3\nExplanation:\n- The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n- The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n- The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n- The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n- The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n- The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\nThe average difference of index 3 is the minimum average difference so return 3.\n\n\n
Example 2:
\n\n\nInput: nums = [0]\nOutput: 0\nExplanation:\nThe only index is 0 so return 0.\nThe average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
You are given two integers m
and n
representing a 0-indexed m x n
grid. You are also given two 2D integer arrays guards
and walls
where guards[i] = [rowi, coli]
and walls[j] = [rowj, colj]
represent the positions of the ith
guard and jth
wall respectively.
A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.
\n\nReturn the number of unoccupied cells that are not guarded.
\n\n\n
Example 1:
\n\nInput: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\nOutput: 7\nExplanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.\n\n\n
Example 2:
\n\nInput: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\nOutput: 4\nExplanation: The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.\n\n\n
\n
Constraints:
\n\n1 <= m, n <= 105
2 <= m * n <= 105
1 <= guards.length, walls.length <= 5 * 104
2 <= guards.length + walls.length <= m * n
guards[i].length == walls[j].length == 2
0 <= rowi, rowj < m
0 <= coli, colj < n
guards
and walls
are unique.You are given a 0-indexed 2D integer array grid
of size m x n
which represents a field. Each cell has one of three values:
0
represents grass,1
represents fire,2
represents a wall that you and fire cannot pass through.You are situated in the top-left cell, (0, 0)
, and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1)
. Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.
Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1
. If you can always reach the safehouse regardless of the minutes stayed, return 109
.
Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.
\n\nA cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
\n\n\n
Example 1:
\n\nInput: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput: 3\nExplanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.\n\n
Example 2:
\n\nInput: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput: -1\nExplanation: The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.\n\n\n
Example 3:
\n\nInput: grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput: 1000000000\nExplanation: The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109 is returned.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 300
4 <= m * n <= 2 * 104
grid[i][j]
is either 0
, 1
, or 2
.grid[0][0] == grid[m - 1][n - 1] == 0
You are given a string number
representing a positive integer and a character digit
.
Return the resulting string after removing exactly one occurrence of digit
from number
such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit
occurs at least once in number
.
\n
Example 1:
\n\n\nInput: number = "123", digit = "3"\nOutput: "12"\nExplanation: There is only one '3' in "123". After removing '3', the result is "12".\n\n\n
Example 2:
\n\n\nInput: number = "1231", digit = "1"\nOutput: "231"\nExplanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".\nSince 231 > 123, we return "231".\n\n\n
Example 3:
\n\n\nInput: number = "551", digit = "5"\nOutput: "51"\nExplanation: We can remove either the first or second '5' from "551".\nBoth result in the string "51".\n\n\n
\n
Constraints:
\n\n2 <= number.length <= 100
number
consists of digits from '1'
to '9'
.digit
is a digit from '1'
to '9'
.digit
occurs at least once in number
.You are given an integer array cards
where cards[i]
represents the value of the ith
card. A pair of cards are matching if the cards have the same value.
Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1
.
\n
Example 1:
\n\n\nInput: cards = [3,4,2,3,4,7]\nOutput: 4\nExplanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.\n\n\n
Example 2:
\n\n\nInput: cards = [1,0,5,3]\nOutput: -1\nExplanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.\n\n\n
\n
Constraints:
\n\n1 <= cards.length <= 105
0 <= cards[i] <= 106
Given an integer array nums
and two integers k
and p
, return the number of distinct subarrays, which have at most k
elements that are divisible by p
.
Two arrays nums1
and nums2
are said to be distinct if:
i
where nums1[i] != nums2[i]
.A subarray is defined as a non-empty contiguous sequence of elements in an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,3,2,2], k = 2, p = 2\nOutput: 11\nExplanation:\nThe elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4], k = 4, p = 1\nOutput: 10\nExplanation:\nAll element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i], p <= 200
1 <= k <= nums.length
\n
Follow up:
\n\nCan you solve this problem in O(n2) time complexity?
\n", - "likes": 701, - "dislikes": 158, - "stats": "{\"totalAccepted\": \"39.9K\", \"totalSubmission\": \"75.2K\", \"totalAcceptedRaw\": 39897, \"totalSubmissionRaw\": 75168, \"acRate\": \"53.1%\"}", + "likes": 714, + "dislikes": 159, + "stats": "{\"totalAccepted\": \"43.6K\", \"totalSubmission\": \"81K\", \"totalAcceptedRaw\": 43576, \"totalSubmissionRaw\": 80956, \"acRate\": \"53.8%\"}", "similarQuestions": "[{\"title\": \"Subarrays with K Different Integers\", \"titleSlug\": \"subarrays-with-k-different-integers\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Count Number of Nice Subarrays\", \"titleSlug\": \"count-number-of-nice-subarrays\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Subarray With Elements Greater Than Varying Threshold\", \"titleSlug\": \"subarray-with-elements-greater-than-varying-threshold\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -85372,9 +85543,9 @@ "questionFrontendId": "2262", "title": "Total Appeal of A String", "content": "The appeal of a string is the number of distinct characters found in the string.
\n\n"abbca"
is 3
because it has 3
distinct characters: 'a'
, 'b'
, and 'c'
.Given a string s
, return the total appeal of all of its substrings.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "abbca"\nOutput: 28\nExplanation: The following are the substrings of "abbca":\n- Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: "abbca" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.\n\n\n
Example 2:
\n\n\nInput: s = "code"\nOutput: 20\nExplanation: The following are the substrings of "code":\n- Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: "code" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.You are given a string num
representing a large integer. An integer is good if it meets the following conditions:
num
with length 3
.Return the maximum good integer as a string or an empty string ""
if no such integer exists.
Note:
\n\nnum
or a good integer.\n
Example 1:
\n\n\nInput: num = "6777133339"\nOutput: "777"\nExplanation: There are two distinct good integers: "777" and "333".\n"777" is the largest, so we return "777".\n\n\n
Example 2:
\n\n\nInput: num = "2300019"\nOutput: "000"\nExplanation: "000" is the only good integer.\n\n\n
Example 3:
\n\n\nInput: num = "42352338"\nOutput: ""\nExplanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.\n\n\n
\n
Constraints:
\n\n3 <= num.length <= 1000
num
only consists of digits.Given the root
of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.
Note:
\n\nn
elements is the sum of the n
elements divided by n
and rounded down to the nearest integer.root
is a tree consisting of root
and all of its descendants.\n
Example 1:
\n\nInput: root = [4,8,5,0,1,null,6]\nOutput: 5\nExplanation: \nFor the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.\n\n\n
Example 2:
\n\nInput: root = [1]\nOutput: 1\nExplanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.\n\n\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 1000
Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.
\nIn order to add a letter, Alice has to press the key of the corresponding digit i
times, where i
is the position of the letter in the key.
's'
, Alice has to press '7'
four times. Similarly, to add the letter 'k'
, Alice has to press '5'
twice.'0'
and '1'
do not map to any letters, so Alice does not use them.However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.
\n\n"bob"
, Bob received the string "2266622"
.Given a string pressedKeys
representing the string received by Bob, return the total number of possible text messages Alice could have sent.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: pressedKeys = "22233"\nOutput: 8\nExplanation:\nThe possible text messages Alice could have sent are:\n"aaadd", "abdd", "badd", "cdd", "aaae", "abe", "bae", and "ce".\nSince there are 8 possible messages, we return 8.\n\n\n
Example 2:
\n\n\nInput: pressedKeys = "222222222222222222222222222222222222"\nOutput: 82876089\nExplanation:\nThere are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n\n\n
\n
Constraints:
\n\n1 <= pressedKeys.length <= 105
pressedKeys
only consists of digits from '2'
- '9'
.A parentheses string is a non-empty string consisting only of '('
and ')'
. It is valid if any of the following conditions is true:
()
.AB
(A
concatenated with B
), where A
and B
are valid parentheses strings.(A)
, where A
is a valid parentheses string.You are given an m x n
matrix of parentheses grid
. A valid parentheses string path in the grid is a path satisfying all of the following conditions:
(0, 0)
.(m - 1, n - 1)
.Return true
if there exists a valid parentheses string path in the grid. Otherwise, return false
.
\n
Example 1:
\n\nInput: grid = [["(","(","("],[")","(",")"],["(","(",")"],["(","(",")"]]\nOutput: true\nExplanation: The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string "()(())".\nThe second path shown results in the valid parentheses string "((()))".\nNote that there may be other valid parentheses string paths.\n\n\n
Example 2:
\n\nInput: grid = [[")",")"],["(","("]]\nOutput: false\nExplanation: The two possible paths form the parentheses strings "))(" and ")((". Since neither of them are valid parentheses strings, we return false.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 100
grid[i][j]
is either '('
or ')'
.The k-beauty of an integer num
is defined as the number of substrings of num
when it is read as a string that meet the following conditions:
k
.num
.Given integers num
and k
, return the k-beauty of num
.
Note:
\n\n0
is not a divisor of any value.A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: num = 240, k = 2\nOutput: 2\nExplanation: The following are the substrings of num of length k:\n- "24" from "240": 24 is a divisor of 240.\n- "40" from "240": 40 is a divisor of 240.\nTherefore, the k-beauty is 2.\n\n\n
Example 2:
\n\n\nInput: num = 430043, k = 2\nOutput: 2\nExplanation: The following are the substrings of num of length k:\n- "43" from "430043": 43 is a divisor of 430043.\n- "30" from "430043": 30 is not a divisor of 430043.\n- "00" from "430043": 0 is not a divisor of 430043.\n- "04" from "430043": 4 is not a divisor of 430043.\n- "43" from "430043": 43 is a divisor of 430043.\nTherefore, the k-beauty is 2.\n\n\n
\n
Constraints:
\n\n1 <= num <= 109
1 <= k <= num.length
(taking num
as a string)You are given a 0-indexed integer array nums
of length n
.
nums
contains a valid split at index i
if the following are true:
i + 1
elements is greater than or equal to the sum of the last n - i - 1
elements.i
. That is, 0 <= i < n - 1
.Return the number of valid splits in nums
.
\n
Example 1:
\n\n\nInput: nums = [10,4,-8,7]\nOutput: 2\nExplanation: \nThere are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,1,0]\nOutput: 2\nExplanation: \nThere are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
-105 <= nums[i] <= 105
You are given a 2D integer array tiles
where tiles[i] = [li, ri]
represents that every tile j
in the range li <= j <= ri
is colored white.
You are also given an integer carpetLen
, the length of a single carpet that can be placed anywhere.
Return the maximum number of white tiles that can be covered by the carpet.
\n\n\n
Example 1:
\n\nInput: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\nOutput: 9\nExplanation: Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.\n\n\n
Example 2:
\n\nInput: tiles = [[10,11],[1,1]], carpetLen = 2\nOutput: 2\nExplanation: Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.\n\n\n
\n
Constraints:
\n\n1 <= tiles.length <= 5 * 104
tiles[i].length == 2
1 <= li <= ri <= 109
1 <= carpetLen <= 109
tiles
are non-overlapping.The variance of a string is defined as the largest difference between the number of occurrences of any 2
characters present in the string. Note the two characters may or may not be the same.
Given a string s
consisting of lowercase English letters only, return the largest variance possible among all substrings of s
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "aababbb"\nOutput: 3\nExplanation:\nAll possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb".\n- Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab".\n- Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb".\n- Variance 3 for substring "babbb".\nSince the largest possible variance is 3, we return it.\n\n\n
Example 2:
\n\n\nInput: s = "abcde"\nOutput: 0\nExplanation:\nNo letter occurs more than once in s, so the variance of every substring is 0.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of lowercase English letters.You are given a 0-indexed string array words
, where words[i]
consists of lowercase English letters.
In one operation, select any index i
such that 0 < i < words.length
and words[i - 1]
and words[i]
are anagrams, and delete words[i]
from words
. Keep performing this operation as long as you can select an index that satisfies the conditions.
Return words
after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb"
is an anagram of "abdc"
.
\n
Example 1:
\n\n\nInput: words = ["abba","baba","bbaa","cd","cd"]\nOutput: ["abba","cd"]\nExplanation:\nOne of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = "bbaa" and words[1] = "baba" are anagrams, we choose index 2 and delete words[2].\n Now words = ["abba","baba","cd","cd"].\n- Since words[1] = "baba" and words[0] = "abba" are anagrams, we choose index 1 and delete words[1].\n Now words = ["abba","cd","cd"].\n- Since words[2] = "cd" and words[1] = "cd" are anagrams, we choose index 2 and delete words[2].\n Now words = ["abba","cd"].\nWe can no longer perform any operations, so ["abba","cd"] is the final answer.\n\n
Example 2:
\n\n\nInput: words = ["a","b","c","d","e"]\nOutput: ["a","b","c","d","e"]\nExplanation:\nNo two adjacent strings in words are anagrams of each other, so no operations are performed.\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 10
words[i]
consists of lowercase English letters.Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.
\n\nYou are given two integers bottom
and top
, which denote that Alice has rented all the floors from bottom
to top
(inclusive). You are also given the integer array special
, where special[i]
denotes a special floor that Alice has designated for relaxation.
Return the maximum number of consecutive floors without a special floor.
\n\n\n
Example 1:
\n\n\nInput: bottom = 2, top = 9, special = [4,6]\nOutput: 3\nExplanation: The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.\n\n\n
Example 2:
\n\n\nInput: bottom = 6, top = 8, special = [7,6,8]\nOutput: 0\nExplanation: Every floor rented is a special floor, so we return 0.\n\n\n
\n
Constraints:
\n\n1 <= special.length <= 105
1 <= bottom <= special[i] <= top <= 109
special
are unique.The bitwise AND of an array nums
is the bitwise AND of all integers in nums
.
nums = [1, 5, 3]
, the bitwise AND is equal to 1 & 5 & 3 = 1
.nums = [7]
, the bitwise AND is 7
.You are given an array of positive integers candidates
. Compute the bitwise AND for all possible combinations of elements in the candidates
array.
Return the size of the largest combination of candidates
with a bitwise AND greater than 0
.
\n
Example 1:
\n\n\nInput: candidates = [16,17,71,62,12,24,14]\nOutput: 4\nExplanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.\n\n\n
Example 2:
\n\n\nInput: candidates = [8,8]\nOutput: 2\nExplanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.\n\n\n
\n
Constraints:
\n\n1 <= candidates.length <= 105
1 <= candidates[i] <= 107
Given an empty set of intervals, implement a data structure that can:
\n\nImplement the CountIntervals
class:
CountIntervals()
Initializes the object with an empty set of intervals.void add(int left, int right)
Adds the interval [left, right]
to the set of intervals.int count()
Returns the number of integers that are present in at least one interval.Note that an interval [left, right]
denotes all the integers x
where left <= x <= right
.
\n
Example 1:
\n\n\nInput\n["CountIntervals", "add", "add", "count", "add", "count"]\n[[], [2, 3], [7, 10], [], [5, 8], []]\nOutput\n[null, null, null, 6, null, 8]\n\nExplanation\nCountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \ncountIntervals.add(2, 3); // add [2, 3] to the set of intervals.\ncountIntervals.add(7, 10); // add [7, 10] to the set of intervals.\ncountIntervals.count(); // return 6\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\ncountIntervals.add(5, 8); // add [5, 8] to the set of intervals.\ncountIntervals.count(); // return 8\n // the integers 2 and 3 are present in the interval [2, 3].\n // the integers 5 and 6 are present in the interval [5, 8].\n // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n // the integers 9 and 10 are present in the interval [7, 10].\n\n\n
\n
Constraints:
\n\n1 <= left <= right <= 109
105
calls in total will be made to add
and count
.count
.Given a string s
and a character letter
, return the percentage of characters in s
that equal letter
rounded down to the nearest whole percent.
\n
Example 1:
\n\n\nInput: s = "foobar", letter = "o"\nOutput: 33\nExplanation:\nThe percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.\n\n\n
Example 2:
\n\n\nInput: s = "jjjj", letter = "k"\nOutput: 0\nExplanation:\nThe percentage of characters in s that equal the letter 'k' is 0%, so we return 0.\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters.letter
is a lowercase English letter.You have n
bags numbered from 0
to n - 1
. You are given two 0-indexed integer arrays capacity
and rocks
. The ith
bag can hold a maximum of capacity[i]
rocks and currently contains rocks[i]
rocks. You are also given an integer additionalRocks
, the number of additional rocks you can place in any of the bags.
Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.
\n\n\n
Example 1:
\n\n\nInput: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2\nOutput: 3\nExplanation:\nPlace 1 rock in bag 0 and 1 rock in bag 1.\nThe number of rocks in each bag are now [2,3,4,4].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that there may be other ways of placing the rocks that result in an answer of 3.\n\n\n
Example 2:
\n\n\nInput: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100\nOutput: 3\nExplanation:\nPlace 8 rocks in bag 0 and 2 rocks in bag 2.\nThe number of rocks in each bag are now [10,2,2].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that we did not use all of the additional rocks.\n\n\n
\n
Constraints:
\n\nn == capacity.length == rocks.length
1 <= n <= 5 * 104
1 <= capacity[i] <= 109
0 <= rocks[i] <= capacity[i]
1 <= additionalRocks <= 109
You are given a 2D integer array stockPrices
where stockPrices[i] = [dayi, pricei]
indicates the price of the stock on day dayi
is pricei
. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:
Return the minimum number of lines needed to represent the line chart.
\n\n\n
Example 1:
\n\nInput: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]\nOutput: 3\nExplanation:\nThe diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.\nThe following 3 lines can be drawn to represent the line chart:\n- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).\n- Line 2 (in blue) from (4,4) to (5,4).\n- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).\nIt can be shown that it is not possible to represent the line chart using less than 3 lines.\n\n\n
Example 2:
\n\nInput: stockPrices = [[3,4],[1,2],[7,8],[2,3]]\nOutput: 1\nExplanation:\nAs shown in the diagram above, the line chart can be represented with a single line.\n\n\n
\n
Constraints:
\n\n1 <= stockPrices.length <= 105
stockPrices[i].length == 2
1 <= dayi, pricei <= 109
dayi
are distinct.As the ruler of a kingdom, you have an army of wizards at your command.
\n\nYou are given a 0-indexed integer array strength
, where strength[i]
denotes the strength of the ith
wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength
), the total strength is defined as the product of the following two values:
Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: strength = [1,3,1,2]\nOutput: 44\nExplanation: The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.\n\n\n
Example 2:
\n\n\nInput: strength = [5,4,6]\nOutput: 213\nExplanation: The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.\n\n\n
\n
Constraints:
\n\n1 <= strength.length <= 105
1 <= strength[i] <= 109
You are given a 0-indexed string num
of length n
consisting of digits.
Return true
if for every index i
in the range 0 <= i < n
, the digit i
occurs num[i]
times in num
, otherwise return false
.
\n
Example 1:
\n\n\nInput: num = "1210"\nOutput: true\nExplanation:\nnum[0] = '1'. The digit 0 occurs once in num.\nnum[1] = '2'. The digit 1 occurs twice in num.\nnum[2] = '1'. The digit 2 occurs once in num.\nnum[3] = '0'. The digit 3 occurs zero times in num.\nThe condition holds true for every index in "1210", so return true.\n\n\n
Example 2:
\n\n\nInput: num = "030"\nOutput: false\nExplanation:\nnum[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\nnum[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\nnum[2] = '0'. The digit 2 occurs zero times in num.\nThe indices 0 and 1 both violate the condition, so return false.\n\n\n
\n
Constraints:
\n\nn == num.length
1 <= n <= 10
num
consists of digits.You have a chat log of n
messages. You are given two string arrays messages
and senders
where messages[i]
is a message sent by senders[i]
.
A message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.
\n\nReturn the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.
\n\nNote:
\n\n"Alice"
and "alice"
are distinct.\n
Example 1:
\n\n\nInput: messages = ["Hello userTwooo","Hi userThree","Wonderful day Alice","Nice day userThree"], senders = ["Alice","userTwo","userThree","Alice"]\nOutput: "Alice"\nExplanation: Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return "Alice".\n\n\n
Example 2:
\n\n\nInput: messages = ["How is leetcode for everyone","Leetcode is useful for practice"], senders = ["Bob","Charlie"]\nOutput: "Charlie"\nExplanation: Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.\n\n
\n
Constraints:
\n\nn == messages.length == senders.length
1 <= n <= 104
1 <= messages[i].length <= 100
1 <= senders[i].length <= 10
messages[i]
consists of uppercase and lowercase English letters and ' '
.messages[i]
are separated by a single space.messages[i]
does not have leading or trailing spaces.senders[i]
consists of uppercase and lowercase English letters only.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 integer value from 1
to n
, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.
Return the maximum total importance of all roads possible after assigning the values optimally.
\n\n\n
Example 1:
\n\nInput: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput: 43\nExplanation: The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.\n\n\n
Example 2:
\n\nInput: n = 5, roads = [[0,3],[2,4],[1,3]]\nOutput: 20\nExplanation: The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.\n\n\n
\n
Constraints:
\n\n2 <= n <= 5 * 104
1 <= roads.length <= 5 * 104
roads[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
A concert hall has n
rows numbered from 0
to n - 1
, each with m
seats, numbered from 0
to m - 1
. You need to design a ticketing system that can allocate seats in the following cases:
k
spectators can sit together in a row.k
spectators can get a seat. They may or may not sit together.Note that the spectators are very picky. Hence:
\n\nmaxRow
. maxRow
can vary from group to group.Implement the BookMyShow
class:
BookMyShow(int n, int m)
Initializes the object with n
as number of rows and m
as number of seats per row.int[] gather(int k, int maxRow)
Returns an array of length 2
denoting the row and seat number (respectively) of the first seat being allocated to the k
members of the group, who must sit together. In other words, it returns the smallest possible r
and c
such that all [c, c + k - 1]
seats are valid and empty in row r
, and r <= maxRow
. Returns []
in case it is not possible to allocate seats to the group.boolean scatter(int k, int maxRow)
Returns true
if all k
members of the group can be allocated seats in rows 0
to maxRow
, who may or may not sit together. If the seats can be allocated, it allocates k
seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returns false
.\n
Example 1:
\n\n\nInput\n["BookMyShow", "gather", "gather", "scatter", "scatter"]\n[[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]\nOutput\n[null, [0, 0], [], true, false]\n\nExplanation\nBookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \nbms.gather(4, 0); // return [0, 0]\n // The group books seats [0, 3] of row 0. \nbms.gather(2, 0); // return []\n // There is only 1 seat left in row 0,\n // so it is not possible to book 2 consecutive seats. \nbms.scatter(5, 1); // return True\n // The group books seat 4 of row 0 and seats [0, 3] of row 1. \nbms.scatter(5, 1); // return False\n // There is only one seat left in the hall.\n\n\n
\n
Constraints:
\n\n1 <= n <= 5 * 104
1 <= m, k <= 109
0 <= maxRow <= n - 1
5 * 104
calls in total will be made to gather
and scatter
.You are given two 0-indexed strings s
and target
. You can take some letters from s
and rearrange them to form new strings.
Return the maximum number of copies of target
that can be formed by taking letters from s
and rearranging them.
\n
Example 1:
\n\n\nInput: s = "ilovecodingonleetcode", target = "code"\nOutput: 2\nExplanation:\nFor the first copy of "code", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of "code", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are "ecod" and "code" which can both be rearranged into "code".\nWe can make at most two copies of "code", so we return 2.\n\n\n
Example 2:
\n\n\nInput: s = "abcba", target = "abc"\nOutput: 1\nExplanation:\nWe can make one copy of "abc" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of "abc", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of "abc".\n\n\n
Example 3:
\n\n\nInput: s = "abbaccaddaeea", target = "aaaaa"\nOutput: 1\nExplanation:\nWe can make one copy of "aaaaa" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of "aaaaa", so we return 1.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
1 <= target.length <= 10
s
and target
consist of lowercase English letters.\n
Note: This question is the same as 1189: Maximum Number of Balloons.
\n", - "likes": 490, + "likes": 506, "dislikes": 36, - "stats": "{\"totalAccepted\": \"46.6K\", \"totalSubmission\": \"77.7K\", \"totalAcceptedRaw\": 46559, \"totalSubmissionRaw\": 77734, \"acRate\": \"59.9%\"}", + "stats": "{\"totalAccepted\": \"49.9K\", \"totalSubmission\": \"82.9K\", \"totalAcceptedRaw\": 49855, \"totalSubmissionRaw\": 82865, \"acRate\": \"60.2%\"}", "similarQuestions": "[{\"title\": \"Find Words That Can Be Formed by Characters\", \"titleSlug\": \"find-words-that-can-be-formed-by-characters\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Occurrences of a Substring\", \"titleSlug\": \"maximum-number-of-occurrences-of-a-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -86397,9 +86568,9 @@ "questionFrontendId": "2288", "title": "Apply Discount to Prices", "content": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'
. A word represents a price if it is a sequence of digits preceded by a dollar sign.
"$100"
, "$23"
, and "$6"
represent prices while "100"
, "$"
, and "$1e5"
do not.You are given a string sentence
representing a sentence and an integer discount
. For each word representing a price, apply a discount of discount%
on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.
Return a string representing the modified sentence.
\n\nNote that all prices will contain at most 10
digits.
\n
Example 1:
\n\n\nInput: sentence = "there are $1 $2 and 5$ candies in the shop", discount = 50\nOutput: "there are $0.50 $1.00 and 5$ candies in the shop"\nExplanation: \nThe words which represent prices are "$1" and "$2". \n- A 50% discount on "$1" yields "$0.50", so "$1" is replaced by "$0.50".\n- A 50% discount on "$2" yields "$1". Since we need to have exactly 2 decimal places after a price, we replace "$2" with "$1.00".\n\n\n
Example 2:
\n\n\nInput: sentence = "1 2 $3 4 $5 $6 7 8$ $9 $10$", discount = 100\nOutput: "1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$"\nExplanation: \nApplying a 100% discount on any price will result in 0.\nThe words representing prices are "$3", "$5", "$6", and "$9".\nEach of them is replaced by "$0.00".\n\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 105
sentence
consists of lowercase English letters, digits, ' '
, and '$'
.sentence
does not have leading or trailing spaces.sentence
are separated by a single space.10
digits.0 <= discount <= 100
You are given a 0-indexed integer array nums
. In one step, remove all elements nums[i]
where nums[i - 1] > nums[i]
for all 0 < i < nums.length
.
Return the number of steps performed until nums
becomes a non-decreasing array.
\n
Example 1:
\n\n\nInput: nums = [5,3,4,4,7,3,6,11,8,5,11]\nOutput: 3\nExplanation: The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.\n\n\n
Example 2:
\n\n\nInput: nums = [4,5,7,7,13]\nOutput: 0\nExplanation: nums is already a non-decreasing array. Therefore, we return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed 2D integer array grid
of size m x n
. Each cell has one of two values:
0
represents an empty cell,1
represents an obstacle that may be removed.You can move up, down, left, or right from and to an empty cell.
\n\nReturn the minimum number of obstacles to remove so you can move from the upper left corner (0, 0)
to the lower right corner (m - 1, n - 1)
.
\n
Example 1:
\n\nInput: grid = [[0,1,1],[1,1,0],[1,1,0]]\nOutput: 2\nExplanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.\n\n\n
Example 2:
\n\nInput: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\nOutput: 0\nExplanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
2 <= m * n <= 105
grid[i][j]
is either 0
or 1
.grid[0][0] == grid[m - 1][n - 1] == 0
You are given a 0-indexed integer array nums
whose length is a power of 2
.
Apply the following algorithm on nums
:
n
be the length of nums
. If n == 1
, end the process. Otherwise, create a new 0-indexed integer array newNums
of length n / 2
.i
where 0 <= i < n / 2
, assign the value of newNums[i]
as min(nums[2 * i], nums[2 * i + 1])
.i
where 0 <= i < n / 2
, assign the value of newNums[i]
as max(nums[2 * i], nums[2 * i + 1])
.nums
with newNums
.Return the last number that remains in nums
after applying the algorithm.
\n
Example 1:
\n\nInput: nums = [1,3,5,2,4,8,2,2]\nOutput: 1\nExplanation: The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.\n\n\n
Example 2:
\n\n\nInput: nums = [3]\nOutput: 3\nExplanation: 3 is already the last remaining number, so we return 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1024
1 <= nums[i] <= 109
nums.length
is a power of 2
.You are given an integer array nums
and an integer k
. You may partition nums
into one or more subsequences such that each element in nums
appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k
.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,6,1,2,5], k = 2\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3], k = 1\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].\n\n\n
Example 3:
\n\n\nInput: nums = [2,2,4,5], k = 0\nOutput: 3\nExplanation:\nWe can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
0 <= k <= 105
You are given a 0-indexed array nums
that consists of n
distinct positive integers. Apply m
operations to this array, where in the ith
operation you replace the number operations[i][0]
with operations[i][1]
.
It is guaranteed that in the ith
operation:
operations[i][0]
exists in nums
.operations[i][1]
does not exist in nums
.Return the array obtained after applying all the operations.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\nOutput: [3,2,7,1]\nExplanation: We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].\n\n\n
Example 2:
\n\n\nInput: nums = [1,2], operations = [[1,3],[2,1],[3,2]]\nOutput: [2,1]\nExplanation: We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].\n\n\n
\n
Constraints:
\n\nn == nums.length
m == operations.length
1 <= n, m <= 105
nums
are distinct.operations[i].length == 2
1 <= nums[i], operations[i][0], operations[i][1] <= 106
operations[i][0]
will exist in nums
when applying the ith
operation.operations[i][1]
will not exist in nums
when applying the ith
operation.Design a text editor with a cursor that can do the following:
\n\nWhen deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length
always holds.
Implement the TextEditor
class:
TextEditor()
Initializes the object with empty text.void addText(string text)
Appends text
to where the cursor is. The cursor ends to the right of text
.int deleteText(int k)
Deletes k
characters to the left of the cursor. Returns the number of characters actually deleted.string cursorLeft(int k)
Moves the cursor to the left k
times. Returns the last min(10, len)
characters to the left of the cursor, where len
is the number of characters to the left of the cursor.string cursorRight(int k)
Moves the cursor to the right k
times. Returns the last min(10, len)
characters to the left of the cursor, where len
is the number of characters to the left of the cursor.\n
Example 1:
\n\n\nInput\n["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]\n[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]\nOutput\n[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]\n\nExplanation\nTextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)\ntextEditor.addText("leetcode"); // The current text is "leetcode|".\ntextEditor.deleteText(4); // return 4\n // The current text is "leet|". \n // 4 characters were deleted.\ntextEditor.addText("practice"); // The current text is "leetpractice|". \ntextEditor.cursorRight(3); // return "etpractice"\n // The current text is "leetpractice|". \n // The cursor cannot be moved beyond the actual text and thus did not move.\n // "etpractice" is the last 10 characters to the left of the cursor.\ntextEditor.cursorLeft(8); // return "leet"\n // The current text is "leet|practice".\n // "leet" is the last min(10, 4) = 4 characters to the left of the cursor.\ntextEditor.deleteText(10); // return 4\n // The current text is "|practice".\n // Only 4 characters were deleted.\ntextEditor.cursorLeft(2); // return ""\n // The current text is "|practice".\n // The cursor cannot be moved beyond the actual text and thus did not move. \n // "" is the last min(10, 0) = 0 characters to the left of the cursor.\ntextEditor.cursorRight(6); // return "practi"\n // The current text is "practi|ce".\n // "practi" is the last min(10, 6) = 6 characters to the left of the cursor.\n\n\n
\n
Constraints:
\n\n1 <= text.length, k <= 40
text
consists of lowercase English letters.2 * 104
calls in total will be made to addText
, deleteText
, cursorLeft
and cursorRight
.\n
Follow-up: Could you find a solution with time complexity of O(k)
per call?
A password is said to be strong if it satisfies all the following criteria:
\n\n8
characters."!@#$%^&*()-+"
.2
of the same character in adjacent positions (i.e., "aab"
violates this condition, but "aba"
does not).Given a string password
, return true
if it is a strong password. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: password = "IloveLe3tcode!"\nOutput: true\nExplanation: The password meets all the requirements. Therefore, we return true.\n\n\n
Example 2:
\n\n\nInput: password = "Me+You--IsMyDream"\nOutput: false\nExplanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.\n\n\n
Example 3:
\n\n\nInput: password = "1aB!"\nOutput: false\nExplanation: The password does not meet the length requirement. Therefore, we return false.\n\n
\n
Constraints:
\n\n1 <= password.length <= 100
password
consists of letters, digits, and special characters: "!@#$%^&*()-+"
.You are given two positive integer arrays spells
and potions
, of length n
and m
respectively, where spells[i]
represents the strength of the ith
spell and potions[j]
represents the strength of the jth
potion.
You are also given an integer success
. A spell and potion pair is considered successful if the product of their strengths is at least success
.
Return an integer array pairs
of length n
where pairs[i]
is the number of potions that will form a successful pair with the ith
spell.
\n
Example 1:
\n\n\nInput: spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput: [4,0,3]\nExplanation:\n- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.\n\n\n
Example 2:
\n\n\nInput: spells = [3,1,2], potions = [8,5,8], success = 16\nOutput: [2,0,2]\nExplanation:\n- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.\n\n\n
\n
Constraints:
\n\nn == spells.length
m == potions.length
1 <= n, m <= 105
1 <= spells[i], potions[i] <= 105
1 <= success <= 1010
You are given two strings s
and sub
. You are also given a 2D character array mappings
where mappings[i] = [oldi, newi]
indicates that you may perform the following operation any number of times:
oldi
of sub
with newi
.Each character in sub
cannot be replaced more than once.
Return true
if it is possible to make sub
a substring of s
by replacing zero or more characters according to mappings
. Otherwise, return false
.
A substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]\nOutput: true\nExplanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.\nNow sub = "l3e7" is a substring of s, so we return true.\n\n
Example 2:
\n\n\nInput: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]]\nOutput: false\nExplanation: The string "f00l" is not a substring of s and no replacements can be made.\nNote that we cannot replace '0' with 'o'.\n\n\n
Example 3:
\n\n\nInput: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]]\nOutput: true\nExplanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\nNow sub = "l33tb" is a substring of s, so we return true.\n\n\n\n
\n
Constraints:
\n\n1 <= sub.length <= s.length <= 5000
0 <= mappings.length <= 1000
mappings[i].length == 2
oldi != newi
s
and sub
consist of uppercase and lowercase English letters and digits.oldi
and newi
are either uppercase or lowercase English letters or digits.The score of an array is defined as the product of its sum and its length.
\n\n[1, 2, 3, 4, 5]
is (1 + 2 + 3 + 4 + 5) * 5 = 75
.Given a positive integer array nums
and an integer k
, return the number of non-empty subarrays of nums
whose score is strictly less than k
.
A subarray is a contiguous sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,4,3,5], k = 10\nOutput: 6\nExplanation:\nThe 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.\n\n
Example 2:
\n\n\nInput: nums = [1,1,1], k = 5\nOutput: 5\nExplanation:\nEvery subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= k <= 1015
You are given a 0-indexed 2D integer array brackets
where brackets[i] = [upperi, percenti]
means that the ith
tax bracket has an upper bound of upperi
and is taxed at a rate of percenti
. The brackets are sorted by upper bound (i.e. upperi-1 < upperi
for 0 < i < brackets.length
).
Tax is calculated as follows:
\n\nupper0
dollars earned are taxed at a rate of percent0
.upper1 - upper0
dollars earned are taxed at a rate of percent1
.upper2 - upper1
dollars earned are taxed at a rate of percent2
.You are given an integer income
representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5
of the actual answer will be accepted.
\n
Example 1:
\n\n\nInput: brackets = [[3,50],[7,10],[12,25]], income = 10\nOutput: 2.65000\nExplanation:\nBased on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.\n\n\n
Example 2:
\n\n\nInput: brackets = [[1,0],[4,25],[5,50]], income = 2\nOutput: 0.25000\nExplanation:\nBased on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.\n\n\n
Example 3:
\n\n\nInput: brackets = [[2,50]], income = 0\nOutput: 0.00000\nExplanation:\nYou have no income to tax, so you have to pay a total of $0 in taxes.\n\n\n
\n
Constraints:
\n\n1 <= brackets.length <= 100
1 <= upperi <= 1000
0 <= percenti <= 100
0 <= income <= 1000
upperi
is sorted in ascending order.upperi
are unique.income
.You are given a 0-indexed m x n
integer matrix grid
consisting of distinct integers from 0
to m * n - 1
. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y)
such that x < m - 1
, you can move to any of the cells (x + 1, 0)
, (x + 1, 1)
, ..., (x + 1, n - 1)
. Note that it is not possible to move from cells in the last row.
Each possible move has a cost given by a 0-indexed 2D array moveCost
of size (m * n) x n
, where moveCost[i][j]
is the cost of moving from a cell with value i
to a cell in column j
of the next row. The cost of moving from cells in the last row of grid
can be ignored.
The cost of a path in grid
is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.
\n
Example 1:
\n\nInput: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]\nOutput: 17\nExplanation: The path with the minimum possible cost is the path 5 -> 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.\n\n\n
Example 2:
\n\n\nInput: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]\nOutput: 6\nExplanation: The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 50
grid
consists of distinct integers from 0
to m * n - 1
.moveCost.length == m * n
moveCost[i].length == n
1 <= moveCost[i][j] <= 100
You are given an integer array cookies
, where cookies[i]
denotes the number of cookies in the ith
bag. You are also given an integer k
that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.
\n\nReturn the minimum unfairness of all distributions.
\n\n\n
Example 1:
\n\n\nInput: cookies = [8,15,10,20,8], k = 2\nOutput: 31\nExplanation: One optimal distribution is [8,15,8] and [10,20]\n- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.\n- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.\nThe unfairness of the distribution is max(31,30) = 31.\nIt can be shown that there is no distribution with an unfairness less than 31.\n\n\n
Example 2:
\n\n\nInput: cookies = [6,1,3,2,2,4,1,2], k = 3\nOutput: 7\nExplanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]\n- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.\n- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.\n- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.\nThe unfairness of the distribution is max(7,7,7) = 7.\nIt can be shown that there is no distribution with an unfairness less than 7.\n\n\n
\n
Constraints:
\n\n2 <= cookies.length <= 8
1 <= cookies[i] <= 105
2 <= k <= cookies.length
You are given an array of strings ideas
that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:
ideas
, call them ideaA
and ideaB
.ideaA
and ideaB
with each other.ideas
, then the name ideaA ideaB
(the concatenation of ideaA
and ideaB
, separated by a space) is a valid company name.Return the number of distinct valid names for the company.
\n\n\n
Example 1:
\n\n\nInput: ideas = ["coffee","donuts","time","toffee"]\nOutput: 6\nExplanation: The following selections are valid:\n- ("coffee", "donuts"): The company name created is "doffee conuts".\n- ("donuts", "coffee"): The company name created is "conuts doffee".\n- ("donuts", "time"): The company name created is "tonuts dime".\n- ("donuts", "toffee"): The company name created is "tonuts doffee".\n- ("time", "donuts"): The company name created is "dime tonuts".\n- ("toffee", "donuts"): The company name created is "doffee tonuts".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.\n- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.\n- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.\n\n\n
Example 2:
\n\n\nInput: ideas = ["lack","back"]\nOutput: 0\nExplanation: There are no valid selections. Therefore, 0 is returned.\n\n\n
\n
Constraints:
\n\n2 <= ideas.length <= 5 * 104
1 <= ideas[i].length <= 10
ideas[i]
consists of lowercase English letters.ideas
are unique.Given a string of English letters s
, return the greatest English letter which occurs as both a lowercase and uppercase letter in s
. The returned letter should be in uppercase. If no such letter exists, return an empty string.
An English letter b
is greater than another letter a
if b
appears after a
in the English alphabet.
\n
Example 1:
\n\n\nInput: s = "lEeTcOdE"\nOutput: "E"\nExplanation:\nThe letter 'E' is the only letter to appear in both lower and upper case.\n\n\n
Example 2:
\n\n\nInput: s = "arRAzFif"\nOutput: "R"\nExplanation:\nThe letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.\n\n\n
Example 3:
\n\n\nInput: s = "AbCdEfGhIjK"\nOutput: ""\nExplanation:\nThere is no letter that appears in both lower and upper case.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of lowercase and uppercase English letters.Given two integers num
and k
, consider a set of positive integers with the following properties:
k
.num
.Return the minimum possible size of such a set, or -1
if no such set exists.
Note:
\n\n0
.\n
Example 1:
\n\n\nInput: num = 58, k = 9\nOutput: 2\nExplanation:\nOne valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.\n\n\n
Example 2:
\n\n\nInput: num = 37, k = 2\nOutput: -1\nExplanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.\n\n\n
Example 3:
\n\n\nInput: num = 0, k = 7\nOutput: 0\nExplanation: The sum of an empty set is considered 0.\n\n\n
\n
Constraints:
\n\n0 <= num <= 3000
0 <= k <= 9
You are given a binary string s
and a positive integer k
.
Return the length of the longest subsequence of s
that makes up a binary number less than or equal to k
.
Note:
\n\n0
.\n
Example 1:
\n\n\nInput: s = "1001010", k = 5\nOutput: 5\nExplanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.\nNote that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.\n\n\n
Example 2:
\n\n\nInput: s = "00101001", k = 1\nOutput: 6\nExplanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either '0'
or '1'
.1 <= k <= 109
You are given two integers m
and n
that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices
, where prices[i] = [hi, wi, pricei]
indicates you can sell a rectangular piece of wood of height hi
and width wi
for pricei
dollars.
To cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices
. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.
Return the maximum money you can earn after cutting an m x n
piece of wood.
Note that you can cut the piece of wood as many times as you want.
\n\n\n
Example 1:
\n\nInput: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\nOutput: 19\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.\n\n\n
Example 2:
\n\nInput: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\nOutput: 32\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.\n\n
\n
Constraints:
\n\n1 <= m, n <= 200
1 <= prices.length <= 2 * 104
prices[i].length == 3
1 <= hi <= m
1 <= wi <= n
1 <= pricei <= 106
(hi, wi)
are pairwise distinct.You are given a string s
, where every two consecutive vertical bars '|'
are grouped into a pair. In other words, the 1st and 2nd '|'
make a pair, the 3rd and 4th '|'
make a pair, and so forth.
Return the number of '*'
in s
, excluding the '*'
between each pair of '|'
.
Note that each '|'
will belong to exactly one pair.
\n
Example 1:
\n\n\nInput: s = "l|*e*et|c**o|*de|"\nOutput: 2\nExplanation: The considered characters are underlined: "l|*e*et|c**o|*de|".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.\n\n
Example 2:
\n\n\nInput: s = "iamprogrammer"\nOutput: 0\nExplanation: In this example, there are no asterisks in s. Therefore, we return 0.\n\n\n
Example 3:
\n\n\nInput: s = "yo|uar|e**|b|e***au|tifu|l"\nOutput: 5\nExplanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of lowercase English letters, vertical bars '|'
, and asterisks '*'
.s
contains an even number of vertical bars '|'
.You are given an integer n
. There is an undirected graph with n
nodes, numbered from 0
to n - 1
. You are given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
Return the number of pairs of different nodes that are unreachable from each other.
\n\n\n
Example 1:
\n\nInput: n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput: 0\nExplanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.\n\n\n
Example 2:
\n\nInput: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput: 14\nExplanation: There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
0 <= edges.length <= 2 * 105
edges[i].length == 2
0 <= ai, bi < n
ai != bi
You are given a 0-indexed integer array nums
. In one operation, select any non-negative integer x
and an index i
, then update nums[i]
to be equal to nums[i] AND (nums[i] XOR x)
.
Note that AND
is the bitwise AND operation and XOR
is the bitwise XOR operation.
Return the maximum possible bitwise XOR of all elements of nums
after applying the operation any number of times.
\n
Example 1:
\n\n\nInput: nums = [3,2,4,6]\nOutput: 7\nExplanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,9,2]\nOutput: 11\nExplanation: Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 108
You are given an integer n
. You roll a fair 6-sided dice n
times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:
1
.2
rolls between equal valued rolls. More formally, if the value of the ith
roll is equal to the value of the jth
roll, then abs(i - j) > 2
.Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7
.
Two sequences are considered distinct if at least one element is different.
\n\n\n
Example 1:
\n\n\nInput: n = 4\nOutput: 184\nExplanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\nSome invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).\n(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).\n(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.\nThere are a total of 184 distinct sequences possible, so we return 184.\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 22\nExplanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).\nSome invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\nThere are a total of 22 distinct sequences possible, so we return 22.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
A square matrix is said to be an X-Matrix if both of the following conditions hold:
\n\nGiven a 2D integer array grid
of size n x n
representing a square matrix, return true
if grid
is an X-Matrix. Otherwise, return false
.
\n
Example 1:
\n\nInput: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]\nOutput: true\nExplanation: Refer to the diagram above. \nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is an X-Matrix.\n\n\n
Example 2:
\n\nInput: grid = [[5,7,0],[0,3,1],[0,5,0]]\nOutput: false\nExplanation: Refer to the diagram above.\nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is not an X-Matrix.\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
3 <= n <= 100
0 <= grid[i][j] <= 105
There is a street with n * 2
plots, where there are n
plots on each side of the street. The plots on each side are numbered from 1
to n
. On each plot, a house can be placed.
Return the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7
.
Note that if a house is placed on the ith
plot on one side of the street, a house can also be placed on the ith
plot on the other side of the street.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 4\nExplanation: \nPossible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.\n\n\n
Example 2:
\n\nInput: n = 2\nOutput: 9\nExplanation: The 9 possible arrangements are shown in the diagram above.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
You are given two 0-indexed integer arrays nums1
and nums2
, both of length n
.
You can choose two integers left
and right
where 0 <= left <= right < n
and swap the subarray nums1[left...right]
with the subarray nums2[left...right]
.
nums1 = [1,2,3,4,5]
and nums2 = [11,12,13,14,15]
and you choose left = 1
and right = 2
, nums1
becomes [1,12,13,4,5]
and nums2
becomes [11,2,3,14,15]
.You may choose to apply the mentioned operation once or not do anything.
\n\nThe score of the arrays is the maximum of sum(nums1)
and sum(nums2)
, where sum(arr)
is the sum of all the elements in the array arr
.
Return the maximum possible score.
\n\nA subarray is a contiguous sequence of elements within an array. arr[left...right]
denotes the subarray that contains the elements of nums
between indices left
and right
(inclusive).
\n
Example 1:
\n\n\nInput: nums1 = [60,60,60], nums2 = [10,90,10]\nOutput: 210\nExplanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.\n\n
Example 2:
\n\n\nInput: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]\nOutput: 220\nExplanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.\n\n\n
Example 3:
\n\n\nInput: nums1 = [7,11,13], nums2 = [1,1,1]\nOutput: 31\nExplanation: We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 104
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]
indicates that there is an edge between nodes ai
and bi
in the tree.
Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:
\n\n[4,5,7]
, [1,9]
, and [3,3,3]
. The three XOR values are 4 ^ 5 ^ 7 = 6
, 1 ^ 9 = 8
, and 3 ^ 3 ^ 3 = 3
. The largest XOR value is 8
and the smallest XOR value is 3
. The score is then 8 - 3 = 5
.Return the minimum score of any possible pair of edge removals on the given tree.
\n\n\n
Example 1:
\n\nInput: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]\nOutput: 9\nExplanation: The diagram above shows a way to make a pair of removals.\n- The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.\n\n\n
Example 2:
\n\nInput: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]\nOutput: 0\nExplanation: The diagram above shows a way to make a pair of removals.\n- The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.\n\n\n
\n
Constraints:
\n\nn == nums.length
3 <= n <= 1000
1 <= nums[i] <= 108
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.You are given the strings key
and message
, which represent a cipher key and a secret message, respectively. The steps to decode message
are as follows:
key
as the order of the substitution table.message
is then substituted using the table.' '
are transformed to themselves.key = "happy boy"
(actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a'
, 'a' -> 'b'
, 'p' -> 'c'
, 'y' -> 'd'
, 'b' -> 'e'
, 'o' -> 'f'
).Return the decoded message.
\n\n\n
Example 1:
\n\nInput: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv"\nOutput: "this is a secret"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog".\n\n\n
Example 2:
\n\nInput: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb"\nOutput: "the five boxing wizards jump quickly"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo".\n\n\n
\n
Constraints:
\n\n26 <= key.length <= 2000
key
consists of lowercase English letters and ' '
.key
contains every letter in the English alphabet ('a'
to 'z'
) at least once.1 <= message.length <= 2000
message
consists of lowercase English letters and ' '
.You are given two integers m
and n
, which represent the dimensions of a matrix.
You are also given the head
of a linked list of integers.
Generate an m x n
matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1
.
Return the generated matrix.
\n\n\n
Example 1:
\n\nInput: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation: The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.\n\n\n
Example 2:
\n\nInput: m = 1, n = 4, head = [0,1,2]\nOutput: [[0,1,2,-1]]\nExplanation: The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.\n\n
\n
Constraints:
\n\n1 <= m, n <= 105
1 <= m * n <= 105
[1, m * n]
.0 <= Node.val <= 1000
On day 1
, one person discovers a secret.
You are given an integer delay
, which means that each person will share the secret with a new person every day, starting from delay
days after discovering the secret. You are also given an integer forget
, which means that each person will forget the secret forget
days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.
Given an integer n
, return the number of people who know the secret at the end of day n
. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 6, delay = 2, forget = 4\nOutput: 5\nExplanation:\nDay 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)\n\n\n
Example 2:
\n\n\nInput: n = 4, delay = 1, forget = 3\nOutput: 6\nExplanation:\nDay 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
1 <= delay < forget <= n
You are given an m x n
integer matrix grid
, where you can move from a cell to any adjacent cell in all 4
directions.
Return the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7
.
Two paths are considered different if they do not have exactly the same sequence of visited cells.
\n\n\n
Example 1:
\n\nInput: grid = [[1,1],[3,4]]\nOutput: 8\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.\n\n\n
Example 2:
\n\n\nInput: grid = [[1],[2]]\nOutput: 3\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= grid[i][j] <= 105
You are given the root
of a full binary tree with the following properties:
0
or 1
, where 0
represents False
and 1
represents True
.2
or 3
, where 2
represents the boolean OR
and 3
represents the boolean AND
.The evaluation of a node is as follows:
\n\nTrue
or False
.Return the boolean result of evaluating the root
node.
A full binary tree is a binary tree where each node has either 0
or 2
children.
A leaf node is a node that has zero children.
\n\n\n
Example 1:
\n\nInput: root = [2,1,3,null,null,0,1]\nOutput: true\nExplanation: The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.\n\n
Example 2:
\n\n\nInput: root = [0]\nOutput: false\nExplanation: The root node is a leaf node and it evaluates to false, so we return false.\n\n\n
\n
Constraints:
\n\n[1, 1000]
.0 <= Node.val <= 3
0
or 2
children.0
or 1
.2
or 3
.You are given a 0-indexed integer array buses
of length n
, where buses[i]
represents the departure time of the ith
bus. You are also given a 0-indexed integer array passengers
of length m
, where passengers[j]
represents the arrival time of the jth
passenger. All bus departure times are unique. All passenger arrival times are unique.
You are given an integer capacity
, which represents the maximum number of passengers that can get on each bus.
When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x
minutes if you arrive at y
minutes where y <= x
, and the bus is not full. Passengers with the earliest arrival times get on the bus first.
More formally when a bus arrives, either:
\n\ncapacity
or fewer passengers are waiting for a bus, they will all get on the bus, orcapacity
passengers with the earliest arrival times will get on the bus.Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.
\n\nNote: The arrays buses
and passengers
are not necessarily sorted.
\n
Example 1:
\n\n\nInput: buses = [10,20], passengers = [2,17,18,19], capacity = 2\nOutput: 16\nExplanation: Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0th passenger. \nAt time 20, the second bus departs with you and the 1st passenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.\n\n
Example 2:
\n\n\nInput: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2\nOutput: 20\nExplanation: Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rd passenger. \nAt time 20, the second bus departs with the 5th and 1st passengers.\nAt time 30, the third bus departs with the 0th passenger and you.\nNotice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.\n\n
\n
Constraints:
\n\nn == buses.length
m == passengers.length
1 <= n, m, capacity <= 105
2 <= buses[i], passengers[i] <= 109
buses
is unique.passengers
is unique.You are given two positive 0-indexed integer arrays nums1
and nums2
, both of length n
.
The sum of squared difference of arrays nums1
and nums2
is defined as the sum of (nums1[i] - nums2[i])2
for each 0 <= i < n
.
You are also given two positive integers k1
and k2
. You can modify any of the elements of nums1
by +1
or -1
at most k1
times. Similarly, you can modify any of the elements of nums2
by +1
or -1
at most k2
times.
Return the minimum sum of squared difference after modifying array nums1
at most k1
times and modifying array nums2
at most k2
times.
Note: You are allowed to modify the array elements to become negative integers.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\nOutput: 579\nExplanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\nOutput: 43\nExplanation: One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 105
0 <= nums1[i], nums2[i] <= 105
0 <= k1, k2 <= 109
You are given an integer array nums
and an integer threshold
.
Find any subarray of nums
of length k
such that every element in the subarray is greater than threshold / k
.
Return the size of any such subarray. If there is no such subarray, return -1
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,4,3,1], threshold = 6\nOutput: 3\nExplanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.\nNote that this is the only valid subarray.\n\n\n
Example 2:
\n\n\nInput: nums = [6,5,6,5,8], threshold = 7\nOutput: 1\nExplanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i], threshold <= 109
You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2
cups with different types of water, or 1
cup of any type of water.
You are given a 0-indexed integer array amount
of length 3
where amount[0]
, amount[1]
, and amount[2]
denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.
\n
Example 1:
\n\n\nInput: amount = [1,4,2]\nOutput: 4\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.\n\n\n
Example 2:
\n\n\nInput: amount = [5,4,4]\nOutput: 7\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.\n\n\n
Example 3:
\n\n\nInput: amount = [5,0,0]\nOutput: 5\nExplanation: Every second, we fill up a cold cup.\n\n\n
\n
Constraints:
\n\namount.length == 3
0 <= amount[i] <= 100
You have a set which contains all positive integers [1, 2, 3, 4, 5, ...]
.
Implement the SmallestInfiniteSet
class:
SmallestInfiniteSet()
Initializes the SmallestInfiniteSet object to contain all positive integers.int popSmallest()
Removes and returns the smallest integer contained in the infinite set.void addBack(int num)
Adds a positive integer num
back into the infinite set, if it is not already in the infinite set.\n
Example 1:
\n\n\nInput\n["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"]\n[[], [2], [], [], [], [1], [], [], []]\nOutput\n[null, null, 1, 2, 3, null, 1, 4, 5]\n\nExplanation\nSmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\nsmallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\nsmallestInfiniteSet.addBack(1); // 1 is added back to the set.\nsmallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n // is the smallest number, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\nsmallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.\n\n\n
\n
Constraints:
\n\n1 <= num <= 1000
1000
calls will be made in total to popSmallest
and addBack
.You are given two strings start
and target
, both of length n
. Each string consists only of the characters 'L'
, 'R'
, and '_'
where:
'L'
and 'R'
represent pieces, where a piece 'L'
can move to the left only if there is a blank space directly to its left, and a piece 'R'
can move to the right only if there is a blank space directly to its right.'_'
represents a blank space that can be occupied by any of the 'L'
or 'R'
pieces.Return true
if it is possible to obtain the string target
by moving the pieces of the string start
any number of times. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: start = "_L__R__R_", target = "L______RR"\nOutput: true\nExplanation: We can obtain the string target from start by doing the following moves:\n- Move the first piece one step to the left, start becomes equal to "L___R__R_".\n- Move the last piece one step to the right, start becomes equal to "L___R___R".\n- Move the second piece three steps to the right, start becomes equal to "L______RR".\nSince it is possible to get the string target from start, we return true.\n\n\n
Example 2:
\n\n\nInput: start = "R_L_", target = "__LR"\nOutput: false\nExplanation: The 'R' piece in the string start can move one step to the right to obtain "_RL_".\nAfter that, no pieces can move anymore, so it is impossible to obtain the string target from start.\n\n\n
Example 3:
\n\n\nInput: start = "_R", target = "R_"\nOutput: false\nExplanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.\n\n
\n
Constraints:
\n\nn == start.length == target.length
1 <= n <= 105
start
and target
consist of the characters 'L'
, 'R'
, and '_'
.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:
arr[i]
is a value from 1
to maxValue
, for 0 <= i < n
.arr[i]
is divisible by arr[i - 1]
, for 0 < i < n
.Return the number of distinct ideal arrays of length n
. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 2, maxValue = 5\nOutput: 10\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.\n\n\n
Example 2:
\n\n\nInput: n = 5, maxValue = 3\nOutput: 11\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n - With no other distinct values (1 array): [1,1,1,1,1] \n - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.\n\n\n
\n
Constraints:
\n\n2 <= n <= 104
1 <= maxValue <= 104
You are given a 0-indexed integer array nums
. In one operation, you may do the following:
nums
that are equal.nums
, forming a pair.The operation is done on nums
as many times as possible.
Return a 0-indexed integer array answer
of size 2
where answer[0]
is the number of pairs that are formed and answer[1]
is the number of leftover integers in nums
after doing the operation as many times as possible.
\n
Example 1:
\n\n\nInput: nums = [1,3,2,1,3,2,2]\nOutput: [3,1]\nExplanation:\nForm a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1]\nOutput: [1,0]\nExplanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.\n\n\n
Example 3:
\n\n\nInput: nums = [0]\nOutput: [0,1]\nExplanation: No pairs can be formed, and there is 1 number leftover in nums.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 100
You are given a 0-indexed array nums
consisting of positive integers. You can choose two indices i
and j
, such that i != j
, and the sum of digits of the number nums[i]
is equal to that of nums[j]
.
Return the maximum value of nums[i] + nums[j]
that you can obtain over all possible indices i
and j
that satisfy the conditions.
\n
Example 1:
\n\n\nInput: nums = [18,43,36,13,7]\nOutput: 54\nExplanation: The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.\n\n\n
Example 2:
\n\n\nInput: nums = [10,12,19,14]\nOutput: -1\nExplanation: There are no two numbers that satisfy the conditions, so we return -1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed array nums
consisting of positive integers. You can choose two indices i
and j
, such that i != j
, and the sum of digits of the number nums[i]
is equal to that of nums[j]
.
Return the maximum value of nums[i] + nums[j]
that you can obtain over all possible indices i
and j
that satisfy the conditions. If no such pair of indices exists, return -1.
\n
Example 1:
\n\n\nInput: nums = [18,43,36,13,7]\nOutput: 54\nExplanation: The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.\n\n\n
Example 2:
\n\n\nInput: nums = [10,12,19,14]\nOutput: -1\nExplanation: There are no two numbers that satisfy the conditions, so we return -1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed array of strings nums
, where each string is of equal length and consists of only digits.
You are also given a 0-indexed 2D integer array queries
where queries[i] = [ki, trimi]
. For each queries[i]
, you need to:
nums
to its rightmost trimi
digits.kith
smallest trimmed number in nums
. If two trimmed numbers are equal, the number with the lower index is considered to be smaller.nums
to its original length.Return an array answer
of the same length as queries
, where answer[i]
is the answer to the ith
query.
Note:
\n\nx
digits means to keep removing the leftmost digit, until only x
digits remain.nums
may contain leading zeros.\n
Example 1:
\n\n\nInput: nums = ["102","473","251","814"], queries = [[1,1],[2,3],[4,2],[1,2]]\nOutput: [2,2,1,0]\nExplanation:\n1. After trimming to the last digit, nums = ["2","3","1","4"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = ["02","73","51","14"]. The 4th smallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n Note that the trimmed number "02" is evaluated as 2.\n\n\n
Example 2:
\n\n\nInput: nums = ["24","37","96","04"], queries = [[2,1],[2,2]]\nOutput: [3,0]\nExplanation:\n1. Trimmed to the last digit, nums = ["4","7","6","4"]. The 2nd smallest number is 4 at index 3.\n There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i].length <= 100
nums[i]
consists of only digits.nums[i].length
are equal.1 <= queries.length <= 100
queries[i].length == 2
1 <= ki <= nums.length
1 <= trimi <= nums[i].length
\n
Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?
\n", - "likes": 322, - "dislikes": 434, - "stats": "{\"totalAccepted\": \"33.4K\", \"totalSubmission\": \"74.2K\", \"totalAcceptedRaw\": 33395, \"totalSubmissionRaw\": 74206, \"acRate\": \"45.0%\"}", + "likes": 328, + "dislikes": 437, + "stats": "{\"totalAccepted\": \"35.6K\", \"totalSubmission\": \"78.1K\", \"totalAcceptedRaw\": 35576, \"totalSubmissionRaw\": 78087, \"acRate\": \"45.6%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -88531,9 +88711,9 @@ "questionFrontendId": "2344", "title": "Minimum Deletions to Make Array Divisible", "content": "You are given two positive integer arrays nums
and numsDivide
. You can delete any number of elements from nums
.
Return the minimum number of deletions such that the smallest element in nums
divides all the elements of numsDivide
. If this is not possible, return -1
.
Note that an integer x
divides y
if y % x == 0
.
\n
Example 1:
\n\n\nInput: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]\nOutput: 2\nExplanation: \nThe smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.\nWe use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].\nThe smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.\nIt can be shown that 2 is the minimum number of deletions needed.\n\n\n
Example 2:
\n\n\nInput: nums = [4,3,6], numsDivide = [8,2,6,10]\nOutput: -1\nExplanation: \nWe want the smallest element in nums to divide all the elements of numsDivide.\nThere is no way to delete elements from nums to allow this.\n\n
\n
Constraints:
\n\n1 <= nums.length, numsDivide.length <= 105
1 <= nums[i], numsDivide[i] <= 109
You are given an integer array ranks
and a character array suits
. You have 5
cards where the ith
card has a rank of ranks[i]
and a suit of suits[i]
.
The following are the types of poker hands you can make from best to worst:
\n\n"Flush"
: Five cards of the same suit."Three of a Kind"
: Three cards of the same rank."Pair"
: Two cards of the same rank."High Card"
: Any single card.Return a string representing the best type of poker hand you can make with the given cards.
\n\nNote that the return values are case-sensitive.
\n\n\n
Example 1:
\n\n\nInput: ranks = [13,2,3,1,9], suits = ["a","a","a","a","a"]\nOutput: "Flush"\nExplanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".\n\n\n
Example 2:
\n\n\nInput: ranks = [4,4,2,4,4], suits = ["d","a","a","b","c"]\nOutput: "Three of a Kind"\nExplanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind".\nNote that we could also make a "Pair" hand but "Three of a Kind" is a better hand.\nAlso note that other cards could be used to make the "Three of a Kind" hand.\n\n
Example 3:
\n\n\nInput: ranks = [10,10,2,12,9], suits = ["a","b","c","a","d"]\nOutput: "Pair"\nExplanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair".\nNote that we cannot make a "Flush" or a "Three of a Kind".\n\n\n
\n
Constraints:
\n\nranks.length == suits.length == 5
1 <= ranks[i] <= 13
'a' <= suits[i] <= 'd'
Given an integer array nums
, return the number of subarrays filled with 0
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,0,0,2,0,0,4]\nOutput: 6\nExplanation: \nThere are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.\n\n
Example 2:
\n\n\nInput: nums = [0,0,0,2,0,0]\nOutput: 9\nExplanation:\nThere are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.\n\n\n
Example 3:
\n\n\nInput: nums = [2,10,2019]\nOutput: 0\nExplanation: There is no subarray filled with 0. Therefore, we return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
Design a number container system that can do the following:
\n\nImplement the NumberContainers
class:
NumberContainers()
Initializes the number container system.void change(int index, int number)
Fills the container at index
with the number
. If there is already a number at that index
, replace it.int find(int number)
Returns the smallest index for the given number
, or -1
if there is no index that is filled by number
in the system.\n
Example 1:
\n\n\nInput\n["NumberContainers", "find", "change", "change", "change", "change", "find", "change", "find"]\n[[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]\nOutput\n[null, -1, null, null, null, null, 1, null, 2]\n\nExplanation\nNumberContainers nc = new NumberContainers();\nnc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\nnc.change(2, 10); // Your container at index 2 will be filled with number 10.\nnc.change(1, 10); // Your container at index 1 will be filled with number 10.\nnc.change(3, 10); // Your container at index 3 will be filled with number 10.\nnc.change(5, 10); // Your container at index 5 will be filled with number 10.\nnc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\nnc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \nnc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.\n\n\n
\n
Constraints:
\n\n1 <= index, number <= 109
105
calls will be made in total to change
and find
.You are given an integer array rolls
of length n
and an integer k
. You roll a k
sided dice numbered from 1
to k
, n
times, where the result of the ith
roll is rolls[i]
.
Return the length of the shortest sequence of rolls so that there's no such subsequence in rolls
.
A sequence of rolls of length len
is the result of rolling a k
sided dice len
times.
\n
Example 1:
\n\n\nInput: rolls = [4,2,1,2,3,3,2,4,1], k = 4\nOutput: 3\nExplanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.\n\n
Example 2:
\n\n\nInput: rolls = [1,1,2,2], k = 2\nOutput: 2\nExplanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.\n\n\n
Example 3:
\n\n\nInput: rolls = [1,1,3,2,2,2,3,3], k = 4\nOutput: 1\nExplanation: The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.\n\n\n
\n
Constraints:
\n\nn == rolls.length
1 <= n <= 105
1 <= rolls[i] <= k <= 105
Given a string s
consisting of lowercase English letters, return the first letter to appear twice.
Note:
\n\na
appears twice before another letter b
if the second occurrence of a
is before the second occurrence of b
.s
will contain at least one letter that appears twice.\n
Example 1:
\n\n\nInput: s = "abccbaacz"\nOutput: "c"\nExplanation:\nThe letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.\n\n\n
Example 2:
\n\n\nInput: s = "abcdd"\nOutput: "d"\nExplanation:\nThe only letter that appears twice is 'd' so we return 'd'.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 100
s
consists of lowercase English letters.s
has at least one repeated letter.Given a 0-indexed n x n
integer matrix grid
, return the number of pairs (ri, cj)
such that row ri
and column cj
are equal.
A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).
\n\n\n
Example 1:
\n\nInput: grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput: 1\nExplanation: There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]\n\n\n
Example 2:
\n\nInput: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput: 3\nExplanation: There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
1 <= n <= 200
1 <= grid[i][j] <= 105
Design a food rating system that can do the following:
\n\nImplement the FoodRatings
class:
FoodRatings(String[] foods, String[] cuisines, int[] ratings)
Initializes the system. The food items are described by foods
, cuisines
and ratings
, all of which have a length of n
.\n\n\tfoods[i]
is the name of the ith
food,cuisines[i]
is the type of cuisine of the ith
food, andratings[i]
is the initial rating of the ith
food.void changeRating(String food, int newRating)
Changes the rating of the food item with the name food
.String highestRated(String cuisine)
Returns the name of the food item that has the highest rating for the given type of cuisine
. If there is a tie, return the item with the lexicographically smaller name.Note that a string x
is lexicographically smaller than string y
if x
comes before y
in dictionary order, that is, either x
is a prefix of y
, or if i
is the first position such that x[i] != y[i]
, then x[i]
comes before y[i]
in alphabetic order.
\n
Example 1:
\n\n\nInput\n["FoodRatings", "highestRated", "highestRated", "changeRating", "highestRated", "changeRating", "highestRated"]\n[[["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]], ["korean"], ["japanese"], ["sushi", 16], ["japanese"], ["ramen", 16], ["japanese"]]\nOutput\n[null, "kimchi", "ramen", null, "sushi", null, "ramen"]\n\nExplanation\nFoodRatings foodRatings = new FoodRatings(["kimchi", "miso", "sushi", "moussaka", "ramen", "bulgogi"], ["korean", "japanese", "japanese", "greek", "japanese", "korean"], [9, 12, 8, 15, 14, 7]);\nfoodRatings.highestRated("korean"); // return "kimchi"\n // "kimchi" is the highest rated korean food with a rating of 9.\nfoodRatings.highestRated("japanese"); // return "ramen"\n // "ramen" is the highest rated japanese food with a rating of 14.\nfoodRatings.changeRating("sushi", 16); // "sushi" now has a rating of 16.\nfoodRatings.highestRated("japanese"); // return "sushi"\n // "sushi" is the highest rated japanese food with a rating of 16.\nfoodRatings.changeRating("ramen", 16); // "ramen" now has a rating of 16.\nfoodRatings.highestRated("japanese"); // return "ramen"\n // Both "sushi" and "ramen" have a rating of 16.\n // However, "ramen" is lexicographically smaller than "sushi".\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 104
n == foods.length == cuisines.length == ratings.length
1 <= foods[i].length, cuisines[i].length <= 10
foods[i]
, cuisines[i]
consist of lowercase English letters.1 <= ratings[i] <= 108
foods
are distinct.food
will be the name of a food item in the system across all calls to changeRating
.cuisine
will be a type of cuisine of at least one food item in the system across all calls to highestRated
.2 * 104
calls in total will be made to changeRating
and highestRated
.You are given a 0-indexed positive integer array nums
and a positive integer k
.
A pair of numbers (num1, num2)
is called excellent if the following conditions are satisfied:
num1
and num2
exist in the array nums
.num1 OR num2
and num1 AND num2
is greater than or equal to k
, where OR
is the bitwise OR operation and AND
is the bitwise AND operation.Return the number of distinct excellent pairs.
\n\nTwo pairs (a, b)
and (c, d)
are considered distinct if either a != c
or b != d
. For example, (1, 2)
and (2, 1)
are distinct.
Note that a pair (num1, num2)
such that num1 == num2
can also be excellent if you have at least one occurrence of num1
in the array.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,1], k = 3\nOutput: 5\nExplanation: The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.\n\n
Example 2:
\n\n\nInput: nums = [5,1,1], k = 10\nOutput: 0\nExplanation: There are no excellent pairs for this array.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 60
Table: Teacher
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| teacher_id | int |\n| subject_id | int |\n| dept_id | int |\n+-------------+------+\n(subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table.\nEach row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.\n\n\n
\n\n
Write a solution to calculate the number of unique subjects each teacher teaches in the university.
\n\nReturn the result table in any order.
\n\nThe result format is shown in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nTeacher table:\n+------------+------------+---------+\n| teacher_id | subject_id | dept_id |\n+------------+------------+---------+\n| 1 | 2 | 3 |\n| 1 | 2 | 4 |\n| 1 | 3 | 3 |\n| 2 | 1 | 1 |\n| 2 | 2 | 1 |\n| 2 | 3 | 1 |\n| 2 | 4 | 1 |\n+------------+------------+---------+\nOutput: \n+------------+-----+\n| teacher_id | cnt |\n+------------+-----+\n| 1 | 2 |\n| 2 | 4 |\n+------------+-----+\nExplanation: \nTeacher 1:\n - They teach subject 2 in departments 3 and 4.\n - They teach subject 3 in department 3.\nTeacher 2:\n - They teach subject 1 in department 1.\n - They teach subject 2 in department 1.\n - They teach subject 3 in department 1.\n - They teach subject 4 in department 1.\n\n", - "likes": 546, - "dislikes": 45, - "stats": "{\"totalAccepted\": \"303.7K\", \"totalSubmission\": \"340.2K\", \"totalAcceptedRaw\": 303682, \"totalSubmissionRaw\": 340232, \"acRate\": \"89.3%\"}", + "likes": 599, + "dislikes": 47, + "stats": "{\"totalAccepted\": \"371.2K\", \"totalSubmission\": \"415.4K\", \"totalAcceptedRaw\": 371208, \"totalSubmissionRaw\": 415416, \"acRate\": \"89.4%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -89041,9 +89227,9 @@ "questionFrontendId": "2357", "title": "Make Array Zero by Subtracting Equal Amounts", "content": "
You are given a non-negative integer array nums
. In one operation, you must:
x
such that x
is less than or equal to the smallest non-zero element in nums
.x
from every positive element in nums
.Return the minimum number of operations to make every element in nums
equal to 0
.
\n
Example 1:
\n\n\nInput: nums = [1,5,0,3,5]\nOutput: 3\nExplanation:\nIn the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].\n\n\n
Example 2:
\n\n\nInput: nums = [0]\nOutput: 0\nExplanation: Each element in nums is already 0 so no operations are needed.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 100
You are given a positive integer array grades
which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:
ith
group is less than the sum of the grades of students in the (i + 1)th
group, for all groups (except the last).ith
group is less than the total number of students in the (i + 1)th
group, for all groups (except the last).Return the maximum number of groups that can be formed.
\n\n\n
Example 1:
\n\n\nInput: grades = [10,6,12,7,3,5]\nOutput: 3\nExplanation: The following is a possible way to form 3 groups of students:\n- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1\n- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2\n- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3\nIt can be shown that it is not possible to form more than 3 groups.\n\n\n
Example 2:
\n\n\nInput: grades = [8,8]\nOutput: 1\nExplanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.\n\n\n
\n
Constraints:
\n\n1 <= grades.length <= 105
1 <= grades[i] <= 105
You are given a directed graph of n
nodes numbered from 0
to n - 1
, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges
of size n
, indicating that there is a directed edge from node i
to node edges[i]
. If there is no outgoing edge from i
, then edges[i] == -1
.
You are also given two integers node1
and node2
.
Return the index of the node that can be reached from both node1
and node2
, such that the maximum between the distance from node1
to that node, and from node2
to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1
.
Note that edges
may contain cycles.
\n
Example 1:
\n\nInput: edges = [2,2,3,-1], node1 = 0, node2 = 1\nOutput: 2\nExplanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\nThe maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.\n\n\n
Example 2:
\n\nInput: edges = [1,2,-1], node1 = 0, node2 = 2\nOutput: 2\nExplanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\nThe maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.\n\n\n
\n
Constraints:
\n\nn == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
0 <= node1, node2 < n
You are given a directed graph of n
nodes numbered from 0
to n - 1
, where each node has at most one outgoing edge.
The graph is represented with a given 0-indexed array edges
of size n
, indicating that there is a directed edge from node i
to node edges[i]
. If there is no outgoing edge from node i
, then edges[i] == -1
.
Return the length of the longest cycle in the graph. If no cycle exists, return -1
.
A cycle is a path that starts and ends at the same node.
\n\n\n
Example 1:
\n\nInput: edges = [3,3,4,2,3]\nOutput: 3\nExplanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.\n\n\n
Example 2:
\n\nInput: edges = [2,-1,3,1]\nOutput: -1\nExplanation: There are no cycles in this graph.\n\n\n
\n
Constraints:
\n\nn == edges.length
2 <= n <= 105
-1 <= edges[i] < n
edges[i] != i
You are given two 2D integer arrays, items1
and items2
, representing two sets of items. Each array items
has the following properties:
items[i] = [valuei, weighti]
where valuei
represents the value and weighti
represents the weight of the ith
item.items
is unique.Return a 2D integer array ret
where ret[i] = [valuei, weighti]
, with weighti
being the sum of weights of all items with value valuei
.
Note: ret
should be returned in ascending order by value.
\n
Example 1:
\n\n\nInput: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]\nOutput: [[1,6],[3,9],[4,5]]\nExplanation: \nThe item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.\nThe item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.\nThe item with value = 4 occurs in items1 with weight = 5, total weight = 5. \nTherefore, we return [[1,6],[3,9],[4,5]].\n\n\n
Example 2:
\n\n\nInput: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]\nOutput: [[1,4],[2,4],[3,4]]\nExplanation: \nThe item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.\nThe item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.\nThe item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.\nTherefore, we return [[1,4],[2,4],[3,4]].\n\n
Example 3:
\n\n\nInput: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]\nOutput: [[1,7],[2,4],[7,1]]\nExplanation:\nThe item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. \nThe item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. \nThe item with value = 7 occurs in items2 with weight = 1, total weight = 1.\nTherefore, we return [[1,7],[2,4],[7,1]].\n\n\n
\n
Constraints:
\n\n1 <= items1.length, items2.length <= 1000
items1[i].length == items2[i].length == 2
1 <= valuei, weighti <= 1000
valuei
in items1
is unique.valuei
in items2
is unique.You are given a 0-indexed integer array nums
. A pair of indices (i, j)
is a bad pair if i < j
and j - i != nums[j] - nums[i]
.
Return the total number of bad pairs in nums
.
\n
Example 1:
\n\n\nInput: nums = [4,1,3,3]\nOutput: 5\nExplanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: There are no bad pairs.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed array of positive integers tasks
, representing tasks that need to be completed in order, where tasks[i]
represents the type of the ith
task.
You are also given a positive integer space
, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.
Each day, until all tasks have been completed, you must either:
\n\ntasks
, orReturn the minimum number of days needed to complete all tasks.
\n\n\n
Example 1:
\n\n\nInput: tasks = [1,2,1,2,3,1], space = 3\nOutput: 9\nExplanation:\nOne way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.\n\n\n
Example 2:
\n\n\nInput: tasks = [5,8,8,5], space = 2\nOutput: 6\nExplanation:\nOne way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.\n\n\n
\n
Constraints:
\n\n1 <= tasks.length <= 105
1 <= tasks[i] <= 109
1 <= space <= tasks.length
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.
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 number of operations to make an array that is sorted in non-decreasing order.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,9,3]\nOutput: 2\nExplanation: Here are the steps to sort the array in non-decreasing order:\n- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]\n- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]\nThere are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.\n\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: The array is already in non-decreasing order. Therefore, we return 0. \n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed, strictly increasing integer array nums
and a positive integer diff
. A triplet (i, j, k)
is an arithmetic triplet if the following conditions are met:
i < j < k
,nums[j] - nums[i] == diff
, andnums[k] - nums[j] == diff
.Return the number of unique arithmetic triplets.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,1,4,6,7,10], diff = 3\nOutput: 2\nExplanation:\n(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. \n\n\n
Example 2:
\n\n\nInput: nums = [4,5,6,7,8,9], diff = 2\nOutput: 2\nExplanation:\n(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 200
0 <= nums[i] <= 200
1 <= diff <= 50
nums
is strictly increasing.There is an undirected tree with n
nodes labeled from 0
to n - 1
and n - 1
edges.
You are given a 2D integer array edges
of length n - 1
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree. You are also given an integer array restricted
which represents restricted nodes.
Return the maximum number of nodes you can reach from node 0
without visiting a restricted node.
Note that node 0
will not be a restricted node.
\n
Example 1:
\n\nInput: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput: 4\nExplanation: The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\n
Example 2:
\n\nInput: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput: 3\nExplanation: The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.1 <= restricted.length < n
1 <= restricted[i] < n
restricted
are unique.You are given a 0-indexed integer array nums
. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
\n\n2,
equal elements. For example, the subarray [2,2]
is good.3,
equal elements. For example, the subarray [4,4,4]
is good.3
consecutive increasing elements, that is, the difference between adjacent elements is 1
. For example, the subarray [3,4,5]
is good, but the subarray [1,3,5]
is not.Return true
if the array has at least one valid partition. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: nums = [4,4,4,5,6]\nOutput: true\nExplanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,2]\nOutput: false\nExplanation: There is no valid partition for this array.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 106
You are given a string s
consisting of lowercase letters and an integer k
. We call a string t
ideal if the following conditions are satisfied:
t
is a subsequence of the string s
.t
is less than or equal to k
.Return the length of the longest ideal string.
\n\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
\n\nNote that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a'
and 'z'
is 25
, not 1
.
\n
Example 1:
\n\n\nInput: s = "acfgbd", k = 2\nOutput: 4\nExplanation: The longest ideal string is "acbd". The length of this string is 4, so 4 is returned.\nNote that "acfgbd" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.\n\n
Example 2:
\n\n\nInput: s = "abcd", k = 3\nOutput: 4\nExplanation: The longest ideal string is "abcd". The length of this string is 4, so 4 is returned.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
0 <= k <= 25
s
consists of lowercase English letters.You are given an n x n
integer matrix grid
.
Generate an integer matrix maxLocal
of size (n - 2) x (n - 2)
such that:
maxLocal[i][j]
is equal to the largest value of the 3 x 3
matrix in grid
centered around row i + 1
and column j + 1
.In other words, we want to find the largest value in every contiguous 3 x 3
matrix in grid
.
Return the generated matrix.
\n\n\n
Example 1:
\n\nInput: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]\nOutput: [[9,9],[8,6]]\nExplanation: The diagram above shows the original matrix and the generated matrix.\nNotice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.\n\n
Example 2:
\n\nInput: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]\nOutput: [[2,2,2],[2,2,2],[2,2,2]]\nExplanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
3 <= n <= 100
1 <= grid[i][j] <= 100
You are given a directed graph with n
nodes labeled from 0
to n - 1
, where each node has exactly one outgoing edge.
The graph is represented by a given 0-indexed integer array edges
of length n
, where edges[i]
indicates that there is a directed edge from node i
to node edges[i]
.
The edge score of a node i
is defined as the sum of the labels of all the nodes that have an edge pointing to i
.
Return the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.
\n\n\n
Example 1:
\n\nInput: edges = [1,0,0,0,0,7,7,5]\nOutput: 7\nExplanation:\n- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10.\n- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0.\n- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7.\n- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11.\nNode 7 has the highest edge score so return 7.\n\n\n
Example 2:
\n\nInput: edges = [2,0,0,2]\nOutput: 0\nExplanation:\n- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3.\n- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3.\nNodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.\n\n\n
\n
Constraints:
\n\nn == edges.length
2 <= n <= 105
0 <= edges[i] < n
edges[i] != i
You are given a 0-indexed string pattern
of length n
consisting of the characters 'I'
meaning increasing and 'D'
meaning decreasing.
A 0-indexed string num
of length n + 1
is created using the following conditions:
num
consists of the digits '1'
to '9'
, where each digit is used at most once.pattern[i] == 'I'
, then num[i] < num[i + 1]
.pattern[i] == 'D'
, then num[i] > num[i + 1]
.Return the lexicographically smallest possible string num
that meets the conditions.
\n
Example 1:
\n\n\nInput: pattern = "IIIDIDDD"\nOutput: "123549876"\nExplanation:\nAt indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].\nAt indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].\nSome possible values of num are "245639871", "135749862", and "123849765".\nIt can be proven that "123549876" is the smallest possible num that meets the conditions.\nNote that "123414321" is not possible because the digit '1' is used more than once.\n\n
Example 2:
\n\n\nInput: pattern = "DDD"\nOutput: "4321"\nExplanation:\nSome possible values of num are "9876", "7321", and "8742".\nIt can be proven that "4321" is the smallest possible num that meets the conditions.\n\n\n
\n
Constraints:
\n\n1 <= pattern.length <= 8
pattern
consists of only the letters 'I'
and 'D'
.We call a positive integer special if all of its digits are distinct.
\n\nGiven a positive integer n
, return the number of special integers that belong to the interval [1, n]
.
\n
Example 1:
\n\n\nInput: n = 20\nOutput: 19\nExplanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.\n\n\n
Example 2:
\n\n\nInput: n = 5\nOutput: 5\nExplanation: All the integers from 1 to 5 are special.\n\n\n
Example 3:
\n\n\nInput: n = 135\nOutput: 110\nExplanation: There are 110 integers from 1 to 135 that are special.\nSome of the integers that are not special are: 22, 114, and 131.\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 109
You are given a 0-indexed string blocks
of length n
, where blocks[i]
is either 'W'
or 'B'
, representing the color of the ith
block. The characters 'W'
and 'B'
denote the colors white and black, respectively.
You are also given an integer k
, which is the desired number of consecutive black blocks.
In one operation, you can recolor a white block such that it becomes a black block.
\n\nReturn the minimum number of operations needed such that there is at least one occurrence of k
consecutive black blocks.
\n
Example 1:
\n\n\nInput: blocks = "WBBWWBBWBW", k = 7\nOutput: 3\nExplanation:\nOne way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks\nso that blocks = "BBBBBBBWBW". \nIt can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.\nTherefore, we return 3.\n\n\n
Example 2:
\n\n\nInput: blocks = "WBWBBBW", k = 2\nOutput: 0\nExplanation:\nNo changes need to be made, since 2 consecutive black blocks already exist.\nTherefore, we return 0.\n\n\n
\n
Constraints:
\n\nn == blocks.length
1 <= n <= 100
blocks[i]
is either 'W'
or 'B'
.1 <= k <= n
You are given a binary string s
. In one second, all occurrences of "01"
are simultaneously replaced with "10"
. This process repeats until no occurrences of "01"
exist.
Return the number of seconds needed to complete this process.
\n\n\n
Example 1:
\n\n\nInput: s = "0110101"\nOutput: 4\nExplanation: \nAfter one second, s becomes "1011010".\nAfter another second, s becomes "1101100".\nAfter the third second, s becomes "1110100".\nAfter the fourth second, s becomes "1111000".\nNo occurrence of "01" exists any longer, and the process needed 4 seconds to complete,\nso we return 4.\n\n\n
Example 2:
\n\n\nInput: s = "11100"\nOutput: 0\nExplanation:\nNo occurrence of "01" exists in s, and the processes needed 0 seconds to complete,\nso we return 0.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is either '0'
or '1'
.\n
Follow up:
\n\nCan you solve this problem in O(n) time complexity?
\n", - "likes": 515, + "likes": 527, "dislikes": 113, - "stats": "{\"totalAccepted\": \"36.5K\", \"totalSubmission\": \"71K\", \"totalAcceptedRaw\": 36488, \"totalSubmissionRaw\": 71018, \"acRate\": \"51.4%\"}", + "stats": "{\"totalAccepted\": \"38.4K\", \"totalSubmission\": \"74.5K\", \"totalAcceptedRaw\": 38433, \"totalSubmissionRaw\": 74549, \"acRate\": \"51.6%\"}", "similarQuestions": "[{\"title\": \"Minimum Swaps to Group All 1's Together\", \"titleSlug\": \"minimum-swaps-to-group-all-1s-together\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Swaps to Group All 1's Together II\", \"titleSlug\": \"minimum-swaps-to-group-all-1s-together-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -89969,9 +90161,9 @@ "questionFrontendId": "2381", "title": "Shifting Letters II", "content": "You are given a string s
of lowercase English letters and a 2D integer array shifts
where shifts[i] = [starti, endi, directioni]
. For every i
, shift the characters in s
from the index starti
to the index endi
(inclusive) forward if directioni = 1
, or shift the characters backward if directioni = 0
.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z'
becomes 'a'
). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a'
becomes 'z'
).
Return the final string after all such shifts to s
are applied.
\n
Example 1:
\n\n\nInput: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]\nOutput: "ace"\nExplanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".\nSecondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".\nFinally, shift the characters from index 0 to index 2 forward. Now s = "ace".\n\n
Example 2:
\n\n\nInput: s = "dztz", shifts = [[0,0,0],[1,1,1]]\nOutput: "catz"\nExplanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".\nFinally, shift the characters from index 1 to index 1 forward. Now s = "catz".\n\n\n
\n
Constraints:
\n\n1 <= s.length, shifts.length <= 5 * 104
shifts[i].length == 3
0 <= starti <= endi < s.length
0 <= directioni <= 1
s
consists of lowercase English letters.You are given two 0-indexed integer arrays nums
and removeQueries
, both of length n
. For the ith
query, the element in nums
at the index removeQueries[i]
is removed, splitting nums
into different segments.
A segment is a contiguous sequence of positive integers in nums
. A segment sum is the sum of every element in a segment.
Return an integer array answer
, of length n
, where answer[i]
is the maximum segment sum after applying the ith
removal.
Note: The same index will not be removed more than once.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]\nOutput: [14,7,2,2,0]\nExplanation: Using 0 to indicate a removed element, the answer is as follows:\nQuery 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1].\nQuery 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].\nQuery 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. \nQuery 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. \nQuery 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.\nFinally, we return [14,7,2,2,0].\n\n
Example 2:
\n\n\nInput: nums = [3,2,11,1], removeQueries = [3,2,1,0]\nOutput: [16,5,3,0]\nExplanation: Using 0 to indicate a removed element, the answer is as follows:\nQuery 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].\nQuery 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].\nQuery 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].\nQuery 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.\nFinally, we return [16,5,3,0].\n\n\n
\n
Constraints:
\n\nn == nums.length == removeQueries.length
1 <= n <= 105
1 <= nums[i] <= 109
0 <= removeQueries[i] < n
removeQueries
are unique.You are entering a competition, and are given two positive integers initialEnergy
and initialExperience
denoting your initial energy and initial experience respectively.
You are also given two 0-indexed integer arrays energy
and experience
, both of length n
.
You will face n
opponents in order. The energy and experience of the ith
opponent is denoted by energy[i]
and experience[i]
respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available.
Defeating the ith
opponent increases your experience by experience[i]
, but decreases your energy by energy[i]
.
Before starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one.
\n\nReturn the minimum number of training hours required to defeat all n
opponents.
\n
Example 1:
\n\n\nInput: initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]\nOutput: 8\nExplanation: You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.\nYou face the opponents in the following order:\n- You have more energy and experience than the 0th opponent so you win.\n Your energy becomes 11 - 1 = 10, and your experience becomes 5 + 2 = 7.\n- You have more energy and experience than the 1st opponent so you win.\n Your energy becomes 10 - 4 = 6, and your experience becomes 7 + 6 = 13.\n- You have more energy and experience than the 2nd opponent so you win.\n Your energy becomes 6 - 3 = 3, and your experience becomes 13 + 3 = 16.\n- You have more energy and experience than the 3rd opponent so you win.\n Your energy becomes 3 - 2 = 1, and your experience becomes 16 + 1 = 17.\nYou did a total of 6 + 2 = 8 hours of training before the competition, so we return 8.\nIt can be proven that no smaller answer exists.\n\n\n
Example 2:
\n\n\nInput: initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]\nOutput: 0\nExplanation: You do not need any additional energy or experience to win the competition, so we return 0.\n\n\n
\n
Constraints:
\n\nn == energy.length == experience.length
1 <= n <= 100
1 <= initialEnergy, initialExperience, energy[i], experience[i] <= 100
You are given a string num
consisting of digits only.
Return the largest palindromic integer (in the form of a string) that can be formed using digits taken from num
. It should not contain leading zeroes.
Notes:
\n\nnum
, but you must use at least one digit.\n
Example 1:
\n\n\nInput: num = "444947137"\nOutput: "7449447"\nExplanation: \nUse the digits "4449477" from "444947137" to form the palindromic integer "7449447".\nIt can be shown that "7449447" is the largest palindromic integer that can be formed.\n\n\n
Example 2:
\n\n\nInput: num = "00009"\nOutput: "9"\nExplanation: \nIt can be shown that "9" is the largest palindromic integer that can be formed.\nNote that the integer returned should not contain leading zeroes.\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 105
num
consists of digits.You are given the root
of a binary tree with unique values, and an integer start
. At minute 0
, an infection starts from the node with value start
.
Each minute, a node becomes infected if:
\n\nReturn the number of minutes needed for the entire tree to be infected.
\n\n\n
Example 1:
\n\nInput: root = [1,5,3,null,4,10,6,9,2], start = 3\nOutput: 4\nExplanation: The following nodes are infected during:\n- Minute 0: Node 3\n- Minute 1: Nodes 1, 10 and 6\n- Minute 2: Node 5\n- Minute 3: Node 4\n- Minute 4: Nodes 9 and 2\nIt takes 4 minutes for the whole tree to be infected so we return 4.\n\n\n
Example 2:
\n\nInput: root = [1], start = 1\nOutput: 0\nExplanation: At minute 0, the only node in the tree is infected so we return 0.\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 105
start
exists in the tree.You are given an integer array nums
and a positive integer k
. You can choose any subsequence of the array and sum all of its elements together.
We define the K-Sum of the array as the kth
largest subsequence sum that can be obtained (not necessarily distinct).
Return the K-Sum of the array.
\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\nNote that the empty subsequence is considered to have a sum of 0
.
\n
Example 1:
\n\n\nInput: nums = [2,4,-2], k = 5\nOutput: 2\nExplanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:\n- 6, 4, 4, 2, 2, 0, 0, -2.\nThe 5-Sum of the array is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,-2,3,4,-10,12], k = 16\nOutput: 10\nExplanation: The 16-Sum of the array is 10.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
-109 <= nums[i] <= 109
1 <= k <= min(2000, 2n)
You are given an integer array nums
of length n
, and an integer array queries
of length m
.
Return an array answer
of length m
where answer[i]
is the maximum size of a subsequence that you can take from nums
such that the sum of its elements is less than or equal to queries[i]
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,5,2,1], queries = [3,10,21]\nOutput: [2,3,4]\nExplanation: We answer the queries as follows:\n- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.\n- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.\n- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,4,5], queries = [1]\nOutput: [0]\nExplanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.\n\n
\n
Constraints:
\n\nn == nums.length
m == queries.length
1 <= n, m <= 1000
1 <= nums[i], queries[i] <= 106
You are given a string s
, which contains stars *
.
In one operation, you can:
\n\ns
.Return the string after all stars have been removed.
\n\nNote:
\n\n\n
Example 1:
\n\n\nInput: s = "leet**cod*e"\nOutput: "lecoe"\nExplanation: Performing the removals from left to right:\n- The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".\n- The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".\n- The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".\nThere are no more stars, so we return "lecoe".\n\n
Example 2:
\n\n\nInput: s = "erase*****"\nOutput: ""\nExplanation: The entire string is removed, so we return an empty string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters and stars *
.s
.You are given a 0-indexed array of strings garbage
where garbage[i]
represents the assortment of garbage at the ith
house. garbage[i]
consists only of the characters 'M'
, 'P'
and 'G'
representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1
minute.
You are also given a 0-indexed integer array travel
where travel[i]
is the number of minutes needed to go from house i
to house i + 1
.
There are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0
and must visit each house in order; however, they do not need to visit every house.
Only one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.
\n\nReturn the minimum number of minutes needed to pick up all the garbage.
\n\n\n
Example 1:
\n\n\nInput: garbage = ["G","P","GP","GG"], travel = [2,4,3]\nOutput: 21\nExplanation:\nThe paper garbage truck:\n1. Travels from house 0 to house 1\n2. Collects the paper garbage at house 1\n3. Travels from house 1 to house 2\n4. Collects the paper garbage at house 2\nAltogether, it takes 8 minutes to pick up all the paper garbage.\nThe glass garbage truck:\n1. Collects the glass garbage at house 0\n2. Travels from house 0 to house 1\n3. Travels from house 1 to house 2\n4. Collects the glass garbage at house 2\n5. Travels from house 2 to house 3\n6. Collects the glass garbage at house 3\nAltogether, it takes 13 minutes to pick up all the glass garbage.\nSince there is no metal garbage, we do not need to consider the metal garbage truck.\nTherefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.\n\n\n
Example 2:
\n\n\nInput: garbage = ["MMM","PGM","GP"], travel = [3,10]\nOutput: 37\nExplanation:\nThe metal garbage truck takes 7 minutes to pick up all the metal garbage.\nThe paper garbage truck takes 15 minutes to pick up all the paper garbage.\nThe glass garbage truck takes 15 minutes to pick up all the glass garbage.\nIt takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.\n\n\n
\n
Constraints:
\n\n2 <= garbage.length <= 105
garbage[i]
consists of only the letters 'M'
, 'P'
, and 'G'
.1 <= garbage[i].length <= 10
travel.length == garbage.length - 1
1 <= travel[i] <= 100
You are given a positive integer k
. You are also given:
rowConditions
of size n
where rowConditions[i] = [abovei, belowi]
, andcolConditions
of size m
where colConditions[i] = [lefti, righti]
.The two arrays contain integers from 1
to k
.
You have to build a k x k
matrix that contains each of the numbers from 1
to k
exactly once. The remaining cells should have the value 0
.
The matrix should also satisfy the following conditions:
\n\nabovei
should appear in a row that is strictly above the row at which the number belowi
appears for all i
from 0
to n - 1
.lefti
should appear in a column that is strictly left of the column at which the number righti
appears for all i
from 0
to m - 1
.Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
\n\n\n
Example 1:
\n\nInput: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]\nOutput: [[3,0,0],[0,0,1],[0,2,0]]\nExplanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.\nThe row conditions are the following:\n- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.\n- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.\nThe column conditions are the following:\n- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.\n- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.\nNote that there may be multiple correct answers.\n\n\n
Example 2:
\n\n\nInput: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]\nOutput: []\nExplanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.\nNo matrix can satisfy all the conditions, so we return the empty matrix.\n\n\n
\n
Constraints:
\n\n2 <= k <= 400
1 <= rowConditions.length, colConditions.length <= 104
rowConditions[i].length == colConditions[i].length == 2
1 <= abovei, belowi, lefti, righti <= k
abovei != belowi
lefti != righti
Given a 0-indexed integer array nums
, determine whether there exist two subarrays of length 2
with equal sum. Note that the two subarrays must begin at different indices.
Return true
if these subarrays exist, and false
otherwise.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,2,4]\nOutput: true\nExplanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: false\nExplanation: No two subarrays of size 2 have the same sum.\n\n\n
Example 3:
\n\n\nInput: nums = [0,0,0]\nOutput: true\nExplanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. \nNote that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 1000
-109 <= nums[i] <= 109
An integer n
is strictly palindromic if, for every base b
between 2
and n - 2
(inclusive), the string representation of the integer n
in base b
is palindromic.
Given an integer n
, return true
if n
is strictly palindromic and false
otherwise.
A string is palindromic if it reads the same forward and backward.
\n\n\n
Example 1:
\n\n\nInput: n = 9\nOutput: false\nExplanation: In base 2: 9 = 1001 (base 2), which is palindromic.\nIn base 3: 9 = 100 (base 3), which is not palindromic.\nTherefore, 9 is not strictly palindromic so we return false.\nNote that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.\n\n\n
Example 2:
\n\n\nInput: n = 4\nOutput: false\nExplanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.\nTherefore, we return false.\n\n\n\n
\n
Constraints:
\n\n4 <= n <= 105
You are given an m x n
binary matrix matrix
and an integer numSelect
.
Your goal is to select exactly numSelect
distinct columns from matrix
such that you cover as many rows as possible.
A row is considered covered if all the 1
's in that row are also part of a column that you have selected. If a row does not have any 1
s, it is also considered covered.
More formally, let us consider selected = {c1, c2, ...., cnumSelect}
as the set of columns selected by you. A row i
is covered by selected
if:
matrix[i][j] == 1
, the column j
is in selected
.i
has a value of 1
.Return the maximum number of rows that can be covered by a set of numSelect
columns.
\n
Example 1:
\n\nInput: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2
\n\nOutput: 3
\n\nExplanation:
\n\nOne possible way to cover 3 rows is shown in the diagram above.
\nWe choose s = {0, 2}.
\n- Row 0 is covered because it has no occurrences of 1.
\n- Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s.
\n- Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s.
\n- Row 3 is covered because matrix[2][2] == 1 and 2 is present in s.
\nThus, we can cover three rows.
\nNote that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.
Example 2:
\n\nInput: matrix = [[1],[0]], numSelect = 1
\n\nOutput: 2
\n\nExplanation:
\n\nSelecting the only column will result in both rows being covered since the entire matrix is selected.
\n\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
1 <= m, n <= 12
matrix[i][j]
is either 0
or 1
.1 <= numSelect <= n
You have n
robots. You are given two 0-indexed integer arrays, chargeTimes
and runningCosts
, both of length n
. The ith
robot costs chargeTimes[i]
units to charge and costs runningCosts[i]
units to run. You are also given an integer budget
.
The total cost of running k
chosen robots is equal to max(chargeTimes) + k * sum(runningCosts)
, where max(chargeTimes)
is the largest charge cost among the k
robots and sum(runningCosts)
is the sum of running costs among the k
robots.
Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget
.
\n
Example 1:
\n\n\nInput: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25\nOutput: 3\nExplanation: \nIt is possible to run all individual and consecutive pairs of robots within budget.\nTo obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25.\nIt can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.\n\n\n
Example 2:
\n\n\nInput: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19\nOutput: 0\nExplanation: No robot can be run that does not exceed the budget, so we return 0.\n\n\n
\n
Constraints:
\n\nchargeTimes.length == runningCosts.length == n
1 <= n <= 5 * 104
1 <= chargeTimes[i], runningCosts[i] <= 105
1 <= budget <= 1015
You are given a 0-indexed string s
consisting of only lowercase English letters, where each letter in s
appears exactly twice. You are also given a 0-indexed integer array distance
of length 26
.
Each letter in the alphabet is numbered from 0
to 25
(i.e. 'a' -> 0
, 'b' -> 1
, 'c' -> 2
, ... , 'z' -> 25
).
In a well-spaced string, the number of letters between the two occurrences of the ith
letter is distance[i]
. If the ith
letter does not appear in s
, then distance[i]
can be ignored.
Return true
if s
is a well-spaced string, otherwise return false
.
\n
Example 1:
\n\n\nInput: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: true\nExplanation:\n- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.\n- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.\n- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.\nNote that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.\nReturn true because s is a well-spaced string.\n\n\n
Example 2:
\n\n\nInput: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: false\nExplanation:\n- 'a' appears at indices 0 and 1 so there are zero letters between them.\nBecause distance[0] = 1, s is not a well-spaced string.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 52
s
consists only of lowercase English letters.s
exactly twice.distance.length == 26
0 <= distance[i] <= 50
You are given two positive integers startPos
and endPos
. Initially, you are standing at position startPos
on an infinite number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer k
, return the number of different ways to reach the position endPos
starting from startPos
, such that you perform exactly k
steps. Since the answer may be very large, return it modulo 109 + 7
.
Two ways are considered different if the order of the steps made is not exactly the same.
\n\nNote that the number line includes negative integers.
\n\n\n
Example 1:
\n\n\nInput: startPos = 1, endPos = 2, k = 3\nOutput: 3\nExplanation: We can reach position 2 from 1 in exactly 3 steps in three ways:\n- 1 -> 2 -> 3 -> 2.\n- 1 -> 2 -> 1 -> 2.\n- 1 -> 0 -> 1 -> 2.\nIt can be proven that no other way is possible, so we return 3.\n\n
Example 2:
\n\n\nInput: startPos = 2, endPos = 5, k = 10\nOutput: 0\nExplanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.\n\n\n
\n
Constraints:
\n\n1 <= startPos, endPos, k <= 1000
You are given an array nums
consisting of positive integers.
We call a subarray of nums
nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0
.
Return the length of the longest nice subarray.
\n\nA subarray is a contiguous part of an array.
\n\nNote that subarrays of length 1
are always considered nice.
\n
Example 1:
\n\n\nInput: nums = [1,3,8,48,10]\nOutput: 3\nExplanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:\n- 3 AND 8 = 0.\n- 3 AND 48 = 0.\n- 8 AND 48 = 0.\nIt can be proven that no longer nice subarray can be obtained, so we return 3.\n\n
Example 2:
\n\n\nInput: nums = [3,1,5,11,13]\nOutput: 1\nExplanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
x <= 109
only has 30 bits, hence the length of the longest nice subarray cannot exceed 30."
],
"topicTags": [
{
@@ -90775,8 +90967,11 @@
"companyTags": null,
"difficulty": "Medium",
"isPaidOnly": false,
- "solution": null,
- "hasSolution": false,
+ "solution": {
+ "canSeeDetail": true,
+ "content": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Brute Force\n\n#### Intuition\n\nOur task is to find the longest contiguous sequence in the array where the bitwise AND of any two elements is 0. First, let's understand what makes a subarray \"nice\" according to the given definition. A nice subarray is one where the bitwise AND of any two distinct elements equals zero. This means that for any pair of numbers in our subarray, their binary representations must not have any overlapping set bits (`1`s in the same positions).\n\nWhen two numbers have no overlapping set bits, we can say they are \"bit-disjoint.\" For example, 5 (`101` in binary) and 7 (`111` in binary) are not bit-disjoint since they both have a `1` in the first and third positions from the right. However, 5 (`101`) and 8 (`1000`) are bit-disjoint since they have no `1`s in the same bit positions.\n\nA brute force approach would be to try each possible starting position and extend the subarray as far as possible. We can keep a running counter `maxLength` which can store the longest subarray we encounter in the traversals. But how do we efficiently check whether a subarray is \"nice\"?\n\nOne approach would be to examine each subarray using nested loops to check if they are \"nice.\" However, this would have a quadratic complexity just to identify each subarray, making it too slow for the given constraints.\n\nThe key insight is that we need to track which bit positions are already \"used\" within our current subarray. If a new number wants to join our nice subarray, it must not have any bits set in positions that are already used by other numbers in the subarray.\n\nA **bitmask** is the perfect tool for this job. As we traverse a potential subarray, we maintain a single integer (the bitmask) where each bit represents whether that position has been \"used\" by any number so far.\n\nFor example, consider numbers 4 (`100` in binary), 2 (`010` in binary), and 1 (`001` in binary). When considering a new element, we test if any of its bits overlap with our existing bitmask. If there is an overlap, the subarray is no longer \"nice\" since two numbers now share a set bit.\n\nOtherwise, we add the current number's bits into our bitmask using the OR operation. This operation updates our tracking of occupied bit positions. \n\nAfter updating our bitmask, we increment our current subarray length and continue this process until we encounter a number that conflicts with our existing bits. Once we find such a number, we update our `maxLength` if the current subarray is longer than any we've seen before, and then we start a new potential nice subarray from the next position.\n\n> For a more comprehensive understanding of bit manipulation, check out the [Bit Manipulation Explore Card](https://leetcode.com/explore/learn/card/bit-manipulation/). This resource provides an in-depth look at bit-level operations, explaining their key concepts and applications with a variety of problems to solidify understanding of the pattern.\n\n#### Algorithm\n\n- Initialize a variable `maxLength` to `1`, which will track the maximum nice subarray length found.\n- Iterate through each possible starting position `start` in the array, up to the length minus the current `maxLength`:\n - Initialize variables:\n - `currentLength` to `1`, which represents the length of the current nice subarray.\n - `usedBits` to the value at the current starting position, which tracks which bits are used in our subarray.\n - Iterate through subsequent positions `end` in the array, starting from the position after `start`. For each position:\n - If the bitwise AND of the `usedBits` and the value at the current position is `0`:\n - Update `usedBits` by performing a bitwise OR with the value at the current position.\n - Increment `currentLength` by `1`.\n - If it is not `0`, break the inner loop since we can't extend the nice subarray further.\n - Update `maxLength` to be the maximum of the current `maxLength` and `currentLength`.\n- Return `maxLength` as the result.\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`.\n\n- Time complexity: $O(n^2)$\n\n The algorithm uses two nested loops. The outer loop iterates through all possible starting positions, which is $O(n)$. For each starting position, the inner loop can potentially iterate through all remaining elements in the worst case, which is also $O(n)$. Therefore, the overall time complexity is $O(n^2)$.\n\n- Space complexity: $O(1)$\n\n The algorithm only uses a constant amount of extra space regardless of the input size. It maintains a few variables (`maxLength`, `currentLength`, `usedBits`) that do not scale with the input size, so the space complexity is $O(1)$.\n\n---\n\n### Approach 2: Sliding Window\n\n#### Intuition\n\nOur previous approach examined all possible starting positions and extended each subarray as far as possible. Now, let's try a more efficient technique. We'll build our solution by taking larger and larger subarrays until adding a new element breaks the \"nice\" property. When this happens, we need to remove elements from the beginning until we restore that property.\n\nThis idea naturally translates to a variable-size sliding window approach. To check the validity of each window, we can use a similar concept as the previous approach, by using a bitmask to store all the bits already used in the window (let's call it `usedBits`). \n\nWe start with an empty window and expand it by adding elements one by one. Each time we add a new element, we check whether it conflicts with our existing window by seeing if any of its bits overlap with `usedBits`. If there is an overlap, the subarray is no longer \"nice\" because two elements now share a set bit. \n\nWhen a conflict occurs, we shrink the window from the left by removing elements until the conflict is resolved. Each time we remove an element, we clear its bits from the `usedBits` tracker by XOR'ing it with the element being removed. \n\nThroughout this process, we maintain a variable `maxLength` to track the longest \"nice\" subarray we have found. Whenever we expand the window without conflicts, we update `maxLength`. By the end of the iteration, `maxLength` will contain the length of the longest valid subarray.\n\nHere's a slideshow to demonstrate this algorithm in action:\n\n!?!../Documents/2401/slideshow.json:682,602!?!\n\n> For a more comprehensive understanding of the sliding window technique, check out the [Sliding Window Explore Card](https://leetcode.com/explore/learn/card/array-and-string/204/sliding-window/). This resource provides an in-depth look at the sliding window approach, explaining its key concepts and applications with a variety of problems to solidify understanding of the pattern.\n\n#### Algorithm\n\n- Initialize variables:\n - `usedBits` to `0`, which tracks the bits currently used in the sliding window.\n - `windowStart` to `0`, representing the starting position of the current window.\n - `maxLength` to `0`, which will store the length of the longest nice subarray found.\n- Iterate through the array with a variable `windowEnd` from `0` to the length of `nums`:\n - While the current number at `windowEnd` shares any bits with the `usedBits` (their bitwise AND is not 0):\n - Remove the bits of the leftmost element in the window from `usedBits` using bitwise XOR.\n - Increment `windowStart` to shrink the window from the left.\n - Add the bits of the current number to `usedBits` using bitwise OR.\n - Update `maxLength` to the maximum of the current `maxLength` and the current window size (calculated as `windowEnd - windowStart + 1`).\n- Return the final `maxLength`.\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the length of the input array `nums`. \n\n- Time complexity: $O(n)$ \n\n The algorithm maintains a sliding window that dynamically adjusts its size to ensure the subarray remains nice. Each element is added to the window at most once and removed at most once, resulting in a total of $O(n)$ operations. The bitwise operations inside the loop run in constant time per element, keeping the overall complexity linear. \n\n- Space complexity: $O(1)$ \n\n The algorithm uses only a few integer variables (`usedBits`, `windowStart`, and `maxLength`), all of which require constant space. Since no additional data structures are used that grow with $n$, the space complexity remains constant.\n\n---"
+ },
+ "hasSolution": true,
"hasVideoSolution": false,
"url": "https://leetcode.com/problems/longest-nice-subarray/"
}
@@ -90789,9 +90984,9 @@
"questionFrontendId": "2402",
"title": "Meeting Rooms III",
"content": "You are given an integer n
. There are n
rooms numbered from 0
to n - 1
.
You are given a 2D integer array meetings
where meetings[i] = [starti, endi]
means that a meeting will be held during the half-closed time interval [starti, endi)
. All the values of starti
are unique.
Meetings are allocated to rooms in the following manner:
\n\nReturn the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
\n\nA half-closed interval [a, b)
is the interval between a
and b
including a
and not including b
.
\n
Example 1:
\n\n\nInput: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]\nOutput: 0\nExplanation:\n- At time 0, both rooms are not being used. The first meeting starts in room 0.\n- At time 1, only room 1 is not being used. The second meeting starts in room 1.\n- At time 2, both rooms are being used. The third meeting is delayed.\n- At time 3, both rooms are being used. The fourth meeting is delayed.\n- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).\n- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).\nBoth rooms 0 and 1 held 2 meetings, so we return 0. \n\n\n
Example 2:
\n\n\nInput: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]\nOutput: 1\nExplanation:\n- At time 1, all three rooms are not being used. The first meeting starts in room 0.\n- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.\n- At time 3, only room 2 is not being used. The third meeting starts in room 2.\n- At time 4, all three rooms are being used. The fourth meeting is delayed.\n- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).\n- At time 6, all three rooms are being used. The fifth meeting is delayed.\n- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).\nRoom 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. \n\n\n
\n
Constraints:
\n\n1 <= n <= 100
1 <= meetings.length <= 105
meetings[i].length == 2
0 <= starti < endi <= 5 * 105
starti
are unique.Given an integer array nums
, return the most frequent even element.
If there is a tie, return the smallest one. If there is no such element, return -1
.
\n
Example 1:
\n\n\nInput: nums = [0,1,2,2,4,4,1]\nOutput: 2\nExplanation:\nThe even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.\nWe return the smallest one, which is 2.\n\n
Example 2:
\n\n\nInput: nums = [4,4,4,9,2,4]\nOutput: 4\nExplanation: 4 is the even element appears the most.\n\n\n
Example 3:
\n\n\nInput: nums = [29,47,21,41,13,37,25,7]\nOutput: -1\nExplanation: There is no even element.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2000
0 <= nums[i] <= 105
Given a string s
, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the minimum number of substrings in such a partition.
\n\nNote that each character should belong to exactly one substring in a partition.
\n\n\n
Example 1:
\n\n\nInput: s = "abacaba"\nOutput: 4\nExplanation:\nTwo possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").\nIt can be shown that 4 is the minimum number of substrings needed.\n\n\n
Example 2:
\n\n\nInput: s = "ssssss"\nOutput: 6\nExplanation:\nThe only valid partition is ("s","s","s","s","s","s").\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only English lowercase letters.You are given a 2D integer array intervals
where intervals[i] = [lefti, righti]
represents the inclusive interval [lefti, righti]
.
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
\n\nReturn the minimum number of groups you need to make.
\n\nTwo intervals intersect if there is at least one common number between them. For example, the intervals [1, 5]
and [5, 8]
intersect.
\n
Example 1:
\n\n\nInput: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]\nOutput: 3\nExplanation: We can divide the intervals into the following groups:\n- Group 1: [1, 5], [6, 8].\n- Group 2: [2, 3], [5, 10].\n- Group 3: [1, 10].\nIt can be proven that it is not possible to divide the intervals into fewer than 3 groups.\n\n\n
Example 2:
\n\n\nInput: intervals = [[1,3],[5,6],[8,10],[11,13]]\nOutput: 1\nExplanation: None of the intervals overlap, so we can put all of them in one group.\n\n\n
\n
Constraints:
\n\n1 <= intervals.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 106
You are given an integer array nums
and an integer k
.
Find the longest subsequence of nums
that meets the following requirements:
k
.Return the length of the longest subsequence that meets the requirements.
\n\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,2,1,4,3,4,5,8,15], k = 3\nOutput: 5\nExplanation:\nThe longest subsequence that meets the requirements is [1,3,4,5,8].\nThe subsequence has a length of 5, so we return 5.\nNote that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.\n\n\n
Example 2:
\n\n\nInput: nums = [7,4,5,1,8,12,4,7], k = 5\nOutput: 4\nExplanation:\nThe longest subsequence that meets the requirements is [4,5,8,12].\nThe subsequence has a length of 4, so we return 4.\n\n\n
Example 3:
\n\n\nInput: nums = [1,5], k = 1\nOutput: 1\nExplanation:\nThe longest subsequence that meets the requirements is [1].\nThe subsequence has a length of 1, so we return 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i], k <= 105
Alice and Bob are traveling to Rome for separate business meetings.
\n\nYou are given 4 strings arriveAlice
, leaveAlice
, arriveBob
, and leaveBob
. Alice will be in the city from the dates arriveAlice
to leaveAlice
(inclusive), while Bob will be in the city from the dates arriveBob
to leaveBob
(inclusive). Each will be a 5-character string in the format "MM-DD"
, corresponding to the month and day of the date.
Return the total number of days that Alice and Bob are in Rome together.
\n\nYou can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
.
\n
Example 1:
\n\n\nInput: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19"\nOutput: 3\nExplanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.\n\n\n
Example 2:
\n\n\nInput: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31"\nOutput: 0\nExplanation: There is no day when Alice and Bob are in Rome together, so we return 0.\n\n\n
\n
Constraints:
\n\n"MM-DD"
.You are given a 0-indexed integer array players
, where players[i]
represents the ability of the ith
player. You are also given a 0-indexed integer array trainers
, where trainers[j]
represents the training capacity of the jth
trainer.
The ith
player can match with the jth
trainer if the player's ability is less than or equal to the trainer's training capacity. Additionally, the ith
player can be matched with at most one trainer, and the jth
trainer can be matched with at most one player.
Return the maximum number of matchings between players
and trainers
that satisfy these conditions.
\n
Example 1:
\n\n\nInput: players = [4,7,9], trainers = [8,2,5,8]\nOutput: 2\nExplanation:\nOne of the ways we can form two matchings is as follows:\n- players[0] can be matched with trainers[0] since 4 <= 8.\n- players[1] can be matched with trainers[3] since 7 <= 8.\nIt can be proven that 2 is the maximum number of matchings that can be formed.\n\n\n
Example 2:
\n\n\nInput: players = [1,1,1], trainers = [10]\nOutput: 1\nExplanation:\nThe trainer can be matched with any of the 3 players.\nEach player can only be matched with one trainer, so the maximum answer is 1.\n\n\n
\n
Constraints:
\n\n1 <= players.length, trainers.length <= 105
1 <= players[i], trainers[j] <= 109
\n
Note: This question is the same as 445: Assign Cookies.
\n", - "likes": 540, - "dislikes": 17, - "stats": "{\"totalAccepted\": \"46.2K\", \"totalSubmission\": \"70.3K\", \"totalAcceptedRaw\": 46240, \"totalSubmissionRaw\": 70280, \"acRate\": \"65.8%\"}", + "likes": 577, + "dislikes": 19, + "stats": "{\"totalAccepted\": \"54K\", \"totalSubmission\": \"80.2K\", \"totalAcceptedRaw\": 54019, \"totalSubmissionRaw\": 80173, \"acRate\": \"67.4%\"}", "similarQuestions": "[{\"title\": \"Most Profit Assigning Work\", \"titleSlug\": \"most-profit-assigning-work\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Long Pressed Name\", \"titleSlug\": \"long-pressed-name\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Interval List Intersections\", \"titleSlug\": \"interval-list-intersections\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Largest Merge Of Two Strings\", \"titleSlug\": \"largest-merge-of-two-strings\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximum Number of Tasks You Can Assign\", \"titleSlug\": \"maximum-number-of-tasks-you-can-assign\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Successful Pairs of Spells and Potions\", \"titleSlug\": \"successful-pairs-of-spells-and-potions\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"The Latest Time to Catch a Bus\", \"titleSlug\": \"the-latest-time-to-catch-a-bus\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Maximize Greatness of an Array\", \"titleSlug\": \"maximize-greatness-of-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -91169,9 +91364,9 @@ "questionFrontendId": "2411", "title": "Smallest Subarrays With Maximum Bitwise OR", "content": "You are given a 0-indexed array nums
of length n
, consisting of non-negative integers. For each index i
from 0
to n - 1
, you must determine the size of the minimum sized non-empty subarray of nums
starting at i
(inclusive) that has the maximum possible bitwise OR.
Bij
be the bitwise OR of the subarray nums[i...j]
. You need to find the smallest subarray starting at i
, such that bitwise OR of this subarray is equal to max(Bik)
where i <= k <= n - 1
.The bitwise OR of an array is the bitwise OR of all the numbers in it.
\n\nReturn an integer array answer
of size n
where answer[i]
is the length of the minimum sized subarray starting at i
with maximum bitwise OR.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,0,2,1,3]\nOutput: [3,3,2,2,1]\nExplanation:\nThe maximum possible bitwise OR starting at any index is 3. \n- Starting at index 0, the shortest subarray that yields it is [1,0,2].\n- Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1].\n- Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1].\n- Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3].\n- Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3].\nTherefore, we return [3,3,2,2,1]. \n\n\n
Example 2:
\n\n\nInput: nums = [1,2]\nOutput: [2,1]\nExplanation:\nStarting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.\nStarting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.\nTherefore, we return [2,1].\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
0 <= nums[i] <= 109
You are given a 0-indexed 2D integer array transactions
, where transactions[i] = [costi, cashbacki]
.
The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money
. In order to complete transaction i
, money >= costi
must hold true. After performing a transaction, money
becomes money - costi + cashbacki
.
Return the minimum amount of money
required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.
\n
Example 1:
\n\n\nInput: transactions = [[2,1],[5,0],[4,2]]\nOutput: 10\nExplanation:\nStarting with money = 10, the transactions can be performed in any order.\nIt can be shown that starting with money < 10 will fail to complete all transactions in some order.\n\n\n
Example 2:
\n\n\nInput: transactions = [[3,0],[0,3]]\nOutput: 3\nExplanation:\n- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3.\n- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0.\nThus, starting with money = 3, the transactions can be performed in any order.\n\n\n
\n
Constraints:
\n\n1 <= transactions.length <= 105
transactions[i].length == 2
0 <= costi, cashbacki <= 109
n
, return the smallest positive integer that is a multiple of both 2
and n
.\n\n
Example 1:
\n\n\nInput: n = 5\nOutput: 10\nExplanation: The smallest multiple of both 5 and 2 is 10.\n\n\n
Example 2:
\n\n\nInput: n = 6\nOutput: 6\nExplanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.\n\n\n
\n
Constraints:
\n\n1 <= n <= 150
An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz"
.
"abc"
is an alphabetical continuous string, while "acb"
and "za"
are not.Given a string s
consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.
\n
Example 1:
\n\n\nInput: s = "abacaba"\nOutput: 2\nExplanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".\n"ab" is the longest continuous substring.\n\n\n
Example 2:
\n\n\nInput: s = "abcde"\nOutput: 5\nExplanation: "abcde" is the longest continuous substring.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only English lowercase letters.Given the root
of a perfect binary tree, reverse the node values at each odd level of the tree.
[2,1,3,4,7,11,29,18]
, then it should become [18,29,11,7,4,3,1,2]
.Return the root of the reversed tree.
\n\nA binary tree is perfect if all parent nodes have two children and all leaves are on the same level.
\n\nThe level of a node is the number of edges along the path between it and the root node.
\n\n\n
Example 1:
\n\nInput: root = [2,3,5,8,13,21,34]\nOutput: [2,5,3,8,13,21,34]\nExplanation: \nThe tree has only one odd level.\nThe nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.\n\n\n
Example 2:
\n\nInput: root = [7,13,11]\nOutput: [7,11,13]\nExplanation: \nThe nodes at level 1 are 13, 11, which are reversed and become 11, 13.\n\n\n
Example 3:
\n\n\nInput: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]\nOutput: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]\nExplanation: \nThe odd levels have non-zero values.\nThe nodes at level 1 were 1, 2, and are 2, 1 after the reversal.\nThe nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.\n\n\n
\n
Constraints:
\n\n[1, 214]
.0 <= Node.val <= 105
root
is a perfect binary tree.You are given an array words
of size n
consisting of non-empty strings.
We define the score of a string term
as the number of strings words[i]
such that term
is a prefix of words[i]
.
words = ["a", "ab", "abc", "cab"]
, then the score of "ab"
is 2
, since "ab"
is a prefix of both "ab"
and "abc"
.Return an array answer
of size n
where answer[i]
is the sum of scores of every non-empty prefix of words[i]
.
Note that a string is considered as a prefix of itself.
\n\n\n
Example 1:
\n\n\nInput: words = ["abc","ab","bc","b"]\nOutput: [5,4,3,2]\nExplanation: The answer for each string is the following:\n- "abc" has 3 prefixes: "a", "ab", and "abc".\n- There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc".\nThe total is answer[0] = 2 + 2 + 1 = 5.\n- "ab" has 2 prefixes: "a" and "ab".\n- There are 2 strings with the prefix "a", and 2 strings with the prefix "ab".\nThe total is answer[1] = 2 + 2 = 4.\n- "bc" has 2 prefixes: "b" and "bc".\n- There are 2 strings with the prefix "b", and 1 string with the prefix "bc".\nThe total is answer[2] = 2 + 1 = 3.\n- "b" has 1 prefix: "b".\n- There are 2 strings with the prefix "b".\nThe total is answer[3] = 2.\n\n\n
Example 2:
\n\n\nInput: words = ["abcd"]\nOutput: [4]\nExplanation:\n"abcd" has 4 prefixes: "a", "ab", "abc", and "abcd".\nEach prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i]
consists of lowercase English letters.You are given an array of strings names
, and an array heights
that consists of distinct positive integers. Both arrays are of length n
.
For each index i
, names[i]
and heights[i]
denote the name and height of the ith
person.
Return names
sorted in descending order by the people's heights.
\n
Example 1:
\n\n\nInput: names = ["Mary","John","Emma"], heights = [180,165,170]\nOutput: ["Mary","Emma","John"]\nExplanation: Mary is the tallest, followed by Emma and John.\n\n\n
Example 2:
\n\n\nInput: names = ["Alice","Bob","Bob"], heights = [155,185,150]\nOutput: ["Bob","Alice","Bob"]\nExplanation: The first Bob is the tallest, followed by Alice and the second Bob.\n\n\n
\n
Constraints:
\n\nn == names.length == heights.length
1 <= n <= 103
1 <= names[i].length <= 20
1 <= heights[i] <= 105
names[i]
consists of lower and upper case English letters.heights
are distinct.You are given an integer array nums
of size n
.
Consider a non-empty subarray from nums
that has the maximum possible bitwise AND.
k
be the maximum value of the bitwise AND of any subarray of nums
. Then, only subarrays with a bitwise AND equal to k
should be considered.Return the length of the longest such subarray.
\n\nThe bitwise AND of an array is the bitwise AND of all the numbers in it.
\n\nA subarray is a contiguous sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,3,2,2]\nOutput: 2\nExplanation:\nThe maximum possible bitwise AND of a subarray is 3.\nThe longest subarray with that value is [3,3], so we return 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation:\nThe maximum possible bitwise AND of a subarray is 4.\nThe longest subarray with that value is [4], so we return 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
You are given a 0-indexed integer array nums
of size n
and a positive integer k
.
We call an index i
in the range k <= i < n - k
good if the following conditions are satisfied:
k
elements that are just before the index i
are in non-increasing order.k
elements that are just after the index i
are in non-decreasing order.Return an array of all good indices sorted in increasing order.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,1,1,3,4,1], k = 2\nOutput: [2,3]\nExplanation: There are two good indices in the array:\n- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.\n- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.\nNote that the index 4 is not good because [4,1] is not non-decreasing.\n\n
Example 2:
\n\n\nInput: nums = [2,1,1,2], k = 2\nOutput: []\nExplanation: There are no good indices in this array.\n\n\n
\n
Constraints:
\n\nn == nums.length
3 <= n <= 105
1 <= nums[i] <= 106
1 <= k <= n / 2
There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n
nodes numbered from 0
to n - 1
and exactly n - 1
edges.
You are given a 0-indexed integer array vals
of length n
where vals[i]
denotes the value of the ith
node. You are also given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi
.
A good path is a simple path that satisfies the following conditions:
\n\nReturn the number of distinct good paths.
\n\nNote that a path and its reverse are counted as the same path. For example, 0 -> 1
is considered to be the same as 1 -> 0
. A single node is also considered as a valid path.
\n
Example 1:
\n\nInput: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]\nOutput: 6\nExplanation: There are 5 good paths consisting of a single node.\nThere is 1 additional good path: 1 -> 0 -> 2 -> 4.\n(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)\nNote that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].\n\n\n
Example 2:
\n\nInput: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]\nOutput: 7\nExplanation: There are 5 good paths consisting of a single node.\nThere are 2 additional good paths: 0 -> 1 and 2 -> 3.\n\n\n
Example 3:
\n\nInput: vals = [1], edges = []\nOutput: 1\nExplanation: The tree consists of only one node, so there is one good path.\n\n\n
\n
Constraints:
\n\nn == vals.length
1 <= n <= 3 * 104
0 <= vals[i] <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.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 all letters in word
are equal, and false
otherwise.
Note:
\n\nx
is the number of times it occurs in the string.\n
Example 1:
\n\n\nInput: word = "abcc"\nOutput: true\nExplanation: Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.\n\n\n
Example 2:
\n\n\nInput: word = "aazz"\nOutput: false\nExplanation: We must delete a character, so either the frequency of "a" is 1 and the frequency of "z" is 2, or vice versa. It is impossible to make all present letters have equal frequency.\n\n\n
\n
Constraints:
\n\n2 <= word.length <= 100
word
consists of lowercase English letters only.You are given a stream of n
videos, each represented by a distinct number from 1
to n
that you need to "upload" to a server. You need to implement a data structure that calculates the length of the longest uploaded prefix at various points in the upload process.
We consider i
to be an uploaded prefix if all videos in the range 1
to i
(inclusive) have been uploaded to the server. The longest uploaded prefix is the maximum value of i
that satisfies this definition.
\n
\nImplement the LUPrefix
class:
LUPrefix(int n)
Initializes the object for a stream of n
videos.void upload(int video)
Uploads video
to the server.int longest()
Returns the length of the longest uploaded prefix defined above.\n
Example 1:
\n\n\nInput\n["LUPrefix", "upload", "longest", "upload", "longest", "upload", "longest"]\n[[4], [3], [], [1], [], [2], []]\nOutput\n[null, null, 0, null, 1, null, 3]\n\nExplanation\nLUPrefix server = new LUPrefix(4); // Initialize a stream of 4 videos.\nserver.upload(3); // Upload video 3.\nserver.longest(); // Since video 1 has not been uploaded yet, there is no prefix.\n // So, we return 0.\nserver.upload(1); // Upload video 1.\nserver.longest(); // The prefix [1] is the longest uploaded prefix, so we return 1.\nserver.upload(2); // Upload video 2.\nserver.longest(); // The prefix [1,2,3] is the longest uploaded prefix, so we return 3.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= video <= n
video
are distinct.2 * 105
calls in total will be made to upload
and longest
.longest
.You are given two 0-indexed arrays, nums1
and nums2
, consisting of non-negative integers. There exists another array, nums3
, which contains the bitwise XOR of all pairings of integers between nums1
and nums2
(every integer in nums1
is paired with every integer in nums2
exactly once).
Return the bitwise XOR of all integers in nums3
.
\n
Example 1:
\n\n\nInput: nums1 = [2,1,3], nums2 = [10,2,5,0]\nOutput: 13\nExplanation:\nA possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].\nThe bitwise XOR of all these numbers is 13, so we return 13.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 0\nExplanation:\nAll possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],\nand nums1[1] ^ nums2[1].\nThus, one possible nums3 array is [2,5,1,6].\n2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[j] <= 109
You are given two 0-indexed arrays, nums1
and nums2
, consisting of non-negative integers. Let there be another array, nums3
, which contains the bitwise XOR of all pairings of integers between nums1
and nums2
(every integer in nums1
is paired with every integer in nums2
exactly once).
Return the bitwise XOR of all integers in nums3
.
\n
Example 1:
\n\n\nInput: nums1 = [2,1,3], nums2 = [10,2,5,0]\nOutput: 13\nExplanation:\nA possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].\nThe bitwise XOR of all these numbers is 13, so we return 13.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 0\nExplanation:\nAll possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],\nand nums1[1] ^ nums2[1].\nThus, one possible nums3 array is [2,5,1,6].\n2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[j] <= 109
You are given two 0-indexed integer arrays nums1
and nums2
, each of size n
, and an integer diff
. Find the number of pairs (i, j)
such that:
0 <= i < j <= n - 1
andnums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff
.Return the number of pairs that satisfy the conditions.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1\nOutput: 3\nExplanation:\nThere are 3 pairs that satisfy the conditions:\n1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.\n2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.\n3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.\nTherefore, we return 3.\n\n\n
Example 2:
\n\n\nInput: nums1 = [3,-1], nums2 = [-2,2], diff = -1\nOutput: 0\nExplanation:\nSince there does not exist any pair that satisfies the conditions, we return 0.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
2 <= n <= 105
-104 <= nums1[i], nums2[i] <= 104
-104 <= diff <= 104
Given two positive integers a
and b
, return the number of common factors of a
and b
.
An integer x
is a common factor of a
and b
if x
divides both a
and b
.
\n
Example 1:
\n\n\nInput: a = 12, b = 6\nOutput: 4\nExplanation: The common factors of 12 and 6 are 1, 2, 3, 6.\n\n\n
Example 2:
\n\n\nInput: a = 25, b = 30\nOutput: 2\nExplanation: The common factors of 25 and 30 are 1, 5.\n\n\n
\n
Constraints:
\n\n1 <= a, b <= 1000
You are given an m x n
integer matrix grid
.
We define an hourglass as a part of the matrix with the following form:
\nReturn the maximum sum of the elements of an hourglass.
\n\nNote that an hourglass cannot be rotated and must be entirely contained within the matrix.
\n\n\n
Example 1:
\n\nInput: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]\nOutput: 30\nExplanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.\n\n\n
Example 2:
\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 35\nExplanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
3 <= m, n <= 150
0 <= grid[i][j] <= 106
Given two positive integers num1
and num2
, find the positive integer x
such that:
x
has the same number of set bits as num2
, andx XOR num1
is minimal.Note that XOR
is the bitwise XOR operation.
Return the integer x
. The test cases are generated such that x
is uniquely determined.
The number of set bits of an integer is the number of 1
's in its binary representation.
\n
Example 1:
\n\n\nInput: num1 = 3, num2 = 5\nOutput: 3\nExplanation:\nThe binary representations of num1 and num2 are 0011 and 0101, respectively.\nThe integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0
is minimal.\n
\n\nExample 2:
\n\n\nInput: num1 = 1, num2 = 12\nOutput: 3\nExplanation:\nThe binary representations of num1 and num2 are 0001 and 1100, respectively.\nThe integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2
is minimal.\n
\n\n\n
Constraints:
\n\n1 <= num1, num2 <= 109
You are given a string s
consisting of only lowercase English letters. In one operation, you can:
s
, ori
letters of s
if the first i
letters of s
are equal to the following i
letters in s
, for any i
in the range 1 <= i <= s.length / 2
.For example, if s = "ababc"
, then in one operation, you could delete the first two letters of s
to get "abc"
, since the first two letters of s
and the following two letters of s
are both equal to "ab"
.
Return the maximum number of operations needed to delete all of s
.
\n
Example 1:
\n\n\nInput: s = "abcabcdabc"\nOutput: 2\nExplanation:\n- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".\n- Delete all the letters.\nWe used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.\nNote that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.\n\n\n
Example 2:
\n\n\nInput: s = "aaabaab"\nOutput: 4\nExplanation:\n- Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab".\n- Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab".\n- Delete the first letter ("a") since the next letter is equal. Now, s = "ab".\n- Delete all the letters.\nWe used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.\n\n\n
Example 3:
\n\n\nInput: s = "aaaaa"\nOutput: 5\nExplanation: In each operation, we can delete the first letter of s.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 4000
s
consists only of lowercase English letters.There are n
employees, each with a unique id from 0
to n - 1
.
You are given a 2D integer array logs
where logs[i] = [idi, leaveTimei]
where:
idi
is the id of the employee that worked on the ith
task, andleaveTimei
is the time at which the employee finished the ith
task. All the values leaveTimei
are unique.Note that the ith
task starts the moment right after the (i - 1)th
task ends, and the 0th
task starts at time 0
.
Return the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them.
\n\n\n
Example 1:
\n\n\nInput: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]]\nOutput: 1\nExplanation: \nTask 0 started at 0 and ended at 3 with 3 units of times.\nTask 1 started at 3 and ended at 5 with 2 units of times.\nTask 2 started at 5 and ended at 9 with 4 units of times.\nTask 3 started at 9 and ended at 15 with 6 units of times.\nThe task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1.\n\n\n
Example 2:
\n\n\nInput: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]]\nOutput: 3\nExplanation: \nTask 0 started at 0 and ended at 1 with 1 unit of times.\nTask 1 started at 1 and ended at 7 with 6 units of times.\nTask 2 started at 7 and ended at 12 with 5 units of times.\nTask 3 started at 12 and ended at 17 with 5 units of times.\nThe tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3.\n\n\n
Example 3:
\n\n\nInput: n = 2, logs = [[0,10],[1,20]]\nOutput: 0\nExplanation: \nTask 0 started at 0 and ended at 10 with 10 units of times.\nTask 1 started at 10 and ended at 20 with 10 units of times.\nThe tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0.\n\n\n
\n
Constraints:
\n\n2 <= n <= 500
1 <= logs.length <= 500
logs[i].length == 2
0 <= idi <= n - 1
1 <= leaveTimei <= 500
idi != idi+1
leaveTimei
are sorted in a strictly increasing order.You are given an integer array pref
of size n
. Find and return the array arr
of size n
that satisfies:
pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]
.Note that ^
denotes the bitwise-xor operation.
It can be proven that the answer is unique.
\n\n\n
Example 1:
\n\n\nInput: pref = [5,2,0,3,1]\nOutput: [5,7,2,3,2]\nExplanation: From the array [5,7,2,3,2] we have the following:\n- pref[0] = 5.\n- pref[1] = 5 ^ 7 = 2.\n- pref[2] = 5 ^ 7 ^ 2 = 0.\n- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.\n- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.\n\n\n
Example 2:
\n\n\nInput: pref = [13]\nOutput: [13]\nExplanation: We have pref[0] = arr[0] = 13.\n\n\n
\n
Constraints:
\n\n1 <= pref.length <= 105
0 <= pref[i] <= 106
You are given a string s
and a robot that currently holds an empty string t
. Apply one of the following operations until s
and t
are both empty:
s
and give it to the robot. The robot will append this character to the string t
.t
and give it to the robot. The robot will write this character on paper.Return the lexicographically smallest string that can be written on the paper.
\n\n\n
Example 1:
\n\n\nInput: s = "zza"\nOutput: "azz"\nExplanation: Let p denote the written string.\nInitially p="", s="zza", t="".\nPerform first operation three times p="", s="", t="zza".\nPerform second operation three times p="azz", s="", t="".\n\n\n
Example 2:
\n\n\nInput: s = "bac"\nOutput: "abc"\nExplanation: Let p denote the written string.\nPerform first operation twice p="", s="c", t="ba". \nPerform second operation twice p="ab", s="c", t="". \nPerform first operation p="ab", s="", t="c". \nPerform second operation p="abc", s="", t="".\n\n\n
Example 3:
\n\n\nInput: s = "bdda"\nOutput: "addb"\nExplanation: Let p denote the written string.\nInitially p="", s="bdda", t="".\nPerform first operation four times p="", s="", t="bdda".\nPerform second operation four times p="addb", s="", t="".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only English lowercase letters.You are given a 0-indexed m x n
integer matrix grid
and an integer k
. You are currently at position (0, 0)
and you want to reach position (m - 1, n - 1)
moving only down or right.
Return the number of paths where the sum of the elements on the path is divisible by k
. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3\nOutput: 2\nExplanation: There are two paths where the sum of the elements on the path is divisible by k.\nThe first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.\nThe second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.\n\n\n
Example 2:
\n\nInput: grid = [[0,0]], k = 5\nOutput: 1\nExplanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.\n\n\n
Example 3:
\n\nInput: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1\nOutput: 10\nExplanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 5 * 104
1 <= m * n <= 5 * 104
0 <= grid[i][j] <= 100
1 <= k <= 50
You are given a string of length 5
called time
, representing the current time on a digital clock in the format "hh:mm"
. The earliest possible time is "00:00"
and the latest possible time is "23:59"
.
In the string time
, the digits represented by the ?
symbol are unknown, and must be replaced with a digit from 0
to 9
.
Return an integer answer
, the number of valid clock times that can be created by replacing every ?
with a digit from 0
to 9
.
\n
Example 1:
\n\n\nInput: time = "?5:00"\nOutput: 2\nExplanation: We can replace the ? with either a 0 or 1, producing "05:00" or "15:00". Note that we cannot replace it with a 2, since the time "25:00" is invalid. In total, we have two choices.\n\n\n
Example 2:
\n\n\nInput: time = "0?:0?"\nOutput: 100\nExplanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.\n\n\n
Example 3:
\n\n\nInput: time = "??:??"\nOutput: 1440\nExplanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.\n\n\n
\n
Constraints:
\n\ntime
is a valid string of length 5
in the format "hh:mm"
."00" <= hh <= "23"
"00" <= mm <= "59"
'?'
and need to be replaced with digits from 0
to 9
.Given a positive integer n
, there exists a 0-indexed array called powers
, composed of the minimum number of powers of 2
that sum to n
. The array is sorted in non-decreasing order, and there is only one way to form the array.
You are also given a 0-indexed 2D integer array queries
, where queries[i] = [lefti, righti]
. Each queries[i]
represents a query where you have to find the product of all powers[j]
with lefti <= j <= righti
.
Return an array answers
, equal in length to queries
, where answers[i]
is the answer to the ith
query. Since the answer to the ith
query may be too large, each answers[i]
should be returned modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 15, queries = [[0,1],[2,2],[0,3]]\nOutput: [2,4,64]\nExplanation:\nFor n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.\nAnswer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.\nAnswer to 2nd query: powers[2] = 4.\nAnswer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.\nEach answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.\n\n\n
Example 2:
\n\n\nInput: n = 2, queries = [[0,0]]\nOutput: [2]\nExplanation:\nFor n = 2, powers = [2].\nThe answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
1 <= queries.length <= 105
0 <= starti <= endi < powers.length
You are given a 0-indexed array nums
comprising of n
non-negative integers.
In one operation, you must:
\n\ni
such that 1 <= i < n
and nums[i] > 0
.nums[i]
by 1.nums[i - 1]
by 1.Return the minimum possible value of the maximum integer of nums
after performing any number of operations.
\n
Example 1:
\n\n\nInput: nums = [3,7,1,6]\nOutput: 5\nExplanation:\nOne set of optimal operations is as follows:\n1. Choose i = 1, and nums becomes [4,6,1,6].\n2. Choose i = 3, and nums becomes [4,6,2,5].\n3. Choose i = 1, and nums becomes [5,5,2,5].\nThe maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.\nTherefore, we return 5.\n\n\n
Example 2:
\n\n\nInput: nums = [10,1]\nOutput: 10\nExplanation:\nIt is optimal to leave nums as is, and since 10 is the maximum value, we return 10.\n\n\n
\n
Constraints:
\n\nn == nums.length
2 <= n <= 105
0 <= nums[i] <= 109
There is an undirected tree with n
nodes labeled from 0
to n - 1
.
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]
indicates that there is an edge between nodes ai
and bi
in the tree.
You are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i]
for which node i
is in the component.
Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.
\n\n\n
Example 1:
\n\nInput: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] \nOutput: 2 \nExplanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [2], edges = []\nOutput: 0\nExplanation: There are no edges to be deleted.\n\n\n
\n
Constraints:
\n\n1 <= n <= 2 * 104
nums.length == n
1 <= nums[i] <= 50
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
edges
represents a valid tree.Given an integer array nums
that does not contain any zeros, find the largest positive integer k
such that -k
also exists in the array.
Return the positive integer k
. If there is no such integer, return -1
.
\n
Example 1:
\n\n\nInput: nums = [-1,2,-3,3]\nOutput: 3\nExplanation: 3 is the only valid k we can find in the array.\n\n\n
Example 2:
\n\n\nInput: nums = [-1,10,6,7,-7,1]\nOutput: 7\nExplanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.\n\n\n
Example 3:
\n\n\nInput: nums = [-10,8,6,7,-2,-3]\nOutput: -1\nExplanation: There is no a single valid k, we return -1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0
You are given an array nums
consisting of positive integers.
You have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums
.
Return the number of distinct integers in the final array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,13,10,12,31]\nOutput: 6\nExplanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].\nThe reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1.\nThe number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).\n\n
Example 2:
\n\n\nInput: nums = [2,2,2]\nOutput: 1\nExplanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].\nThe number of distinct integers in this array is 1 (The number 2).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
Given a non-negative integer num
, return true
if num
can be expressed as the sum of any non-negative integer and its reverse, or false
otherwise.
\n
Example 1:
\n\n\nInput: num = 443\nOutput: true\nExplanation: 172 + 271 = 443 so we return true.\n\n\n
Example 2:
\n\n\nInput: num = 63\nOutput: false\nExplanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.\n\n\n
Example 3:
\n\n\nInput: num = 181\nOutput: true\nExplanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.\n\n\n
\n
Constraints:
\n\n0 <= num <= 105
You are given an integer array nums
and two integers minK
and maxK
.
A fixed-bound subarray of nums
is a subarray that satisfies the following conditions:
minK
.maxK
.Return the number of fixed-bound subarrays.
\n\nA subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,5,2,7,5], minK = 1, maxK = 5\nOutput: 2\nExplanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1], minK = 1, maxK = 1\nOutput: 10\nExplanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i], minK, maxK <= 106
You are given two arrays of strings that represent two inclusive events that happened on the same day, event1
and event2
, where:
event1 = [startTime1, endTime1]
andevent2 = [startTime2, endTime2]
.Event times are valid 24 hours format in the form of HH:MM
.
A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events).
\n\nReturn true
if there is a conflict between two events. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: event1 = ["01:15","02:00"], event2 = ["02:00","03:00"]\nOutput: true\nExplanation: The two events intersect at time 2:00.\n\n\n
Example 2:
\n\n\nInput: event1 = ["01:00","02:00"], event2 = ["01:20","03:00"]\nOutput: true\nExplanation: The two events intersect starting from 01:20 to 02:00.\n\n\n
Example 3:
\n\n\nInput: event1 = ["10:00","11:00"], event2 = ["14:00","15:00"]\nOutput: false\nExplanation: The two events do not intersect.\n\n\n
\n
Constraints:
\n\nevent1.length == event2.length == 2
event1[i].length == event2[i].length == 5
startTime1 <= endTime1
startTime2 <= endTime2
HH:MM
format.Given an integer array nums
and an integer k
, return the number of subarrays of nums
where the greatest common divisor of the subarray's elements is k
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\nThe greatest common divisor of an array is the largest integer that evenly divides all the array elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [9,3,1,2,6,3], k = 3\nOutput: 4\nExplanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\n\n\n
Example 2:
\n\n\nInput: nums = [4], k = 7\nOutput: 0\nExplanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i], k <= 109
You are given two 0-indexed arrays nums
and cost
consisting each of n
positive integers.
You can do the following operation any number of times:
\n\nnums
by 1
.The cost of doing one operation on the ith
element is cost[i]
.
Return the minimum total cost such that all the elements of the array nums
become equal.
\n
Example 1:
\n\n\nInput: nums = [1,3,5,2], cost = [2,3,1,14]\nOutput: 8\nExplanation: We can make all the elements equal to 2 in the following way:\n- Increase the 0th element one time. The cost is 2.\n- Decrease the 1st element one time. The cost is 3.\n- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.\nThe total cost is 2 + 3 + 3 = 8.\nIt can be shown that we cannot make the array equal with a smaller cost.\n
\n\nExample 2:
\n\n\nInput: nums = [2,2,2,2,2], cost = [4,2,8,1,3]\nOutput: 0\nExplanation: All the elements are already equal, so no operations are needed.\n\n\n
\n
Constraints:
\n\nn == nums.length == cost.length
1 <= n <= 105
1 <= nums[i], cost[i] <= 106
You are given two positive integer arrays nums
and target
, of the same length.
In one operation, you can choose any two distinct indices i
and j
where 0 <= i, j < nums.length
and:
nums[i] = nums[i] + 2
andnums[j] = nums[j] - 2
.Two arrays are considered to be similar if the frequency of each element is the same.
\n\nReturn the minimum number of operations required to make nums
similar to target
. The test cases are generated such that nums
can always be similar to target
.
\n
Example 1:
\n\n\nInput: nums = [8,12,6], target = [2,14,10]\nOutput: 2\nExplanation: It is possible to make nums similar to target in two operations:\n- Choose i = 0 and j = 2, nums = [10,12,4].\n- Choose i = 1 and j = 2, nums = [10,14,2].\nIt can be shown that 2 is the minimum number of operations needed.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,5], target = [4,1,3]\nOutput: 1\nExplanation: We can make nums similar to target in one operation:\n- Choose i = 1 and j = 2, nums = [1,4,3].\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,1,1,1], target = [1,1,1,1,1]\nOutput: 0\nExplanation: The array nums is already similiar to target.\n\n\n
\n
Constraints:
\n\nn == nums.length == target.length
1 <= n <= 105
1 <= nums[i], target[i] <= 106
nums
similar to target
.You are given an array of equal-length strings words
. Assume that the length of each string is n
.
Each string words[i]
can be converted into a difference integer array difference[i]
of length n - 1
where difference[i][j] = words[i][j+1] - words[i][j]
where 0 <= j <= n - 2
. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a'
is 0
, 'b'
is 1
, and 'z'
is 25
.
"acb"
, the difference integer array is [2 - 0, 1 - 2] = [2, -1]
.All the strings in words have the same difference integer array, except one. You should find that string.
\n\nReturn the string in words
that has different difference integer array.
\n
Example 1:
\n\n\nInput: words = ["adc","wzy","abc"]\nOutput: "abc"\nExplanation: \n- The difference integer array of "adc" is [3 - 0, 2 - 3] = [3, -1].\n- The difference integer array of "wzy" is [25 - 22, 24 - 25]= [3, -1].\n- The difference integer array of "abc" is [1 - 0, 2 - 1] = [1, 1]. \nThe odd array out is [1, 1], so we return the corresponding string, "abc".\n\n\n
Example 2:
\n\n\nInput: words = ["aaa","bob","ccc","ddd"]\nOutput: "bob"\nExplanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].\n\n\n
\n
Constraints:
\n\n3 <= words.length <= 100
n == words[i].length
2 <= n <= 20
words[i]
consists of lowercase English letters.You are given two string arrays, queries
and dictionary
. All words in each array comprise of lowercase English letters and have the same length.
In one edit you can take a word from queries
, and change any letter in it to any other letter. Find all words from queries
that, after a maximum of two edits, equal some word from dictionary
.
Return a list of all words from queries
, that match with some word from dictionary
after a maximum of two edits. Return the words in the same order they appear in queries
.
\n
Example 1:
\n\n\nInput: queries = ["word","note","ants","wood"], dictionary = ["wood","joke","moat"]\nOutput: ["word","note","wood"]\nExplanation:\n- Changing the 'r' in "word" to 'o' allows it to equal the dictionary word "wood".\n- Changing the 'n' to 'j' and the 't' to 'k' in "note" changes it to "joke".\n- It would take more than 2 edits for "ants" to equal a dictionary word.\n- "wood" can remain unchanged (0 edits) and match the corresponding dictionary word.\nThus, we return ["word","note","wood"].\n\n\n
Example 2:
\n\n\nInput: queries = ["yes"], dictionary = ["not"]\nOutput: []\nExplanation:\nApplying any two edits to "yes" cannot make it equal to "not". Thus, we return an empty array.\n\n\n
\n
Constraints:
\n\n1 <= queries.length, dictionary.length <= 100
n == queries[i].length == dictionary[j].length
1 <= n <= 100
queries[i]
and dictionary[j]
are composed of lowercase English letters.You are given a 0-indexed array nums
consisting of positive integers, representing targets on a number line. You are also given an integer space
.
You have a machine which can destroy targets. Seeding the machine with some nums[i]
allows it to destroy all targets with values that can be represented as nums[i] + c * space
, where c
is any non-negative integer. You want to destroy the maximum number of targets in nums
.
Return the minimum value of nums[i]
you can seed the machine with to destroy the maximum number of targets.
\n
Example 1:
\n\n\nInput: nums = [3,7,8,1,1,5], space = 2\nOutput: 1\nExplanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,... \nIn this case, we would destroy 5 total targets (all except for nums[2]). \nIt is impossible to destroy more than 5 targets, so we return nums[3].\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,5,2,4,6], space = 2\nOutput: 1\nExplanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets. \nIt is not possible to destroy more than 3 targets.\nSince nums[0] is the minimal integer that can destroy 3 targets, we return 1.\n\n\n
Example 3:
\n\n\nInput: nums = [6,2,5], space = 100\nOutput: 2\nExplanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= space <= 109
You are given a 0-indexed array of non-negative integers nums
. For each integer in nums
, you must find its respective second greater integer.
The second greater integer of nums[i]
is nums[j]
such that:
j > i
nums[j] > nums[i]
k
such that nums[k] > nums[i]
and i < k < j
.If there is no such nums[j]
, the second greater integer is considered to be -1
.
[1, 2, 4, 3]
, the second greater integer of 1
is 4
, 2
is 3
, and that of 3
and 4
is -1
.Return an integer array answer
, where answer[i]
is the second greater integer of nums[i]
.
\n
Example 1:
\n\n\nInput: nums = [2,4,0,9,6]\nOutput: [9,6,6,-1,-1]\nExplanation:\n0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.\n1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.\n2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.\n3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.\n4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.\nThus, we return [9,6,6,-1,-1].\n\n\n
Example 2:
\n\n\nInput: nums = [3,3]\nOutput: [-1,-1]\nExplanation:\nWe return [-1,-1] since neither integer has any integer greater than it.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
Given an integer array nums
of positive integers, return the average value of all even integers that are divisible by 3
.
Note that the average of n
elements is the sum of the n
elements divided by n
and rounded down to the nearest integer.
\n
Example 1:
\n\n\nInput: nums = [1,3,6,10,12,15]\nOutput: 9\nExplanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,4,7,10]\nOutput: 0\nExplanation: There is no single number that satisfies the requirement, so return 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
You are given two string arrays creators
and ids
, and an integer array views
, all of length n
. The ith
video on a platform was created by creators[i]
, has an id of ids[i]
, and has views[i]
views.
The popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highest popularity and the id of their most viewed video.
\n\nNote: It is possible for different videos to have the same id
, meaning that id
s do not uniquely identify a video. For example, two videos with the same ID are considered as distinct videos with their own viewcount.
Return a 2D array of strings answer
where answer[i] = [creatorsi, idi]
means that creatorsi
has the highest popularity and idi
is the id of their most popular video. The answer can be returned in any order.
\n
Example 1:
\n\nInput: creators = ["alice","bob","alice","chris"], ids = ["one","two","three","four"], views = [5,10,5,4]
\n\nOutput: [["alice","one"],["bob","two"]]
\n\nExplanation:
\n\nThe popularity of alice is 5 + 5 = 10.
\nThe popularity of bob is 10.
\nThe popularity of chris is 4.
\nalice and bob are the most popular creators.
\nFor bob, the video with the highest view count is "two".
\nFor alice, the videos with the highest view count are "one" and "three". Since "one" is lexicographically smaller than "three", it is included in the answer.
Example 2:
\n\nInput: creators = ["alice","alice","alice"], ids = ["a","b","c"], views = [1,2,2]
\n\nOutput: [["alice","b"]]
\n\nExplanation:
\n\nThe videos with id "b" and "c" have the highest view count.
\nSince "b" is lexicographically smaller than "c", it is included in the answer.
\n
Constraints:
\n\nn == creators.length == ids.length == views.length
1 <= n <= 105
1 <= creators[i].length, ids[i].length <= 5
creators[i]
and ids[i]
consist only of lowercase English letters.0 <= views[i] <= 105
You are given two positive integers n
and target
.
An integer is considered beautiful if the sum of its digits is less than or equal to target
.
Return the minimum non-negative integer x
such that n + x
is beautiful. The input will be generated such that it is always possible to make n
beautiful.
\n
Example 1:
\n\n\nInput: n = 16, target = 6\nOutput: 4\nExplanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.\n\n\n
Example 2:
\n\n\nInput: n = 467, target = 6\nOutput: 33\nExplanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.\n\n\n
Example 3:
\n\n\nInput: n = 1, target = 1\nOutput: 0\nExplanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1012
1 <= target <= 150
n
beautiful.You are given the root
of a binary tree with n
nodes. Each node is assigned a unique value from 1
to n
. You are also given an array queries
of size m
.
You have to perform m
independent queries on the tree where in the ith
query you do the following:
queries[i]
from the tree. It is guaranteed that queries[i]
will not be equal to the value of the root.Return an array answer
of size m
where answer[i]
is the height of the tree after performing the ith
query.
Note:
\n\n\n
Example 1:
\n\nInput: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]\nOutput: [2]\nExplanation: The diagram above shows the tree after removing the subtree rooted at node with value 4.\nThe height of the tree is 2 (The path 1 -> 3 -> 2).\n\n\n
Example 2:
\n\nInput: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]\nOutput: [3,2,3,2]\nExplanation: We have the following queries:\n- Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4).\n- Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1).\n- Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6).\n- Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).\n\n\n
\n
Constraints:
\n\nn
.2 <= n <= 105
1 <= Node.val <= n
m == queries.length
1 <= m <= min(n, 104)
1 <= queries[i] <= n
queries[i] != root.val
You are given a 0-indexed array nums
of size n
consisting of non-negative integers.
You need to apply n - 1
operations to this array where, in the ith
operation (0-indexed), you will apply the following on the ith
element of nums
:
nums[i] == nums[i + 1]
, then multiply nums[i]
by 2
and set nums[i + 1]
to 0
. Otherwise, you skip this operation.After performing all the operations, shift all the 0
's to the end of the array.
[1,0,2,0,0,1]
after shifting all its 0
's to the end, is [1,2,1,0,0,0]
.Return the resulting array.
\n\nNote that the operations are applied sequentially, not all at once.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,2,1,1,0]\nOutput: [1,4,2,0,0,0]\nExplanation: We do the following operations:\n- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.\n- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].\n- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.\n- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].\n- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].\nAfter that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].\n\n\n
Example 2:
\n\n\nInput: nums = [0,1]\nOutput: [1,0]\nExplanation: No operation can be applied, we just shift the 0 to the end.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 2000
0 <= nums[i] <= 1000
You are given an integer array nums
and an integer k
. Find the maximum subarray sum of all the subarrays of nums
that meet the following conditions:
k
, andReturn the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,5,4,2,9,9,9], k = 3\nOutput: 15\nExplanation: The subarrays of nums with length 3 are:\n- [1,5,4] which meets the requirements and has a sum of 10.\n- [5,4,2] which meets the requirements and has a sum of 11.\n- [4,2,9] which meets the requirements and has a sum of 15.\n- [2,9,9] which does not meet the requirements because the element 9 is repeated.\n- [9,9,9] which does not meet the requirements because the element 9 is repeated.\nWe return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions\n\n\n
Example 2:
\n\n\nInput: nums = [4,4,4], k = 3\nOutput: 0\nExplanation: The subarrays of nums with length 3 are:\n- [4,4,4] which does not meet the requirements because the element 4 is repeated.\nWe return 0 because no subarrays meet the conditions.\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
1 <= nums[i] <= 105
You are given a 0-indexed integer array costs
where costs[i]
is the cost of hiring the ith
worker.
You are also given two integers k
and candidates
. We want to hire exactly k
workers according to the following rules:
k
sessions and hire exactly one worker in each session.candidates
workers or the last candidates
workers. Break the tie by the smallest index.\n\tcosts = [3,2,7,7,1,2]
and candidates = 2
, then in the first hiring session, we will choose the 4th
worker because they have the lowest cost [3,2,7,7,1,2]
.1st
worker because they have the same lowest cost as 4th
worker but they have the smallest index [3,2,7,7,2]
. Please note that the indexing may be changed in the process.Return the total cost to hire exactly k
workers.
\n
Example 1:
\n\n\nInput: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4\nOutput: 11\nExplanation: We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.\n- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.\n- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.\nThe total hiring cost is 11.\n\n\n
Example 2:
\n\n\nInput: costs = [1,2,4,1], k = 3, candidates = 3\nOutput: 4\nExplanation: We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.\n- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.\n- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.\nThe total hiring cost is 4.\n\n\n
\n
Constraints:
\n\n1 <= costs.length <= 105
1 <= costs[i] <= 105
1 <= k, candidates <= costs.length
There are some robots and factories on the X-axis. You are given an integer array robot
where robot[i]
is the position of the ith
robot. You are also given a 2D integer array factory
where factory[j] = [positionj, limitj]
indicates that positionj
is the position of the jth
factory and that the jth
factory can repair at most limitj
robots.
The positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.
\n\nAll the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.
\n\nAt any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.
\n\nReturn the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.
\n\nNote that
\n\nx
to a position y
, the distance it moved is |y - x|
.\n
Example 1:
\n\nInput: robot = [0,4,6], factory = [[2,2],[6,2]]\nOutput: 4\nExplanation: As shown in the figure:\n- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.\n- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.\n- The third robot at position 6 will be repaired at the second factory. It does not need to move.\nThe limit of the first factory is 2, and it fixed 2 robots.\nThe limit of the second factory is 2, and it fixed 1 robot.\nThe total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.\n\n\n
Example 2:
\n\nInput: robot = [1,-1], factory = [[-2,1],[2,1]]\nOutput: 2\nExplanation: As shown in the figure:\n- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.\n- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.\nThe limit of the first factory is 1, and it fixed 1 robot.\nThe limit of the second factory is 1, and it fixed 1 robot.\nThe total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.\n\n\n
\n
Constraints:
\n\n1 <= robot.length, factory.length <= 100
factory[j].length == 2
-109 <= robot[i], positionj <= 109
0 <= limitj <= robot.length
You are given a 0-indexed integer array nums
of even length.
As long as nums
is not empty, you must repetitively:
nums
and remove it.nums
and remove it.The average of two numbers a
and b
is (a + b) / 2
.
2
and 3
is (2 + 3) / 2 = 2.5
.Return the number of distinct averages calculated using the above process.
\n\nNote that when there is a tie for a minimum or maximum number, any can be removed.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,1,4,0,3,5]\nOutput: 2\nExplanation:\n1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].\n2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].\n3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.\nSince there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,100]\nOutput: 1\nExplanation:\nThere is only one average to be calculated after removing 1 and 100, so we return 1.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
nums.length
is even.0 <= nums[i] <= 100
Given the integers zero
, one
, low
, and high
, we can construct a string by starting with an empty string, and then at each step perform either of the following:
'0'
zero
times.'1'
one
times.This can be performed any number of times.
\n\nA good string is a string constructed by the above process having a length between low
and high
(inclusive).
Return the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: low = 3, high = 3, zero = 1, one = 1\nOutput: 8\nExplanation: \nOne possible valid good string is "011". \nIt can be constructed as follows: "" -> "0" -> "01" -> "011". \nAll binary strings from "000" to "111" are good strings in this example.\n\n\n
Example 2:
\n\n\nInput: low = 2, high = 3, zero = 1, one = 2\nOutput: 5\nExplanation: The good strings are "00", "11", "000", "110", and "011".\n\n\n
\n
Constraints:
\n\n1 <= low <= high <= 105
1 <= zero, one <= low
There is an undirected tree with n
nodes labeled from 0
to n - 1
, rooted at node 0
. You are given a 2D integer array edges
of length n - 1
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
At every node i
, there is a gate. You are also given an array of even integers amount
, where amount[i]
represents:
i
, if amount[i]
is negative, or,i
, otherwise.The game goes on as follows:
\n\n0
and Bob is at node bob
.0
.c
, then both Alice and Bob pay c / 2
each. Similarly, if the reward at the gate is c
, both of them receive c / 2
each.0
, he stops moving. Note that these events are independent of each other.Return the maximum net income Alice can have if she travels towards the optimal leaf node.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]\nOutput: 6\nExplanation: \nThe above diagram represents the given tree. The game goes as follows:\n- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.\n Alice's net income is now -2.\n- Both Alice and Bob move to node 1. \n Since they reach here simultaneously, they open the gate together and share the reward.\n Alice's net income becomes -2 + (4 / 2) = 0.\n- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.\n Bob moves on to node 0, and stops moving.\n- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.\nNow, neither Alice nor Bob can make any further moves, and the game ends.\nIt is not possible for Alice to get a higher net income.\n\n\n
Example 2:
\n\nInput: edges = [[0,1]], bob = 1, amount = [-7280,2350]\nOutput: -7280\nExplanation: \nAlice follows the path 0->1 whereas Bob follows the path 1->0.\nThus, Alice opens the gate at node 0 only. Hence, her net income is -7280. \n\n\n
\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.1 <= bob < n
amount.length == n
amount[i]
is an even integer in the range [-104, 104]
.You are given a string, message
, and a positive integer, limit
.
You must split message
into one or more parts based on limit
. Each resulting part should have the suffix "<a/b>"
, where "b"
is to be replaced with the total number of parts and "a"
is to be replaced with the index of the part, starting from 1
and going up to b
. Additionally, the length of each resulting part (including its suffix) should be equal to limit
, except for the last part whose length can be at most limit
.
The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message
. Also, the result should contain as few parts as possible.
Return the parts message
would be split into as an array of strings. If it is impossible to split message
as required, return an empty array.
\n
Example 1:
\n\n\nInput: message = "this is really a very awesome message", limit = 9\nOutput: ["thi<1/14>","s i<2/14>","s r<3/14>","eal<4/14>","ly <5/14>","a v<6/14>","ery<7/14>"," aw<8/14>","eso<9/14>","me<10/14>"," m<11/14>","es<12/14>","sa<13/14>","ge<14/14>"]\nExplanation:\nThe first 9 parts take 3 characters each from the beginning of message.\nThe next 5 parts take 2 characters each to finish splitting message. \nIn this example, each part, including the last, has length 9. \nIt can be shown it is not possible to split message into less than 14 parts.\n\n\n
Example 2:
\n\n\nInput: message = "short message", limit = 15\nOutput: ["short mess<1/2>","age<2/2>"]\nExplanation:\nUnder the given constraints, the string can be split into two parts: \n- The first part comprises of the first 10 characters, and has a length 15.\n- The next part comprises of the last 3 characters, and has a length 8.\n\n\n
\n
Constraints:
\n\n1 <= message.length <= 104
message
consists only of lowercase English letters and ' '
.1 <= limit <= 104
You are given a non-negative floating point number rounded to two decimal places celsius
, that denotes the temperature in Celsius.
You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit]
.
Return the array ans
. Answers within 10-5
of the actual answer will be accepted.
Note that:
\n\nKelvin = Celsius + 273.15
Fahrenheit = Celsius * 1.80 + 32.00
\n
Example 1:
\n\n\nInput: celsius = 36.50\nOutput: [309.65000,97.70000]\nExplanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70.\n\n\n
Example 2:
\n\n\nInput: celsius = 122.11\nOutput: [395.26000,251.79800]\nExplanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798.\n\n\n
\n
Constraints:
\n\n0 <= celsius <= 1000
Given an integer array nums
and an integer k
, return the number of subarrays of nums
where the least common multiple of the subarray's elements is k
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\nThe least common multiple of an array is the smallest positive integer that is divisible by all the array elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,6,2,7,1], k = 6\nOutput: 4\nExplanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are:\n- [3,6,2,7,1]\n- [3,6,2,7,1]\n- [3,6,2,7,1]\n- [3,6,2,7,1]\n\n\n
Example 2:
\n\n\nInput: nums = [3], k = 2\nOutput: 0\nExplanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i], k <= 1000
You are given the root
of a binary tree with unique values.
In one operation, you can choose any two nodes at the same level and swap their values.
\n\nReturn the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.
\n\nThe level of a node is the number of edges along the path between it and the root node.
\n\n\n
Example 1:
\n\nInput: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]\nOutput: 3\nExplanation:\n- Swap 4 and 3. The 2nd level becomes [3,4].\n- Swap 7 and 5. The 3rd level becomes [5,6,8,7].\n- Swap 8 and 7. The 3rd level becomes [5,6,7,8].\nWe used 3 operations so return 3.\nIt can be proven that 3 is the minimum number of operations needed.\n\n\n
Example 2:
\n\nInput: root = [1,3,2,7,6,5,4]\nOutput: 3\nExplanation:\n- Swap 3 and 2. The 2nd level becomes [2,3].\n- Swap 7 and 4. The 3rd level becomes [4,6,5,7].\n- Swap 6 and 5. The 3rd level becomes [4,5,6,7].\nWe used 3 operations so return 3.\nIt can be proven that 3 is the minimum number of operations needed.\n\n\n
Example 3:
\n\nInput: root = [1,2,3,4,5,6]\nOutput: 0\nExplanation: Each level is already sorted in increasing order so return 0.\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 105
You are given a string s
and a positive integer k
.
Select a set of non-overlapping substrings from the string s
that satisfy the following conditions:
k
.Return the maximum number of substrings in an optimal selection.
\n\nA substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "abaccdbbd", k = 3\nOutput: 2\nExplanation: We can select the substrings underlined in s = "abaccdbbd". Both "aba" and "dbbd" are palindromes and have a length of at least k = 3.\nIt can be shown that we cannot find a selection with more than two valid substrings.\n\n\n
Example 2:
\n\n\nInput: s = "adbcda", k = 2\nOutput: 0\nExplanation: There is no palindrome substring of length at least 2 in the string.\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 2000
s
consists of lowercase English letters.You are given a 0-indexed array of positive integers nums
. Find the number of triplets (i, j, k)
that meet the following conditions:
0 <= i < j < k < nums.length
nums[i]
, nums[j]
, and nums[k]
are pairwise distinct.\n\tnums[i] != nums[j]
, nums[i] != nums[k]
, and nums[j] != nums[k]
.Return the number of triplets that meet the conditions.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,4,2,4,3]\nOutput: 3\nExplanation: The following triplets meet the conditions:\n- (0, 2, 4) because 4 != 2 != 3\n- (1, 2, 4) because 4 != 2 != 3\n- (2, 3, 4) because 2 != 4 != 3\nSince there are 3 triplets, we return 3.\nNote that (2, 0, 4) is not a valid triplet because 2 > 0.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: No triplets meet the conditions so we return 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 100
1 <= nums[i] <= 1000
You are given the root
of a binary search tree and an array queries
of size n
consisting of positive integers.
Find a 2D array answer
of size n
where answer[i] = [mini, maxi]
:
mini
is the largest value in the tree that is smaller than or equal to queries[i]
. If a such value does not exist, add -1
instead.maxi
is the smallest value in the tree that is greater than or equal to queries[i]
. If a such value does not exist, add -1
instead.Return the array answer
.
\n
Example 1:
\n\nInput: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]\nOutput: [[2,2],[4,6],[15,-1]]\nExplanation: We answer the queries in the following way:\n- The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2].\n- The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6].\n- The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].\n\n\n
Example 2:
\n\nInput: root = [4,null,9], queries = [3]\nOutput: [[-1,4]]\nExplanation: The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].\n\n\n
\n
Constraints:
\n\n[2, 105]
.1 <= Node.val <= 106
n == queries.length
1 <= n <= 105
1 <= queries[i] <= 106
There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n
cities numbered from 0
to n - 1
and exactly n - 1
roads. The capital city is city 0
. You are given a 2D integer array roads
where roads[i] = [ai, bi]
denotes that there exists a bidirectional road connecting cities ai
and bi
.
There is a meeting for the representatives of each city. The meeting is in the capital city.
\n\nThere is a car in each city. You are given an integer seats
that indicates the number of seats in each car.
A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.
\n\nReturn the minimum number of liters of fuel to reach the capital city.
\n\n\n
Example 1:
\n\nInput: roads = [[0,1],[0,2],[0,3]], seats = 5\nOutput: 3\nExplanation: \n- Representative1 goes directly to the capital with 1 liter of fuel.\n- Representative2 goes directly to the capital with 1 liter of fuel.\n- Representative3 goes directly to the capital with 1 liter of fuel.\nIt costs 3 liters of fuel at minimum. \nIt can be proven that 3 is the minimum number of liters of fuel needed.\n\n\n
Example 2:
\n\nInput: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2\nOutput: 7\nExplanation: \n- Representative2 goes directly to city 3 with 1 liter of fuel.\n- Representative2 and representative3 go together to city 1 with 1 liter of fuel.\n- Representative2 and representative3 go together to the capital with 1 liter of fuel.\n- Representative1 goes directly to the capital with 1 liter of fuel.\n- Representative5 goes directly to the capital with 1 liter of fuel.\n- Representative6 goes directly to city 4 with 1 liter of fuel.\n- Representative4 and representative6 go together to the capital with 1 liter of fuel.\nIt costs 7 liters of fuel at minimum. \nIt can be proven that 7 is the minimum number of liters of fuel needed.\n\n\n
Example 3:
\n\nInput: roads = [], seats = 1\nOutput: 0\nExplanation: No representatives need to travel to the capital city.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
roads.length == n - 1
roads[i].length == 2
0 <= ai, bi < n
ai != bi
roads
represents a valid tree.1 <= seats <= 105
You are given a string s
that consists of the digits '1'
to '9'
and two integers k
and minLength
.
A partition of s
is called beautiful if:
s
is partitioned into k
non-intersecting substrings.minLength
.'2'
, '3'
, '5'
, and '7'
, and the rest of the digits are non-prime.Return the number of beautiful partitions of s
. Since the answer may be very large, return it modulo 109 + 7
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "23542185131", k = 3, minLength = 2\nOutput: 3\nExplanation: There exists three ways to create a beautiful partition:\n"2354 | 218 | 5131"\n"2354 | 21851 | 31"\n"2354218 | 51 | 31"\n\n\n
Example 2:
\n\n\nInput: s = "23542185131", k = 3, minLength = 3\nOutput: 1\nExplanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131".\n\n\n
Example 3:
\n\n\nInput: s = "3312958", k = 3, minLength = 1\nOutput: 1\nExplanation: There exists one way to create a beautiful partition: "331 | 29 | 58".\n\n\n
\n
Constraints:
\n\n1 <= k, minLength <= s.length <= 1000
s
consists of the digits '1'
to '9'
.A valid cut in a circle can be:
\n\nSome valid and invalid cuts are shown in the figures below.
\nGiven the integer n
, return the minimum number of cuts needed to divide a circle into n
equal slices.
\n
Example 1:
\n\nInput: n = 4\nOutput: 2\nExplanation: \nThe above figure shows how cutting the circle twice through the middle divides it into 4 equal slices.\n\n\n
Example 2:
\n\nInput: n = 3\nOutput: 3\nExplanation:\nAt least 3 cuts are needed to divide the circle into 3 equal slices. \nIt can be shown that less than 3 cuts cannot result in 3 slices of equal size and shape.\nAlso note that the first cut will not divide the circle into distinct parts.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
You are given a 0-indexed m x n
binary matrix grid
.
A 0-indexed m x n
difference matrix diff
is created with the following procedure:
ith
row be onesRowi
.jth
column be onesColj
.ith
row be zerosRowi
.jth
column be zerosColj
.diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
Return the difference matrix diff
.
\n
Example 1:
\n\nInput: grid = [[0,1,1],[1,0,1],[0,0,1]]\nOutput: [[0,0,4],[0,0,4],[-2,-2,2]]\nExplanation:\n- diff[0][0] =\n\nonesRow0 + onesCol0 - zerosRow0 - zerosCol0
= 2 + 1 - 1 - 2 = 0 \n- diff[0][1] =onesRow0 + onesCol1 - zerosRow0 - zerosCol1
= 2 + 1 - 1 - 2 = 0 \n- diff[0][2] =onesRow0 + onesCol2 - zerosRow0 - zerosCol2
= 2 + 3 - 1 - 0 = 4 \n- diff[1][0] =onesRow1 + onesCol0 - zerosRow1 - zerosCol0
= 2 + 1 - 1 - 2 = 0 \n- diff[1][1] =onesRow1 + onesCol1 - zerosRow1 - zerosCol1
= 2 + 1 - 1 - 2 = 0 \n- diff[1][2] =onesRow1 + onesCol2 - zerosRow1 - zerosCol2
= 2 + 3 - 1 - 0 = 4 \n- diff[2][0] =onesRow2 + onesCol0 - zerosRow2 - zerosCol0
= 1 + 1 - 2 - 2 = -2\n- diff[2][1] =onesRow2 + onesCol1 - zerosRow2 - zerosCol1
= 1 + 1 - 2 - 2 = -2\n- diff[2][2] =onesRow2 + onesCol2 - zerosRow2 - zerosCol2
= 1 + 3 - 2 - 0 = 2\n
Example 2:
\n\nInput: grid = [[1,1,1],[1,1,1]]\nOutput: [[5,5,5],[5,5,5]]\nExplanation:\n- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5\n- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5\n- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5\n- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5\n- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5\n- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
grid[i][j]
is either 0
or 1
.You are given the customer visit log of a shop represented by a 0-indexed string customers
consisting only of characters 'N'
and 'Y'
:
ith
character is 'Y'
, it means that customers come at the ith
hour'N'
indicates that no customers come at the ith
hour.If the shop closes at the jth
hour (0 <= j <= n
), the penalty is calculated as follows:
1
.1
.Return the earliest hour at which the shop must be closed to incur a minimum penalty.
\n\nNote that if a shop closes at the jth
hour, it means the shop is closed at the hour j
.
\n
Example 1:
\n\n\nInput: customers = "YYNY"\nOutput: 2\nExplanation: \n- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.\n- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.\n- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.\n- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.\n- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.\nClosing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.\n\n\n
Example 2:
\n\n\nInput: customers = "NNNNN"\nOutput: 0\nExplanation: It is best to close the shop at the 0th hour as no customers arrive.\n\n
Example 3:
\n\n\nInput: customers = "YYYY"\nOutput: 4\nExplanation: It is best to close the shop at the 4th hour as customers arrive at each hour.\n\n\n
\n
Constraints:
\n\n1 <= customers.length <= 105
customers
consists only of characters 'Y'
and 'N'
.Given a string of digits s
, return the number of palindromic subsequences of s
having length 5
. Since the answer may be very large, return it modulo 109 + 7
.
Note:
\n\n\n
Example 1:
\n\n\nInput: s = "103301"\nOutput: 2\nExplanation: \nThere are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301". \nTwo of them (both equal to "10301") are palindromic.\n\n\n
Example 2:
\n\n\nInput: s = "0000000"\nOutput: 21\nExplanation: All 21 subsequences are "00000", which is palindromic.\n\n\n
Example 3:
\n\n\nInput: s = "9999900000"\nOutput: 2\nExplanation: The only two palindromic subsequences are "99999" and "00000".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of digits.Given a positive integer n
, find the pivot integer x
such that:
1
and x
inclusively equals the sum of all elements between x
and n
inclusively.Return the pivot integer x
. If no such integer exists, return -1
. It is guaranteed that there will be at most one pivot index for the given input.
\n
Example 1:
\n\n\nInput: n = 8\nOutput: 6\nExplanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.\n\n\n
Example 2:
\n\n\nInput: n = 1\nOutput: 1\nExplanation: 1 is the pivot integer since: 1 = 1.\n\n\n
Example 3:
\n\n\nInput: n = 4\nOutput: -1\nExplanation: It can be proved that no such integer exist.\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You are given two strings s
and t
consisting of only lowercase English letters.
Return the minimum number of characters that need to be appended to the end of s
so that t
becomes a subsequence of s
.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
\n\n\n
Example 1:
\n\n\nInput: s = "coaching", t = "coding"\nOutput: 4\nExplanation: Append the characters "ding" to the end of s so that s = "coachingding".\nNow, t is a subsequence of s ("coachingding").\nIt can be shown that appending any 3 characters to the end of s will never make t a subsequence.\n\n\n
Example 2:
\n\n\nInput: s = "abcde", t = "a"\nOutput: 0\nExplanation: t is already a subsequence of s ("abcde").\n\n\n
Example 3:
\n\n\nInput: s = "z", t = "abcde"\nOutput: 5\nExplanation: Append the characters "abcde" to the end of s so that s = "zabcde".\nNow, t is a subsequence of s ("zabcde").\nIt can be shown that appending any 4 characters to the end of s will never make t a subsequence.\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 105
s
and t
consist only of lowercase English letters.You are given the head
of a linked list.
Remove every node which has a node with a greater value anywhere to the right side of it.
\n\nReturn the head
of the modified linked list.
\n
Example 1:
\n\nInput: head = [5,2,13,3,8]\nOutput: [13,8]\nExplanation: The nodes that should be removed are 5, 2 and 3.\n- Node 13 is to the right of node 5.\n- Node 13 is to the right of node 2.\n- Node 8 is to the right of node 3.\n\n\n
Example 2:
\n\n\nInput: head = [1,1,1,1]\nOutput: [1,1,1,1]\nExplanation: Every node has value 1, so no nodes are removed.\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 105
You are given an array nums
of size n
consisting of distinct integers from 1
to n
and a positive integer k
.
Return the number of non-empty subarrays in nums
that have a median equal to k
.
Note:
\n\n[2,3,1,4]
is 2
, and the median of [8,4,3,5,1]
is 4
.\n
Example 1:
\n\n\nInput: nums = [3,2,1,4,5], k = 4\nOutput: 3\nExplanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,1], k = 3\nOutput: 1\nExplanation: [3] is the only subarray that has a median equal to 3.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
1 <= nums[i], k <= n
nums
are distinct.A sentence is a list of words that are separated by a single space with no leading or trailing spaces.
\n\n"Hello World"
, "HELLO"
, "hello world hello world"
are all sentences.Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different.
\n\nA sentence is circular if:
\n\nFor example, "leetcode exercises sound delightful"
, "eetcode"
, "leetcode eats soul"
are all circular sentences. However, "Leetcode is cool"
, "happy Leetcode"
, "Leetcode"
and "I like Leetcode"
are not circular sentences.
Given a string sentence
, return true
if it is circular. Otherwise, return false
.
\n
Example 1:
\n\n\nInput: sentence = "leetcode exercises sound delightful"\nOutput: true\nExplanation: The words in sentence are ["leetcode", "exercises", "sound", "delightful"].\n- leetcode's last character is equal to exercises's first character.\n- exercises's last character is equal to sound's first character.\n- sound's last character is equal to delightful's first character.\n- delightful's last character is equal to leetcode's first character.\nThe sentence is circular.\n\n
Example 2:
\n\n\nInput: sentence = "eetcode"\nOutput: true\nExplanation: The words in sentence are ["eetcode"].\n- eetcode's last character is equal to eetcode's first character.\nThe sentence is circular.\n\n
Example 3:
\n\n\nInput: sentence = "Leetcode is cool"\nOutput: false\nExplanation: The words in sentence are ["Leetcode", "is", "cool"].\n- Leetcode's last character is not equal to is's first character.\nThe sentence is not circular.\n\n
\n
Constraints:
\n\n1 <= sentence.length <= 500
sentence
consist of only lowercase and uppercase English letters and spaces.sentence
are separated by a single space.You are given a positive integer array skill
of even length n
where skill[i]
denotes the skill of the ith
player. Divide the players into n / 2
teams of size 2
such that the total skill of each team is equal.
The chemistry of a team is equal to the product of the skills of the players on that team.
\n\nReturn the sum of the chemistry of all the teams, or return -1
if there is no way to divide the players into teams such that the total skill of each team is equal.
\n
Example 1:
\n\n\nInput: skill = [3,2,5,1,3,4]\nOutput: 22\nExplanation: \nDivide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.\nThe sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22.\n\n\n
Example 2:
\n\n\nInput: skill = [3,4]\nOutput: 12\nExplanation: \nThe two players form a team with a total skill of 7.\nThe chemistry of the team is 3 * 4 = 12.\n\n\n
Example 3:
\n\n\nInput: skill = [1,1,2,3]\nOutput: -1\nExplanation: \nThere is no way to divide the players into teams such that the total skill of each team is equal.\n\n\n
\n
Constraints:
\n\n2 <= skill.length <= 105
skill.length
is even.1 <= skill[i] <= 1000
You are given a positive integer n
representing n
cities numbered from 1
to n
. You are also given a 2D array roads
where roads[i] = [ai, bi, distancei]
indicates that there is a bidirectional road between cities ai
and bi
with a distance equal to distancei
. The cities graph is not necessarily connected.
The score of a path between two cities is defined as the minimum distance of a road in this path.
\n\nReturn the minimum possible score of a path between cities 1
and n
.
Note:
\n\n1
and n
multiple times along the path.1
and n
.\n
Example 1:
\n\nInput: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]\nOutput: 5\nExplanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.\nIt can be shown that no other path has less score.\n\n\n
Example 2:
\n\nInput: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]\nOutput: 2\nExplanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
1 <= roads.length <= 105
roads[i].length == 3
1 <= ai, bi <= n
ai != bi
1 <= distancei <= 104
1
and n
.You are given a positive integer n
representing the number of nodes in an undirected graph. The nodes are labeled from 1
to n
.
You are also given a 2D integer array edges
, where edges[i] = [ai, bi]
indicates that there is a bidirectional edge between nodes ai
and bi
. Notice that the given graph may be disconnected.
Divide the nodes of the graph into m
groups (1-indexed) such that:
[ai, bi]
, if ai
belongs to the group with index x
, and bi
belongs to the group with index y
, then |y - x| = 1
.Return the maximum number of groups (i.e., maximum m
) into which you can divide the nodes. Return -1
if it is impossible to group the nodes with the given conditions.
\n
Example 1:
\n\nInput: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]\nOutput: 4\nExplanation: As shown in the image we:\n- Add node 5 to the first group.\n- Add node 1 to the second group.\n- Add nodes 2 and 4 to the third group.\n- Add nodes 3 and 6 to the fourth group.\nWe can see that every edge is satisfied.\nIt can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.\n\n\n
Example 2:
\n\n\nInput: n = 3, edges = [[1,2],[2,3],[3,1]]\nOutput: -1\nExplanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.\nIt can be shown that no grouping is possible.\n\n\n
\n
Constraints:
\n\n1 <= n <= 500
1 <= edges.length <= 104
edges[i].length == 2
1 <= ai, bi <= n
ai != bi
The value of an alphanumeric string can be defined as:
\n\n10
, if it comprises of digits only.Given an array strs
of alphanumeric strings, return the maximum value of any string in strs
.
\n
Example 1:
\n\n\nInput: strs = ["alic3","bob","3","4","00000"]\nOutput: 5\nExplanation: \n- "alic3" consists of both letters and digits, so its value is its length, i.e. 5.\n- "bob" consists only of letters, so its value is also its length, i.e. 3.\n- "3" consists only of digits, so its value is its numeric equivalent, i.e. 3.\n- "4" also consists only of digits, so its value is 4.\n- "00000" consists only of digits, so its value is 0.\nHence, the maximum value is 5, of "alic3".\n\n\n
Example 2:
\n\n\nInput: strs = ["1","01","001","0001"]\nOutput: 1\nExplanation: \nEach string in the array has value 1. Hence, we return 1.\n\n\n
\n
Constraints:
\n\n1 <= strs.length <= 100
1 <= strs[i].length <= 9
strs[i]
consists of only lowercase English letters and digits.There is an undirected graph consisting of n
nodes numbered from 0
to n - 1
. You are given a 0-indexed integer array vals
of length n
where vals[i]
denotes the value of the ith
node.
You are also given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting nodes ai
and bi.
A star graph is a subgraph of the given graph having a center node containing 0
or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.
The image below shows star graphs with 3
and 4
neighbors respectively, centered at the blue node.
The star sum is the sum of the values of all the nodes present in the star graph.
\n\nGiven an integer k
, return the maximum star sum of a star graph containing at most k
edges.
\n
Example 1:
\n\nInput: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2\nOutput: 16\nExplanation: The above diagram represents the input graph.\nThe star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.\nIt can be shown it is not possible to get a star graph with a sum greater than 16.\n\n\n
Example 2:
\n\n\nInput: vals = [-5], edges = [], k = 0\nOutput: -5\nExplanation: There is only one possible star graph, which is node 0 itself.\nHence, we return -5.\n\n\n
\n
Constraints:
\n\nn == vals.length
1 <= n <= 105
-104 <= vals[i] <= 104
0 <= edges.length <= min(n * (n - 1) / 2
, 105)
edges[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
0 <= k <= n - 1
You are given a 0-indexed integer array stones
sorted in strictly increasing order representing the positions of stones in a river.
A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.
\n\nThe length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.
\n\nstones[i]
and is jumping to stones[j]
, the length of the jump is |stones[i] - stones[j]|
.The cost of a path is the maximum length of a jump among all jumps in the path.
\n\nReturn the minimum cost of a path for the frog.
\n\n\n
Example 1:
\n\nInput: stones = [0,2,5,6,7]\nOutput: 5\nExplanation: The above figure represents one of the optimal paths the frog can take.\nThe cost of this path is 5, which is the maximum length of a jump.\nSince it is not possible to achieve a cost of less than 5, we return it.\n\n\n
Example 2:
\n\nInput: stones = [0,3,9]\nOutput: 9\nExplanation: \nThe frog can jump directly to the last stone and come back to the first stone. \nIn this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.\nIt can be shown that this is the minimum achievable cost.\n\n\n
\n
Constraints:
\n\n2 <= stones.length <= 105
0 <= stones[i] <= 109
stones[0] == 0
stones
is sorted in a strictly increasing order.You are given two 0-indexed integer arrays nums1
and nums2
, of equal length n
.
In one operation, you can swap the values of any two indices of nums1
. The cost of this operation is the sum of the indices.
Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i]
for all 0 <= i <= n - 1
after performing all the operations.
Return the minimum total cost such that nums1
and nums2
satisfy the above condition. In case it is not possible, return -1
.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5]\nOutput: 10\nExplanation: \nOne of the ways we can perform the operations is:\n- Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5]\n- Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5].\n- Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4].\nWe can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10.\nNote that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3]\nOutput: 10\nExplanation: \nOne of the ways we can perform the operations is:\n- Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3].\n- Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2].\nThe total cost needed here is 10, which is the minimum possible.\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,2,2], nums2 = [1,2,2]\nOutput: -1\nExplanation: \nIt can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.\nHence, we return -1.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= n
You are given an m x n
matrix grid
consisting of positive integers.
Perform the following operation until grid
becomes empty:
Note that the number of columns decreases by one after each operation.
\n\nReturn the answer after performing the operations described above.
\n\n\n
Example 1:
\n\nInput: grid = [[1,2,4],[3,3,1]]\nOutput: 8\nExplanation: The diagram above shows the removed values in each step.\n- In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.\n- In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.\n- In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.\nThe final answer = 4 + 3 + 1 = 8.\n\n\n
Example 2:
\n\nInput: grid = [[10]]\nOutput: 10\nExplanation: The diagram above shows the removed values in each step.\n- In the first operation, we remove 10 from the first row. We add 10 to the answer.\nThe final answer = 10.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
1 <= grid[i][j] <= 100
You are given an integer array nums
. A subsequence of nums
is called a square streak if:
2
, andReturn the length of the longest square streak in nums
, or return -1
if there is no square streak.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,3,6,16,8,2]\nOutput: 3\nExplanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].\n- 4 = 2 * 2.\n- 16 = 4 * 4.\nTherefore, [4,16,2] is a square streak.\nIt can be shown that every subsequence of length 4 is not a square streak.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,5,6,7]\nOutput: -1\nExplanation: There is no square streak in nums so return -1.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
2 <= nums[i] <= 105
You are given an integer n
representing the size of a 0-indexed memory array. All memory units are initially free.
You have a memory allocator with the following functionalities:
\n\nsize
consecutive free memory units and assign it the id mID
.mID
.Note that:
\n\nmID
.mID
, even if they were allocated in different blocks.Implement the Allocator
class:
Allocator(int n)
Initializes an Allocator
object with a memory array of size n
.int allocate(int size, int mID)
Find the leftmost block of size
consecutive free memory units and allocate it with the id mID
. Return the block's first index. If such a block does not exist, return -1
.int freeMemory(int mID)
Free all memory units with the id mID
. Return the number of memory units you have freed.\n
Example 1:
\n\n\nInput\n["Allocator", "allocate", "allocate", "allocate", "freeMemory", "allocate", "allocate", "allocate", "freeMemory", "allocate", "freeMemory"]\n[[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]]\nOutput\n[null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0]\n\nExplanation\nAllocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.\nloc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0.\nloc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1.\nloc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2.\nloc.freeMemory(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2.\nloc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3.\nloc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1.\nloc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6.\nloc.freeMemory(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1.\nloc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.\nloc.freeMemory(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.\n\n\n
\n
Constraints:
\n\n1 <= n, size, mID <= 1000
1000
calls will be made to allocate
and freeMemory
.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:
queries[i]
is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4
directions: up, down, left, and right.After the process, answer[i]
is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times.
Return the resulting array answer
.
\n
Example 1:
\n\nInput: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]\nOutput: [5,8,1]\nExplanation: The diagrams above show which cells we visit to get points for each query.\n\n
Example 2:
\n\nInput: grid = [[5,2,1],[1,1,2]], queries = [3]\nOutput: [0]\nExplanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
k == queries.length
1 <= k <= 104
1 <= grid[i][j], queries[i] <= 106
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:
queries[i]
is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4
directions: up, down, left, and right.After the process, answer[i]
is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times.
Return the resulting array answer
.
\n
Example 1:
\n\nInput: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]\nOutput: [5,8,1]\nExplanation: The diagrams above show which cells we visit to get points for each query.\n\n
Example 2:
\n\nInput: grid = [[5,2,1],[1,1,2]], queries = [3]\nOutput: [0]\nExplanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
k == queries.length
1 <= k <= 104
1 <= grid[i][j], queries[i] <= 106
You are given a 0-indexed string array words
.
Two strings are similar if they consist of the same characters.
\n\n"abca"
and "cba"
are similar since both consist of characters 'a'
, 'b'
, and 'c'
."abacba"
and "bcfd"
are not similar since they do not consist of the same characters.Return the number of pairs (i, j)
such that 0 <= i < j <= word.length - 1
and the two strings words[i]
and words[j]
are similar.
\n
Example 1:
\n\n\nInput: words = ["aba","aabb","abcd","bac","aabc"]\nOutput: 2\nExplanation: There are 2 pairs that satisfy the conditions:\n- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. \n- i = 3 and j = 4 : both words[3] and words[4] only consist of characters 'a', 'b', and 'c'. \n\n\n
Example 2:
\n\n\nInput: words = ["aabb","ab","ba"]\nOutput: 3\nExplanation: There are 3 pairs that satisfy the conditions:\n- i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. \n- i = 0 and j = 2 : both words[0] and words[2] only consist of characters 'a' and 'b'.\n- i = 1 and j = 2 : both words[1] and words[2] only consist of characters 'a' and 'b'.\n\n\n
Example 3:
\n\n\nInput: words = ["nba","cba","dba"]\nOutput: 0\nExplanation: Since there does not exist any pair that satisfies the conditions, we return 0.\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
consist of only lowercase English letters.You are given a positive integer n
.
Continuously replace n
with the sum of its prime factors.
n
multiple times, it should be included in the sum as many times as it divides n
.Return the smallest value n
will take on.
\n
Example 1:
\n\n\nInput: n = 15\nOutput: 5\nExplanation: Initially, n = 15.\n15 = 3 * 5, so replace n with 3 + 5 = 8.\n8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6.\n6 = 2 * 3, so replace n with 2 + 3 = 5.\n5 is the smallest value n will take on.\n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: 3\nExplanation: Initially, n = 3.\n3 is the smallest value n will take on.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
There is an undirected graph consisting of n
nodes numbered from 1
to n
. You are given the integer n
and a 2D array edges
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
. The graph can be disconnected.
You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.
\n\nReturn true
if it is possible to make the degree of each node in the graph even, otherwise return false
.
The degree of a node is the number of edges connected to it.
\n\n\n
Example 1:
\n\nInput: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]]\nOutput: true\nExplanation: The above diagram shows a valid way of adding an edge.\nEvery node in the resulting graph is connected to an even number of edges.\n\n\n
Example 2:
\n\nInput: n = 4, edges = [[1,2],[3,4]]\nOutput: true\nExplanation: The above diagram shows a valid way of adding two edges.\n\n
Example 3:
\n\nInput: n = 4, edges = [[1,2],[1,3],[1,4]]\nOutput: false\nExplanation: It is not possible to obtain a valid graph with adding at most 2 edges.\n\n
\n
Constraints:
\n\n3 <= n <= 105
2 <= edges.length <= 105
edges[i].length == 2
1 <= ai, bi <= n
ai != bi
You are given an integer n
. There is a complete binary tree with 2n - 1
nodes. The root of that tree is the node with the value 1
, and every node with a value val
in the range [1, 2n - 1 - 1]
has two children where:
2 * val
, and2 * val + 1
.You are also given a 2D integer array queries
of length m
, where queries[i] = [ai, bi]
. For each query, solve the following problem:
ai
and bi
.ai
and bi
.Note that:
\n\nReturn an array answer
of length m
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: n = 3, queries = [[5,3],[4,7],[2,3]]\nOutput: [4,5,3]\nExplanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n- After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes [5,2,1,3]. Thus answer to the first query is 4. We delete the added edge and process the next query.\n- After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes [4,2,1,3,7]. Thus answer to the second query is 5. We delete the added edge and process the next query.\n- After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes [2,1,3]. Thus answer to the third query is 3. We delete the added edge.\n\n\n
Example 2:
\n\nInput: n = 2, queries = [[1,2]]\nOutput: [2]\nExplanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n- After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes [2,1]. Thus answer for the first query is 2. We delete the added edge.\n\n\n
\n
Constraints:
\n\n2 <= n <= 30
m == queries.length
1 <= m <= 105
queries[i].length == 2
1 <= ai, bi <= 2n - 1
ai != bi
You are given a 0-indexed integer array forts
of length n
representing the positions of several forts. forts[i]
can be -1
, 0
, or 1
where:
-1
represents there is no fort at the ith
position.0
indicates there is an enemy fort at the ith
position.1
indicates the fort at the ith
the position is under your command.Now you have decided to move your army from one of your forts at position i
to an empty position j
such that:
0 <= i, j <= n - 1
k
where min(i,j) < k < max(i,j)
, forts[k] == 0.
While moving the army, all the enemy forts that come in the way are captured.
\n\nReturn the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0
.
\n
Example 1:
\n\n\nInput: forts = [1,0,0,-1,0,0,0,0,1]\nOutput: 4\nExplanation:\n- Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2.\n- Moving the army from position 8 to position 3 captures 4 enemy forts.\nSince 4 is the maximum number of enemy forts that can be captured, we return 4.\n\n\n
Example 2:
\n\n\nInput: forts = [0,0,1,-1]\nOutput: 0\nExplanation: Since no enemy fort can be captured, 0 is returned.\n\n\n
\n
Constraints:
\n\n1 <= forts.length <= 1000
-1 <= forts[i] <= 1
You are given two string arrays positive_feedback
and negative_feedback
, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative.
Initially every student has 0
points. Each positive word in a feedback report increases the points of a student by 3
, whereas each negative word decreases the points by 1
.
You are given n
feedback reports, represented by a 0-indexed string array report
and a 0-indexed integer array student_id
, where student_id[i]
represents the ID of the student who has received the feedback report report[i]
. The ID of each student is unique.
Given an integer k
, return the top k
students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.
\n
Example 1:
\n\n\nInput: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is studious","the student is smart"], student_id = [1,2], k = 2\nOutput: [1,2]\nExplanation: \nBoth the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher.\n\n\n
Example 2:
\n\n\nInput: positive_feedback = ["smart","brilliant","studious"], negative_feedback = ["not"], report = ["this student is not studious","the student is smart"], student_id = [1,2], k = 2\nOutput: [2,1]\nExplanation: \n- The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points. \n- The student with ID 2 has 1 positive feedback, so he has 3 points. \nSince student 2 has more points, [2,1] is returned.\n\n\n
\n
Constraints:
\n\n1 <= positive_feedback.length, negative_feedback.length <= 104
1 <= positive_feedback[i].length, negative_feedback[j].length <= 100
positive_feedback[i]
and negative_feedback[j]
consists of lowercase English letters.positive_feedback
and negative_feedback
.n == report.length == student_id.length
1 <= n <= 104
report[i]
consists of lowercase English letters and spaces ' '
.report[i]
.1 <= report[i].length <= 100
1 <= student_id[i] <= 109
student_id[i]
are unique.1 <= k <= n
We have two arrays arr1
and arr2
which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
arr1
contains uniqueCnt1
distinct positive integers, each of which is not divisible by divisor1
.arr2
contains uniqueCnt2
distinct positive integers, each of which is not divisible by divisor2
.arr1
and arr2
.Given divisor1
, divisor2
, uniqueCnt1
, and uniqueCnt2
, return the minimum possible maximum integer that can be present in either array.
\n
Example 1:
\n\n\nInput: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3\nOutput: 4\nExplanation: \nWe can distribute the first 4 natural numbers into arr1 and arr2.\narr1 = [1] and arr2 = [2,3,4].\nWe can see that both arrays satisfy all the conditions.\nSince the maximum value is 4, we return it.\n\n\n
Example 2:
\n\n\nInput: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1\nOutput: 3\nExplanation: \nHere arr1 = [1,2], and arr2 = [3] satisfy all conditions.\nSince the maximum value is 3, we return it.\n\n
Example 3:
\n\n\nInput: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2\nOutput: 15\nExplanation: \nHere, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6].\nIt can be shown that it is not possible to obtain a lower maximum satisfying all conditions. \n\n\n
\n
Constraints:
\n\n2 <= divisor1, divisor2 <= 105
1 <= uniqueCnt1, uniqueCnt2 < 109
2 <= uniqueCnt1 + uniqueCnt2 <= 109
You are given a string s
containing one or more words. Every consecutive pair of words is separated by a single space ' '
.
A string t
is an anagram of string s
if the ith
word of t
is a permutation of the ith
word of s
.
"acb dfe"
is an anagram of "abc def"
, but "def cab"
and "adc bef"
are not.Return the number of distinct anagrams of s
. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "too hot"\nOutput: 18\nExplanation: Some of the anagrams of the given string are "too hot", "oot hot", "oto toh", "too toh", and "too oht".\n\n\n
Example 2:
\n\n\nInput: s = "aa"\nOutput: 1\nExplanation: There is only one anagram possible for the given string.\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters and spaces ' '
.You are given a 0-indexed circular string array words
and a string target
. A circular array means that the array's end connects to the array's beginning.
words[i]
is words[(i + 1) % n]
and the previous element of words[i]
is words[(i - 1 + n) % n]
, where n
is the length of words
.Starting from startIndex
, you can move to either the next word or the previous word with 1
step at a time.
Return the shortest distance needed to reach the string target
. If the string target
does not exist in words
, return -1
.
\n
Example 1:
\n\n\nInput: words = ["hello","i","am","leetcode","hello"], target = "hello", startIndex = 1\nOutput: 1\nExplanation: We start from index 1 and can reach "hello" by\n- moving 3 units to the right to reach index 4.\n- moving 2 units to the left to reach index 4.\n- moving 4 units to the right to reach index 0.\n- moving 1 unit to the left to reach index 0.\nThe shortest distance to reach "hello" is 1.\n\n\n
Example 2:
\n\n\nInput: words = ["a","b","leetcode"], target = "leetcode", startIndex = 0\nOutput: 1\nExplanation: We start from index 0 and can reach "leetcode" by\n- moving 2 units to the right to reach index 3.\n- moving 1 unit to the left to reach index 3.\nThe shortest distance to reach "leetcode" is 1.\n\n
Example 3:
\n\n\nInput: words = ["i","eat","leetcode"], target = "ate", startIndex = 0\nOutput: -1\nExplanation: Since "ate" does not exist in words
, we return -1.\n
\n\n\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 100
words[i]
and target
consist of only lowercase English letters.0 <= startIndex < words.length
You are given a string s
consisting of the characters 'a'
, 'b'
, and 'c'
and a non-negative integer k
. Each minute, you may take either the leftmost character of s
, or the rightmost character of s
.
Return the minimum number of minutes needed for you to take at least k
of each character, or return -1
if it is not possible to take k
of each character.
\n
Example 1:
\n\n\nInput: s = "aabaaaacaabc", k = 2\nOutput: 8\nExplanation: \nTake three characters from the left of s. You now have two 'a' characters, and one 'b' character.\nTake five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.\nA total of 3 + 5 = 8 minutes is needed.\nIt can be proven that 8 is the minimum number of minutes needed.\n\n\n
Example 2:
\n\n\nInput: s = "a", k = 1\nOutput: -1\nExplanation: It is not possible to take one 'b' or 'c' so return -1.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of only the letters 'a'
, 'b'
, and 'c'
.0 <= k <= s.length
You are given an array of positive integers price
where price[i]
denotes the price of the ith
candy and a positive integer k
.
The store sells baskets of k
distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.
Return the maximum tastiness of a candy basket.
\n\n\n
Example 1:
\n\n\nInput: price = [13,5,1,8,21,2], k = 3\nOutput: 8\nExplanation: Choose the candies with the prices [13,5,21].\nThe tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8.\nIt can be proven that 8 is the maximum tastiness that can be achieved.\n\n\n
Example 2:
\n\n\nInput: price = [1,3,1], k = 2\nOutput: 2\nExplanation: Choose the candies with the prices [1,3].\nThe tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2.\nIt can be proven that 2 is the maximum tastiness that can be achieved.\n\n\n
Example 3:
\n\n\nInput: price = [7,7,7,7], k = 2\nOutput: 0\nExplanation: Choosing any two distinct candies from the candies we have will result in a tastiness of 0.\n\n\n
\n
Constraints:
\n\n2 <= k <= price.length <= 105
1 <= price[i] <= 109
You are given an array nums
consisting of positive integers and an integer k
.
Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k
.
Return the number of distinct great partitions. Since the answer may be too large, return it modulo 109 + 7
.
Two partitions are considered distinct if some element nums[i]
is in different groups in the two partitions.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4], k = 4\nOutput: 6\nExplanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).\n\n\n
Example 2:
\n\n\nInput: nums = [3,3,3], k = 4\nOutput: 0\nExplanation: There are no great partitions for this array.\n\n\n
Example 3:
\n\n\nInput: nums = [6,6], k = 2\nOutput: 2\nExplanation: We can either put nums[0] in the first partition or in the second partition.\nThe great partitions will be ([6], [6]) and ([6], [6]).\n\n\n
\n
Constraints:
\n\n1 <= nums.length, k <= 1000
1 <= nums[i] <= 109
Given an integer num
, return the number of digits in num
that divide num
.
An integer val
divides nums
if nums % val == 0
.
\n
Example 1:
\n\n\nInput: num = 7\nOutput: 1\nExplanation: 7 divides itself, hence the answer is 1.\n\n\n
Example 2:
\n\n\nInput: num = 121\nOutput: 2\nExplanation: 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2.\n\n\n
Example 3:
\n\n\nInput: num = 1248\nOutput: 4\nExplanation: 1248 is divisible by all of its digits, hence the answer is 4.\n\n\n
\n
Constraints:
\n\n1 <= num <= 109
num
does not contain 0
as one of its digits.Given an array of positive integers nums
, return the number of distinct prime factors in the product of the elements of nums
.
Note that:
\n\n1
is called prime if it is divisible by only 1
and itself.val1
is a factor of another integer val2
if val2 / val1
is an integer.\n
Example 1:
\n\n\nInput: nums = [2,4,3,7,10,6]\nOutput: 4\nExplanation:\nThe product of all the elements in nums is: 2 * 4 * 3 * 7 * 10 * 6 = 10080 = 25 * 32 * 5 * 7.\nThere are 4 distinct prime factors so we return 4.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,8,16]\nOutput: 1\nExplanation:\nThe product of all the elements in nums is: 2 * 4 * 8 * 16 = 1024 = 210.\nThere is 1 distinct prime factor so we return 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 104
2 <= nums[i] <= 1000
You are given a string s
consisting of digits from 1
to 9
and an integer k
.
A partition of a string s
is called good if:
s
is part of exactly one substring.k
.Return the minimum number of substrings in a good partition of s
. If no good partition of s
exists, return -1
.
Note that:
\n\n"123"
is 123
and the value of "1"
is 1
.\n
Example 1:
\n\n\nInput: s = "165462", k = 60\nOutput: 4\nExplanation: We can partition the string into substrings "16", "54", "6", and "2". Each substring has a value less than or equal to k = 60.\nIt can be shown that we cannot partition the string into less than 4 substrings.\n\n\n
Example 2:
\n\n\nInput: s = "238182", k = 5\nOutput: -1\nExplanation: There is no good partition for this string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is a digit from '1'
to '9'
.1 <= k <= 109
\n\n", - "likes": 378, - "dislikes": 51, - "stats": "{\"totalAccepted\": \"23.4K\", \"totalSubmission\": \"50.1K\", \"totalAcceptedRaw\": 23387, \"totalSubmissionRaw\": 50086, \"acRate\": \"46.7%\"}", + "likes": 382, + "dislikes": 52, + "stats": "{\"totalAccepted\": \"24.4K\", \"totalSubmission\": \"52.4K\", \"totalAcceptedRaw\": 24391, \"totalSubmissionRaw\": 52413, \"acRate\": \"46.5%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -95547,10 +95760,10 @@ "questionId": "2610", "questionFrontendId": "2523", "title": "Closest Prime Numbers in Range", - "content": "
Given two positive integers left
and right
, find the two integers num1
and num2
such that:
left <= num1 < num2 <= right
.num1
and num2
are both prime numbers.num2 - num1
is the minimum amongst all other pairs satisfying the above conditions.Return the positive integer array ans = [num1, num2]
. If there are multiple pairs satisfying these conditions, return the one with the minimum num1
value or [-1, -1]
if such numbers do not exist.
A number greater than 1
is called prime if it is only divisible by 1
and itself.
\n
Example 1:
\n\n\nInput: left = 10, right = 19\nOutput: [11,13]\nExplanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19.\nThe closest gap between any pair is 2, which can be achieved by [11,13] or [17,19].\nSince 11 is smaller than 17, we return the first pair.\n\n\n
Example 2:
\n\n\nInput: left = 4, right = 6\nOutput: [-1,-1]\nExplanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.\n\n\n
\n
Constraints:
\n\n1 <= left <= right <= 106
\n\n", - "likes": 379, - "dislikes": 29, - "stats": "{\"totalAccepted\": \"28K\", \"totalSubmission\": \"71.6K\", \"totalAcceptedRaw\": 28011, \"totalSubmissionRaw\": 71629, \"acRate\": \"39.1%\"}", + "content": "
Given two positive integers left
and right
, find the two integers num1
and num2
such that:
left <= num1 < num2 <= right
.num1
and num2
are prime numbers.num2 - num1
is the minimum amongst all other pairs satisfying the above conditions.Return the positive integer array ans = [num1, num2]
. If there are multiple pairs satisfying these conditions, return the one with the smallest num1
value. If no such numbers exist, return [-1, -1]
.
\n
Example 1:
\n\n\nInput: left = 10, right = 19\nOutput: [11,13]\nExplanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19.\nThe closest gap between any pair is 2, which can be achieved by [11,13] or [17,19].\nSince 11 is smaller than 17, we return the first pair.\n\n\n
Example 2:
\n\n\nInput: left = 4, right = 6\nOutput: [-1,-1]\nExplanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.\n\n\n
\n
Constraints:
\n\n1 <= left <= right <= 106
\n\n", + "likes": 894, + "dislikes": 76, + "stats": "{\"totalAccepted\": \"178.6K\", \"totalSubmission\": \"346.5K\", \"totalAcceptedRaw\": 178563, \"totalSubmissionRaw\": 346453, \"acRate\": \"51.5%\"}", "similarQuestions": "[{\"title\": \"Count Ways to Make Array With Product\", \"titleSlug\": \"count-ways-to-make-array-with-product\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -95568,8 +95781,11 @@ "companyTags": null, "difficulty": "Medium", "isPaidOnly": false, - "solution": null, - "hasSolution": false, + "solution": { + "canSeeDetail": true, + "content": "[TOC]\n\n## Solution\n\n---\n\n### Approach 1: Sieve of Eratosthenes\n\n#### Intuition\n\nWe are given two numbers, `left` and `right`, and we need to find a pair of prime numbers within this range such that their difference is minimized. If multiple pairs have the same minimum difference, we return the one with the smallest values. If no such pair exists, we return `[-1, -1]`.\n\nA simple approach would be to iterate through all numbers in this range, check whether each number is prime, store the primes, and then determine the pair with the smallest difference. However, checking if a number is prime requires verifying that it has no divisors other than `1` and itself. A naive way to do this is to test divisibility for all numbers up to `n`, but a more optimized approach would only check divisibility up to `sqrt(n)`. Even with this optimization, the approach remains too slow. Since `right` can be as large as $10^6$, iterating through all numbers and performing a divisibility check for each would still be inefficient, leading to a Time Limit Exceeded (TLE) error.\n\nA much faster way to find all prime numbers up to a given limit is the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). Instead of checking each number one by one, the sieve marks multiples of each prime in bulk, eliminating the need for repeated divisibility checks. \n\nWe start with a list of numbers from 2 to 100. Notice we skip 1 since it\u2019s not considered a prime. Starting with the smallest prime, 2, we know it\u2019s prime because it hasn\u2019t been marked yet. So, we keep it. Now, we cross out all multiples of 2 (like 4, 6, 8, etc.) because they\u2019re definitely not prime. The next number that isn\u2019t crossed out is 3, so we mark it as a prime. Then, we cross out all multiples of 3 (like 6, 9, 12, etc.). We keep going, finding the next unmarked number (which will be 5), and marking all of its multiples. We do this for 7 as well and continue until we\u2019ve processed all numbers up to the limit.\n\nThe beauty of the Sieve of Eratosthenes is that it saves a lot of time by marking off composites in bulk, rather than testing each number individually to see if it\u2019s prime. By the end, any number that\u2019s still unmarked is a prime.\n\nAs we proceed, we collect all the numbers in an array `primeNumbers`, where `sieve[prime] = 1`. For any marked (non-prime) number, we could also keep track of the specific prime that marked it, though, for this problem, it\u2019s sufficient to identify which numbers are prime.\n\nSince all values lie between 1 and 1000000, we can iterate through the array, check for the minimum difference between two consecutive primes, and return it as the answer.\n\n#### Algorithm\n\nMain Function: `closestPrimes(int left, int right)`\n\n1. Generate Prime Numbers using Sieve:\n - Create an integer array `sieve` of size `(right + 1)`, initialized to `1` (indicating prime numbers).\n - Set `sieve[0]` and `sieve[1]` to `0` (since `0` and `1` are not prime).\n - Iterate through numbers from `2` to `sqrt(right)`:\n - If the number is marked as prime (`sieve[number] == 1`), mark all its multiples as non-prime (`sieve[multiple] = 0`).\n\n2. Collect Prime Numbers in Range:\n - Create a vector `primeNumbers` to store prime numbers within `[left, right]`.\n - Iterate through numbers from `left` to `right`:\n - If `sieve[num] == 1`, add `num` to `primeNumbers`.\n\n3. Find the Closest Prime Pair:\n - If `primeNumbers.size() < 2`, return `{-1, -1}` (since there are not enough primes).\n - Initialize `minDifference` to the maximum integer value and `closestPair` to `{-1, -1}`.\n - Iterate through `primeNumbers` and check consecutive primes:\n - Compute `difference = primeNumbers[index] - primeNumbers[index - 1]`.\n - If `difference` is smaller than `minDifference`, update `closestPair = {primeNumbers[index - 1], primeNumbers[index]}`.\n\n4. Return `closestPair` as the result.\n\nHelper Function: `sieve(int upperLimit)`\n\n1. Create an integer vector `sieve` of size `(upperLimit + 1)`, initialized to `1` (indicating prime numbers).\n2. Set `sieve[0]` and `sieve[1]` to `0` (since `0` and `1` are not prime).\n3. Iterate through numbers from `2` to `sqrt(upperLimit)`:\n - If `sieve[number] == 1`, mark all multiples of `number` as `0` (non-prime).\n4. Return the `sieve` array.\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $R$ be `right` and $L$ be `left`, representing the range within which we search for prime numbers.\n\n- Time Complexity: $O(R \\log(\\log(R)) + R - L)$\n\n The **Sieve of Eratosthenes** runs in $O(R \\log(\\log(R)))$, where $R$ is the upper limit of the sieve. After generating the sieve, iterating through the range $[L, R]$ to collect prime numbers takes $O(R - L)$. Finally, finding the closest prime pair requires $O(R - L)$ operations.\n\n Thus, the overall time complexity is $O(R \\log(\\log(R)) + R - L)$.\n\n- Space Complexity: $O(R)$\n\n The algorithm uses a `sieve` array of size $O(R)$ to mark prime numbers. Additionally, the vector storing prime numbers within the range $[L, R]$ can have at most $O(R - L)$ elements. Thus, the overall space complexity is $O(R)$.\n\n---\n\n### Approach 2: Analyze Distance between twin primes\n\n#### Intuition\n\nTo avoid storing the prime numbers while iterating through the range, we can check if the current number is prime or not. If it is, we can store it and take it's difference with the next prime that we find in this range. Observe that the **Sieve of Eratosthenes** approach cannot be used here, since it uses extra storage to check whether the number is prime or not. The only method left is to iterate through the divisors upto `sqrt(number)` and check if the current number is prime or not.\n\nIn this approach, we take advantage of a special property of prime numbers known as **twin primes**, which are pairs of prime numbers that differ by exactly `2`, such as `(3,5)`, `(11,13)`, and `(17,19)`. Instead of searching through all prime numbers, we can optimize our search by focusing on this pattern. \nA key mathematical observation under the given constraints (`1 \u2264 L,R \u2264 10^6`) is that for any range `[L, R]` where `R - L \u2265 1452`, there is always at least one twin prime pair. This means that if the given range is wide enough (at least `1452` numbers long), we can be certain that a twin prime pair exists. Since no two prime numbers can be closer than a twin prime pair (which has a difference of exactly `2`), we can immediately return this result without further searching. \n \n
Given four integers length
, width
, height
, and mass
, representing the dimensions and mass of a box, respectively, return a string representing the category of the box.
"Bulky"
if:\n\n\t104
.109
.100
, it is "Heavy".
"Bulky"
and "Heavy"
, then its category is "Both"
."Bulky"
nor "Heavy"
, then its category is "Neither"
."Bulky"
but not "Heavy"
, then its category is "Bulky"
."Heavy"
but not "Bulky"
, then its category is "Heavy"
.Note that the volume of the box is the product of its length, width and height.
\n\n\n
Example 1:
\n\n\nInput: length = 1000, width = 35, height = 700, mass = 300\nOutput: "Heavy"\nExplanation: \nNone of the dimensions of the box is greater or equal to 104. \nIts volume = 24500000 <= 109. So it cannot be categorized as "Bulky".\nHowever mass >= 100, so the box is "Heavy".\nSince the box is not "Bulky" but "Heavy", we return "Heavy".\n\n
Example 2:
\n\n\nInput: length = 200, width = 50, height = 800, mass = 50\nOutput: "Neither"\nExplanation: \nNone of the dimensions of the box is greater or equal to 104.\nIts volume = 8 * 106 <= 109. So it cannot be categorized as "Bulky".\nIts mass is also less than 100, so it cannot be categorized as "Heavy" either. \nSince its neither of the two above categories, we return "Neither".\n\n
\n
Constraints:
\n\n1 <= length, width, height <= 105
1 <= mass <= 103
For a stream of integers, implement a data structure that checks if the last k
integers parsed in the stream are equal to value
.
Implement the DataStream class:
\n\nDataStream(int value, int k)
Initializes the object with an empty integer stream and the two integers value
and k
.boolean consec(int num)
Adds num
to the stream of integers. Returns true
if the last k
integers are equal to value
, and false
otherwise. If there are less than k
integers, the condition does not hold true, so returns false
.\n
Example 1:
\n\n\nInput\n["DataStream", "consec", "consec", "consec", "consec"]\n[[4, 3], [4], [4], [4], [3]]\nOutput\n[null, false, false, true, false]\n\nExplanation\nDataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 \ndataStream.consec(4); // Only 1 integer is parsed, so returns False. \ndataStream.consec(4); // Only 2 integers are parsed.\n // Since 2 is less than k, returns False. \ndataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. \ndataStream.consec(3); // The last k integers parsed in the stream are [4,4,3].\n // Since 3 is not equal to value, it returns False.\n\n\n
\n
Constraints:
\n\n1 <= value, num <= 109
1 <= k <= 105
105
calls will be made to consec
.You are given a 0-indexed integer array nums
.
The effective value of three indices i
, j
, and k
is defined as ((nums[i] | nums[j]) & nums[k])
.
The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k)
where 0 <= i, j, k < n
.
Return the xor-beauty of nums
.
Note that:
\n\nval1 | val2
is bitwise OR of val1
and val2
.val1 & val2
is bitwise AND of val1
and val2
.\n
Example 1:
\n\n\nInput: nums = [1,4]\nOutput: 5\nExplanation: \nThe triplets and their corresponding effective values are listed below:\n- (0,0,0) with effective value ((1 | 1) & 1) = 1\n- (0,0,1) with effective value ((1 | 1) & 4) = 0\n- (0,1,0) with effective value ((1 | 4) & 1) = 1\n- (0,1,1) with effective value ((1 | 4) & 4) = 4\n- (1,0,0) with effective value ((4 | 1) & 1) = 1\n- (1,0,1) with effective value ((4 | 1) & 4) = 4\n- (1,1,0) with effective value ((4 | 4) & 1) = 0\n- (1,1,1) with effective value ((4 | 4) & 4) = 4 \nXor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.\n\n
Example 2:
\n\n\nInput: nums = [15,45,20,2,34,35,5,44,32,30]\nOutput: 34\nExplanation: The xor-beauty of the given array is 34.
\n
\n\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed integer array stations
of length n
, where stations[i]
represents the number of power stations in the ith
city.
Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r
, then a power station at city i
can provide power to all cities j
such that |i - j| <= r
and 0 <= i, j <= n - 1
.
|x|
denotes absolute value. For example, |7 - 5| = 2
and |3 - 10| = 7
.The power of a city is the total number of power stations it is being provided power from.
\n\nThe government has sanctioned building k
more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.
Given the two integers r
and k
, return the maximum possible minimum power of a city, if the additional power stations are built optimally.
Note that you can build the k
power stations in multiple cities.
\n
Example 1:
\n\n\nInput: stations = [1,2,4,5,0], r = 1, k = 2\nOutput: 5\nExplanation: \nOne of the optimal ways is to install both the power stations at city 1. \nSo stations will become [1,4,4,5,0].\n- City 0 is provided by 1 + 4 = 5 power stations.\n- City 1 is provided by 1 + 4 + 4 = 9 power stations.\n- City 2 is provided by 4 + 4 + 5 = 13 power stations.\n- City 3 is provided by 5 + 4 = 9 power stations.\n- City 4 is provided by 5 + 0 = 5 power stations.\nSo the minimum power of a city is 5.\nSince it is not possible to obtain a larger power, we return 5.\n\n\n
Example 2:
\n\n\nInput: stations = [4,4,4,4], r = 0, k = 3\nOutput: 4\nExplanation: \nIt can be proved that we cannot make the minimum power of a city greater than 4.\n\n\n
\n
Constraints:
\n\nn == stations.length
1 <= n <= 105
0 <= stations[i] <= 105
0 <= r <= n - 1
0 <= k <= 109
Given an array nums
sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers.
nums
is pos
and the number of negative integers is neg
, then return the maximum of pos
and neg
.Note that 0
is neither positive nor negative.
\n
Example 1:
\n\n\nInput: nums = [-2,-1,-1,1,2,3]\nOutput: 3\nExplanation: There are 3 positive integers and 3 negative integers. The maximum count among them is 3.\n\n\n
Example 2:
\n\n\nInput: nums = [-3,-2,-1,0,0,1,2]\nOutput: 3\nExplanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3.\n\n\n
Example 3:
\n\n\nInput: nums = [5,20,66,1314]\nOutput: 4\nExplanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2000
-2000 <= nums[i] <= 2000
nums
is sorted in a non-decreasing order.\n
Follow up: Can you solve the problem in O(log(n))
time complexity?
You are given a 0-indexed integer array nums
and an integer k
. You have a starting score of 0
.
In one operation:
\n\ni
such that 0 <= i < nums.length
,nums[i]
, andnums[i]
with ceil(nums[i] / 3)
.Return the maximum possible score you can attain after applying exactly k
operations.
The ceiling function ceil(val)
is the least integer greater than or equal to val
.
\n
Example 1:
\n\n\nInput: nums = [10,10,10,10,10], k = 5\nOutput: 50\nExplanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.\n\n\n
Example 2:
\n\n\nInput: nums = [1,10,3,3,3], k = 3\nOutput: 17\nExplanation: You can do the following operations:\nOperation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10.\nOperation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4.\nOperation 3: Select i = 2, so nums becomes [1,2,1,3,3]. Your score increases by 3.\nThe final score is 10 + 4 + 3 = 17.\n\n\n
\n
Constraints:
\n\n1 <= nums.length, k <= 105
1 <= nums[i] <= 109
You are given two 0-indexed strings word1
and word2
.
A move consists of choosing two indices i
and j
such that 0 <= i < word1.length
and 0 <= j < word2.length
and swapping word1[i]
with word2[j]
.
Return true
if it is possible to get the number of distinct characters in word1
and word2
to be equal with exactly one move. Return false
otherwise.
\n
Example 1:
\n\n\nInput: word1 = "ac", word2 = "b"\nOutput: false\nExplanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string.\n\n\n
Example 2:
\n\n\nInput: word1 = "abcc", word2 = "aab"\nOutput: true\nExplanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = "abac" and word2 = "cab", which both have 3 distinct characters.\n\n\n
Example 3:
\n\n\nInput: word1 = "abcde", word2 = "fghij"\nOutput: true\nExplanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.\n\n\n
\n
Constraints:
\n\n1 <= word1.length, word2.length <= 105
word1
and word2
consist of only lowercase English letters.There are k
workers who want to move n
boxes from the right (old) warehouse to the left (new) warehouse. You are given the two integers n
and k
, and a 2D integer array time
of size k x 4
where time[i] = [righti, picki, lefti, puti]
.
The warehouses are separated by a river and connected by a bridge. Initially, all k
workers are waiting on the left side of the bridge. To move the boxes, the ith
worker can do the following:
righti
minutes.picki
minutes.lefti
minutes.puti
minutes.The ith
worker is less efficient than the jth
worker if either condition is met:
lefti + righti > leftj + rightj
lefti + righti == leftj + rightj
and i > j
The following rules regulate the movement of the workers through the bridge:
\n\nReturn the elapsed minutes at which the last box reaches the left side of the bridge.
\n\n\n
Example 1:
\n\nInput: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]
\n\nOutput: 6
\n\nExplanation:
\n\n\nFrom 0 to 1 minutes: worker 2 crosses the bridge to the right.\nFrom 1 to 2 minutes: worker 2 picks up a box from the right warehouse.\nFrom 2 to 6 minutes: worker 2 crosses the bridge to the left.\nFrom 6 to 7 minutes: worker 2 puts a box at the left warehouse.\nThe whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left side of the bridge.\n\n
Example 2:
\n\nInput: n = 3, k = 2, time = [[1,5,1,8],[10,10,10,10]]
\n\nOutput: 37
\n\nExplanation:
\n\n\n\n\n\n
The last box reaches the left side at 37 seconds. Notice, how we do not put the last boxes down, as that would take more time, and they are already on the left with the workers.
\n\n
Constraints:
\n\n1 <= n, k <= 104
time.length == k
time[i].length == 4
1 <= lefti, picki, righti, puti <= 1000
You are given a positive integer array nums
.
nums
.nums
.Return the absolute difference between the element sum and digit sum of nums
.
Note that the absolute difference between two integers x
and y
is defined as |x - y|
.
\n
Example 1:
\n\n\nInput: nums = [1,15,6,3]\nOutput: 9\nExplanation: \nThe element sum of nums is 1 + 15 + 6 + 3 = 25.\nThe digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.\nThe absolute difference between the element sum and digit sum is |25 - 16| = 9.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 0\nExplanation:\nThe element sum of nums is 1 + 2 + 3 + 4 = 10.\nThe digit sum of nums is 1 + 2 + 3 + 4 = 10.\nThe absolute difference between the element sum and digit sum is |10 - 10| = 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2000
1 <= nums[i] <= 2000
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:
1
to every element in the submatrix with the top left corner (row1i, col1i)
and the bottom right corner (row2i, col2i)
. That is, add 1
to mat[x][y]
for all row1i <= x <= row2i
and col1i <= y <= col2i
.Return the matrix mat
after performing every query.
\n
Example 1:
\n\nInput: n = 3, queries = [[1,1,2,2],[0,0,1,1]]\nOutput: [[1,1,0],[1,2,1],[0,1,1]]\nExplanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.\n- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).\n- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).\n\n\n
Example 2:
\n\nInput: n = 2, queries = [[0,0,1,1]]\nOutput: [[1,1],[1,1]]\nExplanation: The diagram above shows the initial matrix and the matrix after the first query.\n- In the first query we add 1 to every element in the matrix.\n\n\n
\n
Constraints:
\n\n1 <= n <= 500
1 <= queries.length <= 104
0 <= row1i <= row2i < n
0 <= col1i <= col2i < n
Given an integer array nums
and an integer k
, return the number of good subarrays of nums
.
A subarray arr
is good if there are at least k
pairs of indices (i, j)
such that i < j
and arr[i] == arr[j]
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1,1,1,1], k = 10\nOutput: 1\nExplanation: The only good subarray is the array nums itself.\n\n\n
Example 2:
\n\n\nInput: nums = [3,1,4,3,2,2,4], k = 2\nOutput: 4\nExplanation: There are 4 different good subarrays:\n- [3,1,4,3,2,2] that has 2 pairs.\n- [3,1,4,3,2,2,4] that has 3 pairs.\n- [1,4,3,2,2,4] that has 2 pairs.\n- [4,3,2,2,4] that has 2 pairs.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i], k <= 109
There exists an undirected and initially unrooted tree with n
nodes indexed from 0
to n - 1
. You are given the integer n
and a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
Each node has an associated price. You are given an integer array price
, where price[i]
is the price of the ith
node.
The price sum of a given path is the sum of the prices of all nodes lying on that path.
\n\nThe tree can be rooted at any node root
of your choice. The incurred cost after choosing root
is the difference between the maximum and minimum price sum amongst all paths starting at root
.
Return the maximum possible cost amongst all possible root choices.
\n\n\n
Example 1:
\n\nInput: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]\nOutput: 24\nExplanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.\n- The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.\n- The second path contains the node [2] with the price [7].\nThe difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.\n\n\n
Example 2:
\n\nInput: n = 3, edges = [[0,1],[1,2]], price = [1,1,1]\nOutput: 2\nExplanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.\n- The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.\n- The second path contains node [0] with a price [1].\nThe difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
edges.length == n - 1
0 <= ai, bi <= n - 1
edges
represents a valid tree.price.length == n
1 <= price[i] <= 105
Given two integer arrays nums1
and nums2
, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1
and nums2
, return -1
.
Note that an integer is said to be common to nums1
and nums2
if both arrays have at least one occurrence of that integer.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3], nums2 = [2,4]\nOutput: 2\nExplanation: The smallest element common to both arrays is 2, so we return 2.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2,3,6], nums2 = [2,3,4,5]\nOutput: 2\nExplanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
1 <= nums1[i], nums2[j] <= 109
nums1
and nums2
are sorted in non-decreasing order.You are given two integer arrays nums1
and nums2
of equal length n
and an integer k
. You can perform the following operation on nums1
:
i
and j
and increment nums1[i]
by k
and decrement nums1[j]
by k
. In other words, nums1[i] = nums1[i] + k
and nums1[j] = nums1[j] - k
.nums1
is said to be equal to nums2
if for all indices i
such that 0 <= i < n
, nums1[i] == nums2[i]
.
Return the minimum number of operations required to make nums1
equal to nums2
. If it is impossible to make them equal, return -1
.
\n
Example 1:
\n\n\nInput: nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3\nOutput: 2\nExplanation: In 2 operations, we can transform nums1 to nums2.\n1st operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].\n2nd operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].\nOne can prove that it is impossible to make arrays equal in fewer operations.\n\n
Example 2:
\n\n\nInput: nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1\nOutput: -1\nExplanation: It can be proved that it is impossible to make the two arrays equal.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
2 <= n <= 105
0 <= nums1[i], nums2[j] <= 109
0 <= k <= 105
You are given two 0-indexed integer arrays nums1
and nums2
of equal length n
and a positive integer k
. You must choose a subsequence of indices from nums1
of length k
.
For chosen indices i0
, i1
, ..., ik - 1
, your score is defined as:
nums1
multiplied with the minimum of the selected elements from nums2
.(nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1])
.Return the maximum possible score.
\n\nA subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1}
by deleting some or no elements.
\n
Example 1:
\n\n\nInput: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3\nOutput: 12\nExplanation: \nThe four possible subsequence scores are:\n- We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.\n- We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6. \n- We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12. \n- We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.\nTherefore, we return the max score, which is 12.\n\n\n
Example 2:
\n\n\nInput: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1\nOutput: 30\nExplanation: \nChoosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 105
0 <= nums1[i], nums2[j] <= 105
1 <= k <= n
There exists an infinitely large grid. You are currently at point (1, 1)
, and you need to reach the point (targetX, targetY)
using a finite number of steps.
In one step, you can move from point (x, y)
to any one of the following points:
(x, y - x)
(x - y, y)
(2 * x, y)
(x, 2 * y)
Given two integers targetX
and targetY
representing the X-coordinate and Y-coordinate of your final position, return true
if you can reach the point from (1, 1)
using some number of steps, and false
otherwise.
\n
Example 1:
\n\n\nInput: targetX = 6, targetY = 9\nOutput: false\nExplanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.\n\n\n
Example 2:
\n\n\nInput: targetX = 4, targetY = 7\nOutput: true\nExplanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).\n\n\n
\n
Constraints:
\n\n1 <= targetX, targetY <= 109
You are given a positive integer n
. Each digit of n
has a sign according to the following rules:
Return the sum of all digits with their corresponding sign.
\n\n\n
Example 1:
\n\n\nInput: n = 521\nOutput: 4\nExplanation: (+5) + (-2) + (+1) = 4.\n\n\n
Example 2:
\n\n\nInput: n = 111\nOutput: 1\nExplanation: (+1) + (-1) + (+1) = 1.\n\n\n
Example 3:
\n\n\nInput: n = 886996\nOutput: 0\nExplanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
\n\n", - "likes": 418, - "dislikes": 21, - "stats": "{\"totalAccepted\": \"73.4K\", \"totalSubmission\": \"107.1K\", \"totalAcceptedRaw\": 73424, \"totalSubmissionRaw\": 107111, \"acRate\": \"68.5%\"}", + "likes": 435, + "dislikes": 22, + "stats": "{\"totalAccepted\": \"80.6K\", \"totalSubmission\": \"117.8K\", \"totalAcceptedRaw\": 80585, \"totalSubmissionRaw\": 117769, \"acRate\": \"68.4%\"}", "similarQuestions": "[{\"title\": \"Add Digits\", \"titleSlug\": \"add-digits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Four Digit Number After Splitting Digits\", \"titleSlug\": \"minimum-sum-of-four-digit-number-after-splitting-digits\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Separate the Digits in an Array\", \"titleSlug\": \"separate-the-digits-in-an-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -96391,9 +96613,9 @@ "questionFrontendId": "2545", "title": "Sort the Students by Their Kth Score", "content": "
There is a class with m
students and n
exams. You are given a 0-indexed m x n
integer matrix score
, where each row represents one student and score[i][j]
denotes the score the ith
student got in the jth
exam. The matrix score
contains distinct integers only.
You are also given an integer k
. Sort the students (i.e., the rows of the matrix) by their scores in the kth
(0-indexed) exam from the highest to the lowest.
Return the matrix after sorting it.
\n\n\n
Example 1:
\n\nInput: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2\nOutput: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]\nExplanation: In the above diagram, S denotes the student, while E denotes the exam.\n- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.\n- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.\n- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.\n\n\n
Example 2:
\n\nInput: score = [[3,4],[5,6]], k = 0\nOutput: [[5,6],[3,4]]\nExplanation: In the above diagram, S denotes the student, while E denotes the exam.\n- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.\n- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.\n\n\n
\n
Constraints:
\n\nm == score.length
n == score[i].length
1 <= m, n <= 250
1 <= score[i][j] <= 105
score
consists of distinct integers.0 <= k < n
You are given two 0-indexed binary strings s
and target
of the same length n
. You can do the following operation on s
any number of times:
i
and j
where 0 <= i, j < n
.s[i]
with (s[i]
OR s[j]
) and s[j]
with (s[i]
XOR s[j]
).For example, if s = "0110"
, you can choose i = 0
and j = 2
, then simultaneously replace s[0]
with (s[0]
OR s[2]
= 0
OR 1
= 1
), and s[2]
with (s[0]
XOR s[2]
= 0
XOR 1
= 1
), so we will have s = "1110"
.
Return true
if you can make the string s
equal to target
, or false
otherwise.
\n
Example 1:
\n\n\nInput: s = "1010", target = "0110"\nOutput: true\nExplanation: We can do the following operations:\n- Choose i = 2 and j = 0. We have now s = "0010".\n- Choose i = 2 and j = 1. We have now s = "0110".\nSince we can make s equal to target, we return true.\n\n\n
Example 2:
\n\n\nInput: s = "11", target = "00"\nOutput: false\nExplanation: It is not possible to make s equal to target with any number of operations.\n\n\n
\n
Constraints:
\n\nn == s.length == target.length
2 <= n <= 105
s
and target
consist of only the digits 0
and 1
.You are given an integer array nums
and an integer k
.
Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split.
\n\nLet trimmed(subarray)
be the version of the subarray where all numbers which appear only once are removed.
trimmed([3,1,2,4,3,4]) = [3,4,3,4].
The importance value of a subarray is k + trimmed(subarray).length
.
[1,2,3,3,3,4,4]
, then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].
The importance value of this subarray will be k + 5
.Return the minimum possible cost of a split of nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1,2,1,3,3], k = 2\nOutput: 8\nExplanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3].\nThe importance value of [1,2] is 2 + (0) = 2.\nThe importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6.\nThe cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,2,1], k = 2\nOutput: 6\nExplanation: We split nums to have two subarrays: [1,2], [1,2,1].\nThe importance value of [1,2] is 2 + (0) = 2.\nThe importance value of [1,2,1] is 2 + (2) = 4.\nThe cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,1,2,1], k = 5\nOutput: 10\nExplanation: We split nums to have one subarray: [1,2,1,2,1].\nThe importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10.\nThe cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
0 <= nums[i] < nums.length
1 <= k <= 109
\n\n", - "likes": 442, - "dislikes": 27, - "stats": "{\"totalAccepted\": \"13.6K\", \"totalSubmission\": \"32.7K\", \"totalAcceptedRaw\": 13615, \"totalSubmissionRaw\": 32697, \"acRate\": \"41.6%\"}", - "similarQuestions": "[{\"title\": \"Coin Change\", \"titleSlug\": \"coin-change\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split Array Largest Sum\", \"titleSlug\": \"split-array-largest-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Divide an Array Into Subarrays With Minimum Cost II\", \"titleSlug\": \"divide-an-array-into-subarrays-with-minimum-cost-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Values by Dividing Array\", \"titleSlug\": \"minimum-sum-of-values-by-dividing-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", + "likes": 450, + "dislikes": 28, + "stats": "{\"totalAccepted\": \"14.6K\", \"totalSubmission\": \"34.4K\", \"totalAcceptedRaw\": 14562, \"totalSubmissionRaw\": 34443, \"acRate\": \"42.3%\"}", + "similarQuestions": "[{\"title\": \"Coin Change\", \"titleSlug\": \"coin-change\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Split Array Largest Sum\", \"titleSlug\": \"split-array-largest-sum\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Divide an Array Into Subarrays With Minimum Cost II\", \"titleSlug\": \"divide-an-array-into-subarrays-with-minimum-cost-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Sum of Values by Dividing Array\", \"titleSlug\": \"minimum-sum-of-values-by-dividing-array\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Minimum Cost to Divide Array Into Subarrays\", \"titleSlug\": \"minimum-cost-to-divide-array-into-subarrays\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ "Let's denote dp[r] = minimum cost to partition the first r elements of nums. What would be the transitions of such dynamic programming?", @@ -96506,7 +96728,7 @@ "content": null, "likes": 41, "dislikes": 9, - "stats": "{\"totalAccepted\": \"1.6K\", \"totalSubmission\": \"2.6K\", \"totalAcceptedRaw\": 1622, \"totalSubmissionRaw\": 2566, \"acRate\": \"63.2%\"}", + "stats": "{\"totalAccepted\": \"1.7K\", \"totalSubmission\": \"2.7K\", \"totalAcceptedRaw\": 1715, \"totalSubmissionRaw\": 2697, \"acRate\": \"63.6%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -96542,9 +96764,9 @@ "questionFrontendId": "2549", "title": "Count Distinct Numbers on Board", "content": "
You are given a positive integer n
, that is initially placed on a board. Every day, for 109
days, you perform the following procedure:
x
present on the board, find all numbers 1 <= i <= n
such that x % i == 1
.Return the number of distinct integers present on the board after 109
days have elapsed.
Note:
\n\n%
stands for the modulo operation. For example, 14 % 3
is 2
.\n
Example 1:
\n\n\nInput: n = 5\nOutput: 4\nExplanation: Initially, 5 is present on the board. \nThe next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. \nAfter that day, 3 will be added to the board because 4 % 3 == 1. \nAt the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. \n\n\n
Example 2:
\n\n\nInput: n = 3\nOutput: 2\nExplanation: \nSince 3 % 2 == 1, 2 will be added to the board. \nAfter a billion days, the only two distinct numbers on the board are 2 and 3. \n\n\n
\n
Constraints:
\n\n1 <= n <= 100
There is a regular convex polygon with n
vertices. The vertices are labeled from 0
to n - 1
in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6
vertices.
Simultaneously, each monkey moves to a neighboring vertex. A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.
\n\nReturn the number of ways the monkeys can move so that at least one collision happens. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 3
\n\nOutput: 6
\n\nExplanation:
\n\nThere are 8 total possible movements.
\nTwo ways such that they collide at some point are:
Example 2:
\n\nInput: n = 4
\n\nOutput: 14
\n\n
Constraints:
\n\n3 <= n <= 109
You have k
bags. You are given a 0-indexed integer array weights
where weights[i]
is the weight of the ith
marble. You are also given the integer k.
Divide the marbles into the k
bags according to the following rules:
ith
marble and jth
marble are in a bag, then all marbles with an index between the ith
and jth
indices should also be in that same bag.i
to j
inclusively, then the cost of the bag is weights[i] + weights[j]
.The score after distributing the marbles is the sum of the costs of all the k
bags.
Return the difference between the maximum and minimum scores among marble distributions.
\n\n\n
Example 1:
\n\n\nInput: weights = [1,3,5,1], k = 2\nOutput: 4\nExplanation: \nThe distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. \nThe distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. \nThus, we return their difference 10 - 6 = 4.\n\n\n
Example 2:
\n\n\nInput: weights = [1, 3], k = 2\nOutput: 0\nExplanation: The only distribution possible is [1],[3]. \nSince both the maximal and minimal score are the same, we return 0.\n\n\n
\n
Constraints:
\n\n1 <= k <= weights.length <= 105
1 <= weights[i] <= 109
Given a 0-indexed integer array nums
of size n
containing all numbers from 1
to n
, return the number of increasing quadruplets.
A quadruplet (i, j, k, l)
is increasing if:
0 <= i < j < k < l < n
, andnums[i] < nums[k] < nums[j] < nums[l]
.\n
Example 1:
\n\n\nInput: nums = [1,3,2,4,5]\nOutput: 2\nExplanation: \n- When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l].\n- When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. \nThere are no other quadruplets, so we return 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 0\nExplanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.\n\n\n
\n
Constraints:
\n\n4 <= nums.length <= 4000
1 <= nums[i] <= nums.length
nums
are unique. nums
is a permutation.Given an array of positive integers nums
, return an array answer
that consists of the digits of each integer in nums
after separating them in the same order they appear in nums
.
To separate the digits of an integer is to get all the digits it has in the same order.
\n\n10921
, the separation of its digits is [1,0,9,2,1]
.\n
Example 1:
\n\n\nInput: nums = [13,25,83,77]\nOutput: [1,3,2,5,8,3,7,7]\nExplanation: \n- The separation of 13 is [1,3].\n- The separation of 25 is [2,5].\n- The separation of 83 is [8,3].\n- The separation of 77 is [7,7].\nanswer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.\n\n\n
Example 2:
\n\n\nInput: nums = [7,1,3,9]\nOutput: [7,1,3,9]\nExplanation: The separation of each integer in nums is itself.\nanswer = [7,1,3,9].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 105
You are given an integer array banned
and two integers n
and maxSum
. You are choosing some number of integers following the below rules:
[1, n]
.banned
.maxSum
.Return the maximum number of integers you can choose following the mentioned rules.
\n\n\n
Example 1:
\n\n\nInput: banned = [1,6,5], n = 5, maxSum = 6\nOutput: 2\nExplanation: You can choose the integers 2 and 4.\n2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum.\n\n\n
Example 2:
\n\n\nInput: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1\nOutput: 0\nExplanation: You cannot choose any integer while following the mentioned conditions.\n\n\n
Example 3:
\n\n\nInput: banned = [11], n = 7, maxSum = 50\nOutput: 7\nExplanation: You can choose the integers 1, 2, 3, 4, 5, 6, and 7.\nThey are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.\n\n\n
\n
Constraints:
\n\n1 <= banned.length <= 104
1 <= banned[i], n <= 104
1 <= maxSum <= 109
There are some prizes on the X-axis. You are given an integer array prizePositions
that is sorted in non-decreasing order, where prizePositions[i]
is the position of the ith
prize. There could be different prizes at the same position on the line. You are also given an integer k
.
You are allowed to select two segments with integer endpoints. The length of each segment must be k
. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.
k = 2
, you can choose segments [1, 3]
and [2, 4]
, and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3
or 2 <= prizePositions[i] <= 4
.Return the maximum number of prizes you can win if you choose the two segments optimally.
\n\n\n
Example 1:
\n\n\nInput: prizePositions = [1,1,2,2,3,3,5], k = 2\nOutput: 7\nExplanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5].\n\n\n
Example 2:
\n\n\nInput: prizePositions = [1,2,3,4], k = 0\nOutput: 2\nExplanation: For this example, one choice for the segments is\n\n[3, 3]
and[4, 4],
and you will be able to get2
prizes. \n
\n
Constraints:
\n\n1 <= prizePositions.length <= 105
1 <= prizePositions[i] <= 109
0 <= k <= 109
prizePositions
is sorted in non-decreasing order.\n\n", - "likes": 578, - "dislikes": 55, - "stats": "{\"totalAccepted\": \"12.2K\", \"totalSubmission\": \"35.1K\", \"totalAcceptedRaw\": 12159, \"totalSubmissionRaw\": 35052, \"acRate\": \"34.7%\"}", + "likes": 587, + "dislikes": 59, + "stats": "{\"totalAccepted\": \"13.1K\", \"totalSubmission\": \"36.9K\", \"totalAcceptedRaw\": 13070, \"totalSubmissionRaw\": 36896, \"acRate\": \"35.4%\"}", "similarQuestions": "[{\"title\": \"Best Time to Buy and Sell Stock III\", \"titleSlug\": \"best-time-to-buy-and-sell-stock-iii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Two Best Non-Overlapping Events\", \"titleSlug\": \"two-best-non-overlapping-events\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -96822,9 +97044,9 @@ "questionFrontendId": "2556", "title": "Disconnect Path in a Binary Matrix by at Most One Flip", "content": "
You are given a 0-indexed m x n
binary matrix grid
. You can move from a cell (row, col)
to any of the cells (row + 1, col)
or (row, col + 1)
that has the value 1
. The matrix is disconnected if there is no path from (0, 0)
to (m - 1, n - 1)
.
You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0)
and (m - 1, n - 1)
.
Return true
if it is possible to make the matrix disconnect or false
otherwise.
Note that flipping a cell changes its value from 0
to 1
or from 1
to 0
.
\n
Example 1:
\n\nInput: grid = [[1,1,1],[1,0,0],[1,1,1]]\nOutput: true\nExplanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid.\n\n\n
Example 2:
\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: false\nExplanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
grid[i][j]
is either 0
or 1
.grid[0][0] == grid[m - 1][n - 1] == 1
You are given an integer array gifts
denoting the number of gifts in various piles. Every second, you do the following:
Return the number of gifts remaining after k
seconds.
\n
Example 1:
\n\n\nInput: gifts = [25,64,9,4,100], k = 4\nOutput: 29\nExplanation: \nThe gifts are taken in the following way:\n- In the first second, the last pile is chosen and 10 gifts are left behind.\n- Then the second pile is chosen and 8 gifts are left behind.\n- After that the first pile is chosen and 5 gifts are left behind.\n- Finally, the last pile is chosen again and 3 gifts are left behind.\nThe final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29.\n\n\n
Example 2:
\n\n\nInput: gifts = [1,1,1,1], k = 4\nOutput: 4\nExplanation: \nIn this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. \nThat is, you can't take any pile with you. \nSo, the total gifts remaining are 4.\n\n\n
\n
Constraints:
\n\n1 <= gifts.length <= 103
1 <= gifts[i] <= 109
1 <= k <= 103
You are given a 0-indexed array of strings words
and a 2D array of integers queries
.
Each query queries[i] = [li, ri]
asks us to find the number of strings present in the range li
to ri
(both inclusive) of words
that start and end with a vowel.
Return an array ans
of size queries.length
, where ans[i]
is the answer to the i
th query.
Note that the vowel letters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
\n
Example 1:
\n\n\nInput: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]\nOutput: [2,3,0]\nExplanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".\nThe answer to the query [0,2] is 2 (strings "aba" and "ece").\nto query [1,4] is 3 (strings "ece", "aa", "e").\nto query [1,1] is 0.\nWe return [2,3,0].\n\n\n
Example 2:
\n\n\nInput: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]\nOutput: [3,2,1]\nExplanation: Every string satisfies the conditions, so we return [3,2,1].\n\n
\n
Constraints:
\n\n1 <= words.length <= 105
1 <= words[i].length <= 40
words[i]
consists only of lowercase English letters.sum(words[i].length) <= 3 * 105
1 <= queries.length <= 105
0 <= li <= ri < words.length
You are given a 0-indexed array of strings words
and a 2D array of integers queries
.
Each query queries[i] = [li, ri]
asks us to find the number of strings present at the indices ranging from li
to ri
(both inclusive) of words
that start and end with a vowel.
Return an array ans
of size queries.length
, where ans[i]
is the answer to the i
th query.
Note that the vowel letters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
\n
Example 1:
\n\n\nInput: words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]\nOutput: [2,3,0]\nExplanation: The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".\nThe answer to the query [0,2] is 2 (strings "aba" and "ece").\nto query [1,4] is 3 (strings "ece", "aa", "e").\nto query [1,1] is 0.\nWe return [2,3,0].\n\n\n
Example 2:
\n\n\nInput: words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]\nOutput: [3,2,1]\nExplanation: Every string satisfies the conditions, so we return [3,2,1].\n\n
\n
Constraints:
\n\n1 <= words.length <= 105
1 <= words[i].length <= 40
words[i]
consists only of lowercase English letters.sum(words[i].length) <= 3 * 105
1 <= queries.length <= 105
0 <= li <= ri < words.length
There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes.
\n\nThe capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed.
\n\nYou are given an integer array nums
representing how much money is stashed in each house. More formally, the ith
house from the left has nums[i]
dollars.
You are also given an integer k
, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k
houses.
Return the minimum capability of the robber out of all the possible ways to steal at least k
houses.
\n
Example 1:
\n\n\nInput: nums = [2,3,5,9], k = 2\nOutput: 5\nExplanation: \nThere are three ways to rob at least 2 houses:\n- Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5.\n- Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9.\n- Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9.\nTherefore, we return min(5, 9, 9) = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [2,7,9,3,1], k = 2\nOutput: 2\nExplanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= (nums.length + 1)/2
You have two fruit baskets containing n
fruits each. You are given two 0-indexed integer arrays basket1
and basket2
representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want:
i
and j
, and swap the ith
fruit of basket1
with the jth
fruit of basket2
.min(basket1[i],basket2[j])
.Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.
\n\nReturn the minimum cost to make both the baskets equal or -1
if impossible.
\n
Example 1:
\n\n\nInput: basket1 = [4,2,2,2], basket2 = [1,4,1,2]\nOutput: 1\nExplanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.\n\n\n
Example 2:
\n\n\nInput: basket1 = [2,3,4,1], basket2 = [3,2,5,1]\nOutput: -1\nExplanation: It can be shown that it is impossible to make both the baskets equal.\n\n\n
\n
Constraints:
\n\nbasket1.length == basket2.length
1 <= basket1.length <= 105
1 <= basket1[i],basket2[i] <= 109
You are given a 0-indexed integer array nums
.
The concatenation of two numbers is the number formed by concatenating their numerals.
\n\n15
, 49
is 1549
.The concatenation value of nums
is initially equal to 0
. Perform this operation until nums
becomes empty:
nums
, pick the first element and last element in nums
respectively and add the value of their concatenation to the concatenation value of nums
, then delete the first and last element from nums
.nums
, then delete it.Return the concatenation value of the nums
.
\n
Example 1:
\n\n\nInput: nums = [7,52,2,4]\nOutput: 596\nExplanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0.\n - In the first operation:\nWe pick the first element, 7, and the last element, 4.\nTheir concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74.\nThen we delete them from nums, so nums becomes equal to [52,2].\n - In the second operation:\nWe pick the first element, 52, and the last element, 2.\nTheir concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596.\nThen we delete them from the nums, so nums becomes empty.\nSince the concatenation value is 596 so the answer is 596.\n\n\n
Example 2:
\n\n\nInput: nums = [5,14,13,8,12]\nOutput: 673\nExplanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0.\n - In the first operation:\nWe pick the first element, 5, and the last element, 12.\nTheir concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512.\nThen we delete them from the nums, so nums becomes equal to [14,13,8].\n - In the second operation:\nWe pick the first element, 14, and the last element, 8.\nTheir concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660.\nThen we delete them from the nums, so nums becomes equal to [13].\n - In the third operation:\nnums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673.\nThen we delete it from nums, so nums become empty.\nSince the concatenation value is 673 so the answer is 673.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 104
\n\n", - "likes": 369, + "content": "
You are given a 0-indexed integer array nums
.
The concatenation of two numbers is the number formed by concatenating their numerals.
\n\n15
, 49
is 1549
.The concatenation value of nums
is initially equal to 0
. Perform this operation until nums
becomes empty:
nums
has a size greater than one, add the value of the concatenation of the first and the last element to the concatenation value of nums
, and remove those two elements from nums
. For example, if the nums
was [1, 2, 4, 5, 6]
, add 16 to the concatenation value
.nums
, add its value to the concatenation value of nums
, then remove it.Return the concatenation value of nums
.
\n
Example 1:
\n\n\nInput: nums = [7,52,2,4]\nOutput: 596\nExplanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0.\n - In the first operation:\nWe pick the first element, 7, and the last element, 4.\nTheir concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74.\nThen we delete them from nums, so nums becomes equal to [52,2].\n - In the second operation:\nWe pick the first element, 52, and the last element, 2.\nTheir concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596.\nThen we delete them from the nums, so nums becomes empty.\nSince the concatenation value is 596 so the answer is 596.\n\n\n
Example 2:
\n\n\nInput: nums = [5,14,13,8,12]\nOutput: 673\nExplanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0.\n - In the first operation:\nWe pick the first element, 5, and the last element, 12.\nTheir concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512.\nThen we delete them from the nums, so nums becomes equal to [14,13,8].\n - In the second operation:\nWe pick the first element, 14, and the last element, 8.\nTheir concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660.\nThen we delete them from the nums, so nums becomes equal to [13].\n - In the third operation:\nnums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673.\nThen we delete it from nums, so nums become empty.\nSince the concatenation value is 673 so the answer is 673.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 104
\n\n", + "likes": 376, "dislikes": 17, - "stats": "{\"totalAccepted\": \"56.1K\", \"totalSubmission\": \"79.3K\", \"totalAcceptedRaw\": 56075, \"totalSubmissionRaw\": 79335, \"acRate\": \"70.7%\"}", + "stats": "{\"totalAccepted\": \"60.4K\", \"totalSubmission\": \"85K\", \"totalAcceptedRaw\": 60393, \"totalSubmissionRaw\": 85039, \"acRate\": \"71.0%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -97104,9 +97329,9 @@ "questionFrontendId": "2563", "title": "Count the Number of Fair Pairs", "content": "
Given a 0-indexed integer array nums
of size n
and two integers lower
and upper
, return the number of fair pairs.
A pair (i, j)
is fair if:
0 <= i < j < n
, andlower <= nums[i] + nums[j] <= upper
\n
Example 1:
\n\n\nInput: nums = [0,1,7,4,4,5], lower = 3, upper = 6\nOutput: 6\nExplanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).\n\n\n
Example 2:
\n\n\nInput: nums = [1,7,9,2,5], lower = 11, upper = 11\nOutput: 1\nExplanation: There is a single fair pair: (2,3).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
nums.length == n
-109 <= nums[i] <= 109
-109 <= lower <= upper <= 109
You are given a binary string s
, and a 2D integer array queries
where queries[i] = [firsti, secondi]
.
For the ith
query, find the shortest substring of s
whose decimal value, val
, yields secondi
when bitwise XORed with firsti
. In other words, val ^ firsti == secondi
.
The answer to the ith
query is the endpoints (0-indexed) of the substring [lefti, righti]
or [-1, -1]
if no such substring exists. If there are multiple answers, choose the one with the minimum lefti
.
Return an array ans
where ans[i] = [lefti, righti]
is the answer to the ith
query.
A substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "101101", queries = [[0,5],[1,2]]\nOutput: [[0,2],[2,3]]\nExplanation: For the first query the substring in range\n\n[0,2]
is "101" which has a decimal value of5
, and5 ^ 0 = 5
, hence the answer to the first query is[0,2]
. In the second query, the substring in range[2,3]
is "11", and has a decimal value of 3, and 3^ 1 = 2
. So,[2,3]
is returned for the second query. \n\n
Example 2:
\n\n\nInput: s = "0101", queries = [[12,8]]\nOutput: [[-1,-1]]\nExplanation: In this example there is no substring that answers the query, hence [-1,-1] is returned
.\n
\n\nExample 3:
\n\n\nInput: s = "1", queries = [[4,5]]\nOutput: [[0,0]]\nExplanation: For this example, the substring in range\n\n[0,0]
has a decimal value of1
, and1 ^ 4 = 5
. So, the answer is[0,0]
.\n
\n
Constraints:
\n\n1 <= s.length <= 104
s[i]
is either '0'
or '1'
.1 <= queries.length <= 105
0 <= firsti, secondi <= 109
You are given two strings s
and t
.
You are allowed to remove any number of characters from the string t
.
The score of the string is 0
if no characters are removed from the string t
, otherwise:
left
be the minimum index among all removed characters.right
be the maximum index among all removed characters.Then the score of the string is right - left + 1
.
Return the minimum possible score to make t
a subsequence of s
.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace"
is a subsequence of "abcde"
while "aec"
is not).
\n
Example 1:
\n\n\nInput: s = "abacaba", t = "bzaa"\nOutput: 1\nExplanation: In this example, we remove the character "z" at index 1 (0-indexed).\nThe string t becomes "baa" which is a subsequence of the string "abacaba" and the score is 1 - 1 + 1 = 1.\nIt can be proven that 1 is the minimum score that we can achieve.\n\n\n
Example 2:
\n\n\nInput: s = "cde", t = "xyz"\nOutput: 3\nExplanation: In this example, we remove characters "x", "y" and "z" at indices 0, 1, and 2 (0-indexed).\nThe string t becomes "" which is a subsequence of the string "cde" and the score is 2 - 0 + 1 = 3.\nIt can be proven that 3 is the minimum score that we can achieve.\n\n\n
\n
Constraints:
\n\n1 <= s.length, t.length <= 105
s
and t
consist of only lowercase English letters.You are given an integer num
. You know that Bob will sneakily remap one of the 10
possible digits (0
to 9
) to another digit.
Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num
.
Notes:
\n\nd1
in num
with d2
.num
does not change.\n
Example 1:
\n\n\nInput: num = 11891\nOutput: 99009\nExplanation: \nTo achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.\nTo achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.\nThe difference between these two numbers is 99009.\n\n\n
Example 2:
\n\n\nInput: num = 90\nOutput: 99\nExplanation:\nThe maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0).\nThus, we return 99.\n\n
\n
Constraints:
\n\n1 <= num <= 108
You are given an integer array nums
.
nums
is the minimum absolute difference between any two integers.nums
is the maximum absolute difference between any two integers.nums
is the sum of the high and low scores.Return the minimum score after changing two elements of nums
.
\n
Example 1:
\n\nInput: nums = [1,4,7,8,5]
\n\nOutput: 3
\n\nExplanation:
\n\nnums[0]
and nums[1]
to be 6 so that nums
becomes [6,6,7,8,5].Example 2:
\n\nInput: nums = [1,4,3]
\n\nOutput: 0
\n\nExplanation:
\n\nnums[1]
and nums[2]
to 1 so that nums
becomes [1,1,1].\n
Constraints:
\n\n3 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed integer array nums
.
We say that an integer x is expressible from nums
if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length
for which nums[index1] | nums[index2] | ... | nums[indexk] = x
. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums
.
Return the minimum positive non-zero integer that is not expressible from nums
.
\n
Example 1:
\n\n\nInput: nums = [2,1]\nOutput: 4\nExplanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.\n\n\n
Example 2:
\n\n\nInput: nums = [5,3,2]\nOutput: 1\nExplanation: We can show that 1 is the smallest number that is not expressible.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given two 0-indexed arrays nums1
and nums2
and a 2D array queries
of queries. There are three types of queries:
queries[i] = [1, l, r]
. Flip the values from 0
to 1
and from 1
to 0
in nums1
from index l
to index r
. Both l
and r
are 0-indexed.queries[i] = [2, p, 0]
. For every index 0 <= i < n
, set nums2[i] = nums2[i] + nums1[i] * p
.queries[i] = [3, 0, 0]
. Find the sum of the elements in nums2
.Return an array containing all the answers to the third type queries.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]]\nOutput: [3]\nExplanation: After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]]\nOutput: [5]\nExplanation: After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length,nums2.length <= 105
nums1.length = nums2.length
1 <= queries.length <= 105
queries[i].length = 3
0 <= l <= r <= nums1.length - 1
0 <= p <= 106
0 <= nums1[i] <= 1
0 <= nums2[i] <= 109
You are given two 2D integer arrays nums1
and nums2.
nums1[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.nums2[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.Each array contains unique ids and is sorted in ascending order by id.
\n\nMerge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
\n\n0
.Return the resulting array. The returned array must be sorted in ascending order by id.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]\nOutput: [[1,6],[2,3],[3,2],[4,6]]\nExplanation: The resulting array contains the following:\n- id = 1, the value of this id is 2 + 4 = 6.\n- id = 2, the value of this id is 3.\n- id = 3, the value of this id is 2.\n- id = 4, the value of this id is 5 + 1 = 6.\n\n\n
Example 2:
\n\n\nInput: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]\nOutput: [[1,3],[2,4],[3,6],[4,3],[5,5]]\nExplanation: There are no common ids, so we just include each id with its value in the resulting list.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 200
nums1[i].length == nums2[j].length == 2
1 <= idi, vali <= 1000
You are given two 2D integer arrays nums1
and nums2.
nums1[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.nums2[i] = [idi, vali]
indicate that the number with the id idi
has a value equal to vali
.Each array contains unique ids and is sorted in ascending order by id.
\n\nMerge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
\n\n0
.Return the resulting array. The returned array must be sorted in ascending order by id.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]\nOutput: [[1,6],[2,3],[3,2],[4,6]]\nExplanation: The resulting array contains the following:\n- id = 1, the value of this id is 2 + 4 = 6.\n- id = 2, the value of this id is 3.\n- id = 3, the value of this id is 2.\n- id = 4, the value of this id is 5 + 1 = 6.\n\n\n
Example 2:
\n\n\nInput: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]\nOutput: [[1,3],[2,4],[3,6],[4,3],[5,5]]\nExplanation: There are no common ids, so we just include each id with its value in the resulting list.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 200
nums1[i].length == nums2[j].length == 2
1 <= idi, vali <= 1000
You are given a positive integer n
, you can do the following operation any number of times:
2
from n
.Return the minimum number of operations to make n
equal to 0
.
A number x
is power of 2
if x == 2i
where i >= 0
.
\n
Example 1:
\n\n\nInput: n = 39\nOutput: 3\nExplanation: We can do the following operations:\n- Add 20 = 1 to n, so now n = 40.\n- Subtract 23 = 8 from n, so now n = 32.\n- Subtract 25 = 32 from n, so now n = 0.\nIt can be shown that 3 is the minimum number of operations we need to make n equal to 0.\n\n\n
Example 2:
\n\n\nInput: n = 54\nOutput: 3\nExplanation: We can do the following operations:\n- Add 21 = 2 to n, so now n = 56.\n- Add 23 = 8 to n, so now n = 64.\n- Subtract 26 = 64 from n, so now n = 0.\nSo the minimum number of operations is 3.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given a positive integer 0-indexed array nums
.
A subset of the array nums
is square-free if the product of its elements is a square-free integer.
A square-free integer is an integer that is divisible by no square number other than 1
.
Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 109 + 7
.
A non-empty subset of nums
is an array that can be obtained by deleting some (possibly none but not all) elements from nums
. Two subsets are different if and only if the chosen indices to delete are different.
\n
Example 1:
\n\n\nInput: nums = [3,4,4,5]\nOutput: 3\nExplanation: There are 3 square-free subsets in this example:\n- The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer.\n- The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer.\n- The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer.\nIt can be proven that there are no more than 3 square-free subsets in the given array.\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: 1\nExplanation: There is 1 square-free subset in this example:\n- The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer.\nIt can be proven that there is no more than 1 square-free subset in the given array.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 30
We define the lcp
matrix of any 0-indexed string word
of n
lowercase English letters as an n x n
grid such that:
lcp[i][j]
is equal to the length of the longest common prefix between the substrings word[i,n-1]
and word[j,n-1]
.Given an n x n
matrix lcp
, return the alphabetically smallest string word
that corresponds to lcp
. If there is no such string, return an empty string.
A string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, string a
has a letter that appears earlier in the alphabet than the corresponding letter in b
. For example, "aabd"
is lexicographically smaller than "aaca"
because the first position they differ is at the third letter, and 'b'
comes before 'c'
.
\n
Example 1:
\n\n\nInput: lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]]\nOutput: "abab"\nExplanation: lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab".\n\n\n
Example 2:
\n\n\nInput: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]]\nOutput: "aaaa"\nExplanation: lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa". \n\n\n
Example 3:
\n\n\nInput: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]]\nOutput: ""\nExplanation: lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists.\n\n\n
\n
Constraints:
\n\n1 <= n ==
lcp.length ==
lcp[i].length
<= 1000
0 <= lcp[i][j] <= n
Given a 0-indexed integer array nums
, find a 0-indexed integer array answer
where:
answer.length == nums.length
.answer[i] = |leftSum[i] - rightSum[i]|
.Where:
\n\nleftSum[i]
is the sum of elements to the left of the index i
in the array nums
. If there is no such element, leftSum[i] = 0
.rightSum[i]
is the sum of elements to the right of the index i
in the array nums
. If there is no such element, rightSum[i] = 0
.Return the array answer
.
\n
Example 1:
\n\n\nInput: nums = [10,4,8,3]\nOutput: [15,1,11,22]\nExplanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].\nThe array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].\n\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: [0]\nExplanation: The array leftSum is [0] and the array rightSum is [0].\nThe array answer is [|0 - 0|] = [0].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 105
You are given a 0-indexed integer array nums
of size n
.
Define two arrays leftSum
and rightSum
where:
leftSum[i]
is the sum of elements to the left of the index i
in the array nums
. If there is no such element, leftSum[i] = 0
.rightSum[i]
is the sum of elements to the right of the index i
in the array nums
. If there is no such element, rightSum[i] = 0
.Return an integer array answer
of size n
where answer[i] = |leftSum[i] - rightSum[i]|
.
\n
Example 1:
\n\n\nInput: nums = [10,4,8,3]\nOutput: [15,1,11,22]\nExplanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].\nThe array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].\n\n\n
Example 2:
\n\n\nInput: nums = [1]\nOutput: [0]\nExplanation: The array leftSum is [0] and the array rightSum is [0].\nThe array answer is [|0 - 0|] = [0].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 105
You are given a 0-indexed string word
of length n
consisting of digits, and a positive integer m
.
The divisibility array div
of word
is an integer array of length n
such that:
div[i] = 1
if the numeric value of word[0,...,i]
is divisible by m
, ordiv[i] = 0
otherwise.Return the divisibility array of word
.
\n
Example 1:
\n\n\nInput: word = "998244353", m = 3\nOutput: [1,1,0,0,0,1,1,0,0]\nExplanation: There are only 4 prefixes that are divisible by 3: "9", "99", "998244", and "9982443".\n\n\n
Example 2:
\n\n\nInput: word = "1010", m = 10\nOutput: [0,1,0,1]\nExplanation: There are only 2 prefixes that are divisible by 10: "10", and "1010".\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
word.length == n
word
consists of digits from 0
to 9
1 <= m <= 109
You are given a 0-indexed integer array nums
.
Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:
\n\ni
and j
such that 2 * nums[i] <= nums[j]
, then mark i
and j
.Return the maximum possible number of marked indices in nums
using the above operation any number of times.
\n
Example 1:
\n\n\nInput: nums = [3,5,2,4]\nOutput: 2\nExplanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1.\nIt can be shown that there's no other valid operation so the answer is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [9,2,5,4]\nOutput: 4\nExplanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0.\nIn the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2.\nSince there is no other operation, the answer is 4.\n\n\n
Example 3:
\n\n\nInput: nums = [7,6,8]\nOutput: 0\nExplanation: There is no valid operation to do, so the answer is 0.\n\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
\n\n", - "likes": 575, - "dislikes": 28, - "stats": "{\"totalAccepted\": \"22.2K\", \"totalSubmission\": \"56.5K\", \"totalAcceptedRaw\": 22213, \"totalSubmissionRaw\": 56509, \"acRate\": \"39.3%\"}", + "likes": 582, + "dislikes": 29, + "stats": "{\"totalAccepted\": \"23.7K\", \"totalSubmission\": \"59.2K\", \"totalAcceptedRaw\": 23713, \"totalSubmissionRaw\": 59213, \"acRate\": \"40.0%\"}", "similarQuestions": "[{\"title\": \"Minimum Array Length After Pair Removals\", \"titleSlug\": \"minimum-array-length-after-pair-removals\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -97648,9 +97879,9 @@ "questionFrontendId": "2577", "title": "Minimum Time to Visit a Cell In a Grid", "content": "
You are given a m x n
matrix grid
consisting of non-negative integers where grid[row][col]
represents the minimum time required to be able to visit the cell (row, col)
, which means you can visit the cell (row, col)
only when the time you visit it is greater than or equal to grid[row][col]
.
You are standing in the top-left cell of the matrix in the 0th
second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1
.
\n
Example 1:
\n\n\nInput: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]\nOutput: 7\nExplanation: One of the paths that we can take is the following:\n- at t = 0, we are on the cell (0,0).\n- at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1.\n- at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2.\n- at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3.\n- at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4.\n- at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5.\n- at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6.\n- at t = 7, we move to the cell (2,3). It is possible because grid[2][3] <= 7.\nThe final time is 7. It can be shown that it is the minimum time possible.\n\n\n
Example 2:
\n\n\nInput: grid = [[0,2,4],[3,2,1],[1,0,4]]\nOutput: -1\nExplanation: There is no path from the top left to the bottom-right cell.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
0 <= grid[i][j] <= 105
grid[0][0] == 0
\n\n", - "likes": 1043, - "dislikes": 41, - "stats": "{\"totalAccepted\": \"80.3K\", \"totalSubmission\": \"140.4K\", \"totalAcceptedRaw\": 80348, \"totalSubmissionRaw\": 140403, \"acRate\": \"57.2%\"}", + "likes": 1076, + "dislikes": 43, + "stats": "{\"totalAccepted\": \"83.6K\", \"totalSubmission\": \"147.1K\", \"totalAcceptedRaw\": 83569, \"totalSubmissionRaw\": 147097, \"acRate\": \"56.8%\"}", "similarQuestions": "[{\"title\": \"Find Minimum Time to Reach Last Room I\", \"titleSlug\": \"find-minimum-time-to-reach-last-room-i\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Find Minimum Time to Reach Last Room II\", \"titleSlug\": \"find-minimum-time-to-reach-last-room-ii\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -97697,9 +97928,9 @@ "questionFrontendId": "2578", "title": "Split With Minimum Sum", "content": "
Given a positive integer num
, split it into two non-negative integers num1
and num2
such that:
num1
and num2
is a permutation of num
.\n\n\tnum1
and num2
is equal to the number of occurrences of that digit in num
.num1
and num2
can contain leading zeros.Return the minimum possible sum of num1
and num2
.
Notes:
\n\nnum
does not contain any leading zeros.num1
and num2
may differ from the order of occurrence of num
.\n
Example 1:
\n\n\nInput: num = 4325\nOutput: 59\nExplanation: We can split 4325 so that\n\nnum1
is 24 andnum2
is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.\n
Example 2:
\n\n\nInput: num = 687\nOutput: 75\nExplanation: We can split 687 so that\n\nnum1
is 68 andnum2
is 7, which would give an optimal sum of 75.\n
\n
Constraints:
\n\n10 <= num <= 109
There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n
, indicating that you must do the following routine for n
minutes:
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
\nReturn the number of colored cells at the end of n
minutes.
\n
Example 1:
\n\n\nInput: n = 1\nOutput: 1\nExplanation: After 1 minute, there is only 1 blue cell, so we return 1.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: 5\nExplanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. \n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given a 2D integer array ranges
where ranges[i] = [starti, endi]
denotes that all integers between starti
and endi
(both inclusive) are contained in the ith
range.
You are to split ranges
into two (possibly empty) groups such that:
Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges.
\n\n[1, 3]
and [2, 5]
are overlapping because 2
and 3
occur in both ranges.Return the total number of ways to split ranges
into two groups. Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: ranges = [[6,10],[5,15]]\nOutput: 2\nExplanation: \nThe two ranges are overlapping, so they must be in the same group.\nThus, there are two possible ways:\n- Put both the ranges together in group 1.\n- Put both the ranges together in group 2.\n\n\n
Example 2:
\n\n\nInput: ranges = [[1,3],[10,20],[2,5],[4,8]]\nOutput: 4\nExplanation: \nRanges [1,3], and [2,5] are overlapping. So, they must be in the same group.\nAgain, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. \nThus, there are four possible ways to group them:\n- All the ranges in group 1.\n- All the ranges in group 2.\n- Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2.\n- Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.\n\n\n
\n
Constraints:
\n\n1 <= ranges.length <= 105
ranges[i].length == 2
0 <= starti <= endi <= 109
Alice has an undirected tree with n
nodes labeled from 0
to n - 1
. The tree is represented as a 2D integer array edges
of length n - 1
where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following:
\n\nu
and v
such that there exists an edge [u, v]
in the tree.u
is the parent of v
in the tree.Bob's guesses are represented by a 2D integer array guesses
where guesses[j] = [uj, vj]
indicates Bob guessed uj
to be the parent of vj
.
Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k
of his guesses are true
.
Given the 2D integer arrays edges
, guesses
and the integer k
, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0
.
\n
Example 1:
\n\n\nInput: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3\nOutput: 3\nExplanation: \nRoot = 0, correct guesses = [1,3], [0,1], [2,4]\nRoot = 1, correct guesses = [1,3], [1,0], [2,4]\nRoot = 2, correct guesses = [1,3], [1,0], [2,4]\nRoot = 3, correct guesses = [1,0], [2,4]\nRoot = 4, correct guesses = [1,3], [1,0]\nConsidering 0, 1, or 2 as root node leads to 3 correct guesses.\n\n\n\n
Example 2:
\n\n\nInput: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1\nOutput: 5\nExplanation: \nRoot = 0, correct guesses = [3,4]\nRoot = 1, correct guesses = [1,0], [3,4]\nRoot = 2, correct guesses = [1,0], [2,1], [3,4]\nRoot = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]\nRoot = 4, correct guesses = [1,0], [2,1], [3,2]\nConsidering any node as root will give at least 1 correct guess. \n\n\n\n
\n
Constraints:
\n\nedges.length == n - 1
2 <= n <= 105
1 <= guesses.length <= 105
0 <= ai, bi, uj, vj <= n - 1
ai != bi
uj != vj
edges
represents a valid tree.guesses[j]
is an edge of the tree.guesses
is unique.0 <= k <= guesses.length
There are n
people standing in a line labeled from 1
to n
. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.
nth
person they pass it to the n - 1th
person, then to the n - 2th
person and so on.Given the two positive integers n
and time
, return the index of the person holding the pillow after time
seconds.
\n
Example 1:
\n\n\nInput: n = 4, time = 5\nOutput: 2\nExplanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.\nAfter five seconds, the 2nd person is holding the pillow.\n\n\n
Example 2:
\n\n\nInput: n = 3, time = 2\nOutput: 3\nExplanation: People pass the pillow in the following way: 1 -> 2 -> 3.\nAfter two seconds, the 3rd person is holding the pillow.\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
1 <= time <= 1000
\n
Note: This question is the same as 3178: Find the Child Who Has the Ball After K Seconds.
\n", - "likes": 1055, - "dislikes": 53, - "stats": "{\"totalAccepted\": \"201.1K\", \"totalSubmission\": \"354.8K\", \"totalAcceptedRaw\": 201057, \"totalSubmissionRaw\": 354777, \"acRate\": \"56.7%\"}", + "likes": 1065, + "dislikes": 54, + "stats": "{\"totalAccepted\": \"205K\", \"totalSubmission\": \"362.6K\", \"totalAcceptedRaw\": 205043, \"totalSubmissionRaw\": 362559, \"acRate\": \"56.6%\"}", "similarQuestions": "[{\"title\": \"Find the Student that Will Replace the Chalk\", \"titleSlug\": \"find-the-student-that-will-replace-the-chalk\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -97880,9 +98114,9 @@ "questionFrontendId": "2583", "title": "Kth Largest Sum in a Binary Tree", "content": "You are given the root
of a binary tree and a positive integer k
.
The level sum in the tree is the sum of the values of the nodes that are on the same level.
\n\nReturn the kth
largest level sum in the tree (not necessarily distinct). If there are fewer than k
levels in the tree, return -1
.
Note that two nodes are on the same level if they have the same distance from the root.
\n\n\n
Example 1:
\n\nInput: root = [5,8,9,2,1,3,7,4,6], k = 2\nOutput: 13\nExplanation: The level sums are the following:\n- Level 1: 5.\n- Level 2: 8 + 9 = 17.\n- Level 3: 2 + 1 + 3 + 7 = 13.\n- Level 4: 4 + 6 = 10.\nThe 2nd largest level sum is 13.\n\n\n
Example 2:
\n\nInput: root = [1,2,null,3], k = 1\nOutput: 3\nExplanation: The largest level sum is 3.\n\n\n
\n
Constraints:
\n\nn
.2 <= n <= 105
1 <= Node.val <= 106
1 <= k <= n
You are given a 0-indexed integer array nums
of length n
.
A split at an index i
where 0 <= i <= n - 2
is called valid if the product of the first i + 1
elements and the product of the remaining elements are coprime.
nums = [2, 3, 3]
, then a split at the index i = 0
is valid because 2
and 9
are coprime, while a split at the index i = 1
is not valid because 6
and 3
are not coprime. A split at the index i = 2
is not valid because i == n - 1
.Return the smallest index i
at which the array can be split validly or -1
if there is no such split.
Two values val1
and val2
are coprime if gcd(val1, val2) == 1
where gcd(val1, val2)
is the greatest common divisor of val1
and val2
.
\n
Example 1:
\n\nInput: nums = [4,7,8,15,3,5]\nOutput: 2\nExplanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.\nThe only valid split is at index 2.\n\n\n
Example 2:
\n\nInput: nums = [4,7,15,8,3,5]\nOutput: -1\nExplanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.\nThere is no valid split.\n\n\n
\n
Constraints:
\n\nn == nums.length
1 <= n <= 104
1 <= nums[i] <= 106
There is a test that has n
types of questions. You are given an integer target
and a 0-indexed 2D integer array types
where types[i] = [counti, marksi]
indicates that there are counti
questions of the ith
type, and each one of them is worth marksi
points.
Return the number of ways you can earn exactly target
points in the exam. Since the answer may be too large, return it modulo 109 + 7
.
Note that questions of the same type are indistinguishable.
\n\n3
questions of the same type, then solving the 1st
and 2nd
questions is the same as solving the 1st
and 3rd
questions, or the 2nd
and 3rd
questions.\n
Example 1:
\n\n\nInput: target = 6, types = [[6,1],[3,2],[2,3]]\nOutput: 7\nExplanation: You can earn 6 points in one of the seven ways:\n- Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6\n- Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6\n- Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6\n- Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6\n- Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6\n- Solve 3 questions of the 1st type: 2 + 2 + 2 = 6\n- Solve 2 questions of the 2nd type: 3 + 3 = 6\n\n\n
Example 2:
\n\n\nInput: target = 5, types = [[50,1],[50,2],[50,5]]\nOutput: 4\nExplanation: You can earn 5 points in one of the four ways:\n- Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5\n- Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5\n- Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5\n- Solve 1 question of the 2nd type: 5\n\n\n
Example 3:
\n\n\nInput: target = 18, types = [[6,1],[3,2],[2,3]]\nOutput: 1\nExplanation: You can only earn 18 points by answering all questions.\n\n\n
\n
Constraints:
\n\n1 <= target <= 1000
n == types.length
1 <= n <= 50
types[i].length == 2
1 <= counti, marksi <= 50
You are given a 0-indexed array of string words
and two integers left
and right
.
A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Return the number of vowel strings words[i]
where i
belongs to the inclusive range [left, right]
.
\n
Example 1:
\n\n\nInput: words = ["are","amy","u"], left = 0, right = 2\nOutput: 2\nExplanation: \n- "are" is a vowel string because it starts with 'a' and ends with 'e'.\n- "amy" is not a vowel string because it does not end with a vowel.\n- "u" is a vowel string because it starts with 'u' and ends with 'u'.\nThe number of vowel strings in the mentioned range is 2.\n\n\n
Example 2:
\n\n\nInput: words = ["hey","aeo","mu","ooo","artro"], left = 1, right = 4\nOutput: 3\nExplanation: \n- "aeo" is a vowel string because it starts with 'a' and ends with 'o'.\n- "mu" is not a vowel string because it does not start with a vowel.\n- "ooo" is a vowel string because it starts with 'o' and ends with 'o'.\n- "artro" is a vowel string because it starts with 'a' and ends with 'o'.\nThe number of vowel strings in the mentioned range is 3.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 10
words[i]
consists of only lowercase English letters.0 <= left <= right < words.length
You are given a 0-indexed integer array nums
. You can rearrange the elements of nums
to any order (including the given order).
Let prefix
be the array containing the prefix sums of nums
after rearranging it. In other words, prefix[i]
is the sum of the elements from 0
to i
in nums
after rearranging it. The score of nums
is the number of positive integers in the array prefix
.
Return the maximum score you can achieve.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,-1,0,1,-3,3,-3]\nOutput: 6\nExplanation: We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].\nprefix = [2,5,6,5,2,2,-1], so the score is 6.\nIt can be shown that 6 is the maximum score we can obtain.\n\n\n
Example 2:
\n\n\nInput: nums = [-2,-3,0]\nOutput: 0\nExplanation: Any rearrangement of the array will result in a score of 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-106 <= nums[i] <= 106
You are given a 0-indexed integer array nums
. In one operation, you can:
i
and j
such that 0 <= i, j < nums.length
.k
such that the kth
bit (0-indexed) in the binary representation of nums[i]
and nums[j]
is 1
.2k
from nums[i]
and nums[j]
.A subarray is beautiful if it is possible to make all of its elements equal to 0
after applying the above operation any number of times.
Return the number of beautiful subarrays in the array nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,3,1,2,4]\nOutput: 2\nExplanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].\n- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:\n - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0].\n - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0].\n- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:\n - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0].\n - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0].\n - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0].\n\n\n
Example 2:
\n\n\nInput: nums = [1,10,4]\nOutput: 0\nExplanation: There are no beautiful subarrays in nums.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 106
You are given a 0-indexed integer array nums
. In one operation, you can:
i
and j
such that 0 <= i, j < nums.length
.k
such that the kth
bit (0-indexed) in the binary representation of nums[i]
and nums[j]
is 1
.2k
from nums[i]
and nums[j]
.A subarray is beautiful if it is possible to make all of its elements equal to 0
after applying the above operation any number of times (including zero).
Return the number of beautiful subarrays in the array nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\nNote: Subarrays where all elements are initially 0 are considered beautiful, as no operation is needed.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,3,1,2,4]\nOutput: 2\nExplanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].\n- We can make all elements in the subarray [3,1,2] equal to 0 in the following way:\n - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0].\n - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0].\n- We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:\n - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0].\n - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0].\n - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0].\n\n\n
Example 2:
\n\n\nInput: nums = [1,10,4]\nOutput: 0\nExplanation: There are no beautiful subarrays in nums.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 106
There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks
where tasks[i] = [starti, endi, durationi]
indicates that the ith
task should run for a total of durationi
seconds (not necessarily continuous) within the inclusive time range [starti, endi]
.
You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.
\n\nReturn the minimum time during which the computer should be turned on to complete all tasks.
\n\n\n
Example 1:
\n\n\nInput: tasks = [[2,3,1],[4,5,1],[1,5,2]]\nOutput: 2\nExplanation: \n- The first task can be run in the inclusive time range [2, 2].\n- The second task can be run in the inclusive time range [5, 5].\n- The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].\nThe computer will be on for a total of 2 seconds.\n\n\n
Example 2:
\n\n\nInput: tasks = [[1,3,2],[2,5,3],[5,6,2]]\nOutput: 4\nExplanation: \n- The first task can be run in the inclusive time range [2, 3].\n- The second task can be run in the inclusive time ranges [2, 3] and [5, 5].\n- The third task can be run in the two inclusive time range [5, 6].\nThe computer will be on for a total of 4 seconds.\n\n\n
\n
Constraints:
\n\n1 <= tasks.length <= 2000
tasks[i].length == 3
1 <= starti, endi <= 2000
1 <= durationi <= endi - starti + 1
You are given an integer money
denoting the amount of money (in dollars) that you have and another integer children
denoting the number of children that you must distribute the money to.
You have to distribute the money according to the following rules:
\n\n1
dollar.4
dollars.Return the maximum number of children who may receive exactly 8
dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1
.
\n
Example 1:
\n\n\nInput: money = 20, children = 3\nOutput: 1\nExplanation: \nThe maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:\n- 8 dollars to the first child.\n- 9 dollars to the second child. \n- 3 dollars to the third child.\nIt can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.\n\n\n
Example 2:
\n\n\nInput: money = 16, children = 2\nOutput: 2\nExplanation: Each child can be given 8 dollars.\n\n\n
\n
Constraints:
\n\n1 <= money <= 200
2 <= children <= 30
You are given a 0-indexed integer array nums
. You are allowed to permute nums
into a new array perm
of your choosing.
We define the greatness of nums
be the number of indices 0 <= i < nums.length
for which perm[i] > nums[i]
.
Return the maximum possible greatness you can achieve after permuting nums
.
\n
Example 1:
\n\n\nInput: nums = [1,3,5,2,1,3,1]\nOutput: 4\nExplanation: One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].\nAt indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 3\nExplanation: We can prove the optimal perm is [2,3,4,1].\nAt indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
You are given an array nums
consisting of positive integers.
Starting with score = 0
, apply the following algorithm:
score
.Return the score you get after applying the above algorithm.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,3,4,5,2]\nOutput: 7\nExplanation: We mark the elements as follows:\n- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2].\n- 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2].\n- 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2].\nOur score is 1 + 2 + 4 = 7.\n\n\n
Example 2:
\n\n\nInput: nums = [2,3,5,1,3,2]\nOutput: 5\nExplanation: We mark the elements as follows:\n- 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2].\n- 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2].\n- 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2].\nOur score is 1 + 2 + 2 = 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
You are given an integer array ranks
representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r
can repair n cars in r * n2
minutes.
You are also given an integer cars
representing the total number of cars waiting in the garage to be repaired.
Return the minimum time taken to repair all the cars.
\n\nNote: All the mechanics can repair the cars simultaneously.
\n\n\n
Example 1:
\n\n\nInput: ranks = [4,2,3,1], cars = 10\nOutput: 16\nExplanation: \n- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.\n- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.\n- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.\n- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.\nIt can be proved that the cars cannot be repaired in less than 16 minutes.\u200b\u200b\u200b\u200b\u200b\n\n\n
Example 2:
\n\n\nInput: ranks = [5,1,8], cars = 6\nOutput: 16\nExplanation: \n- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.\n- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.\n- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.\nIt can be proved that the cars cannot be repaired in less than 16 minutes.\u200b\u200b\u200b\u200b\u200b\n\n\n
\n
Constraints:
\n\n1 <= ranks.length <= 105
1 <= ranks[i] <= 100
1 <= cars <= 106
You are given a positive integer n
.
Let even
denote the number of even indices in the binary representation of n
with value 1.
Let odd
denote the number of odd indices in the binary representation of n
with value 1.
Note that bits are indexed from right to left in the binary representation of a number.
\n\nReturn the array [even, odd]
.
\n
Example 1:
\n\nInput: n = 50
\n\nOutput: [1,2]
\n\nExplanation:
\n\nThe binary representation of 50 is 110010
.
It contains 1 on indices 1, 4, and 5.
\nExample 2:
\n\nInput: n = 2
\n\nOutput: [0,1]
\n\nExplanation:
\n\nThe binary representation of 2 is 10
.
It contains 1 only on index 1.
\n\n
Constraints:
\n\n1 <= n <= 1000
There is a knight on an n x n
chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once.
You are given an n x n
integer matrix grid
consisting of distinct integers from the range [0, n * n - 1]
where grid[row][col]
indicates that the cell (row, col)
is the grid[row][col]th
cell that the knight visited. The moves are 0-indexed.
Return true
if grid
represents a valid configuration of the knight's movements or false
otherwise.
Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.
\n\n
Example 1:
\n\nInput: grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]\nOutput: true\nExplanation: The above diagram represents the grid. It can be shown that it is a valid configuration.\n\n\n
Example 2:
\n\nInput: grid = [[0,3,6],[5,8,1],[2,7,4]]\nOutput: false\nExplanation: The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move.\n\n\n
\n
Constraints:
\n\nn == grid.length == grid[i].length
3 <= n <= 7
0 <= grid[row][col] < n * n
grid
are unique.You are given an array nums
of positive integers and a positive integer k
.
A subset of nums
is beautiful if it does not contain two integers with an absolute difference equal to k
.
Return the number of non-empty beautiful subsets of the array nums
.
A subset of nums
is an array that can be obtained by deleting some (possibly none) elements from nums
. Two subsets are different if and only if the chosen indices to delete are different.
\n
Example 1:
\n\n\nInput: nums = [2,4,6], k = 2\nOutput: 4\nExplanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].\nIt can be proved that there are only 4 beautiful subsets in the array [2,4,6].\n\n\n
Example 2:
\n\n\nInput: nums = [1], k = 1\nOutput: 1\nExplanation: The beautiful subset of the array nums is [1].\nIt can be proved that there is only 1 beautiful subset in the array [1].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 20
1 <= nums[i], k <= 1000
You are given an array nums
of positive integers and a positive integer k
.
A subset of nums
is beautiful if it does not contain two integers with an absolute difference equal to k
.
Return the number of non-empty beautiful subsets of the array nums
.
A subset of nums
is an array that can be obtained by deleting some (possibly none) elements from nums
. Two subsets are different if and only if the chosen indices to delete are different.
\n
Example 1:
\n\n\nInput: nums = [2,4,6], k = 2\nOutput: 4\nExplanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].\nIt can be proved that there are only 4 beautiful subsets in the array [2,4,6].\n\n\n
Example 2:
\n\n\nInput: nums = [1], k = 1\nOutput: 1\nExplanation: The beautiful subset of the array nums is [1].\nIt can be proved that there is only 1 beautiful subset in the array [1].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 18
1 <= nums[i], k <= 1000
You are given a 0-indexed integer array nums
and an integer value
.
In one operation, you can add or subtract value
from any element of nums
.
nums = [1,2,3]
and value = 2
, you can choose to subtract value
from nums[0]
to make nums = [-1,2,3]
.The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.
\n\n[-1,2,3]
is 0
while the MEX of [1,0,3]
is 2
.Return the maximum MEX of nums
after applying the mentioned operation any number of times.
\n
Example 1:
\n\n\nInput: nums = [1,-10,7,13,6,8], value = 5\nOutput: 4\nExplanation: One can achieve this result by applying the following operations:\n- Add value to nums[1] twice to make nums = [1,0,7,13,6,8]\n- Subtract value from nums[2] once to make nums = [1,0,2,13,6,8]\n- Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8]\nThe MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.\n\n\n
Example 2:
\n\n\nInput: nums = [1,-10,7,13,6,8], value = 7\nOutput: 2\nExplanation: One can achieve this result by applying the following operation:\n- subtract value from nums[2] once to make nums = [1,-10,0,13,6,8]\nThe MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.\n\n\n
\n
Constraints:
\n\n1 <= nums.length, value <= 105
-109 <= nums[i] <= 109
There is a bag that consists of items, each item has a number 1
, 0
, or -1
written on it.
You are given four non-negative integers numOnes
, numZeros
, numNegOnes
, and k
.
The bag initially contains:
\n\nnumOnes
items with 1
s written on them.numZeroes
items with 0
s written on them.numNegOnes
items with -1
s written on them.We want to pick exactly k
items among the available items. Return the maximum possible sum of numbers written on the items.
\n
Example 1:
\n\n\nInput: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 2\nOutput: 2\nExplanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 2 items with 1 written on them and get a sum in a total of 2.\nIt can be proven that 2 is the maximum possible sum.\n\n\n
Example 2:
\n\n\nInput: numOnes = 3, numZeros = 2, numNegOnes = 0, k = 4\nOutput: 3\nExplanation: We have a bag of items with numbers written on them {1, 1, 1, 0, 0}. We take 3 items with 1 written on them, and 1 item with 0 written on it, and get a sum in a total of 3.\nIt can be proven that 3 is the maximum possible sum.\n\n\n
\n
Constraints:
\n\n0 <= numOnes, numZeros, numNegOnes <= 50
0 <= k <= numOnes + numZeros + numNegOnes
You are given a 0-indexed integer array nums
of length n
.
You can perform the following operation as many times as you want:
\n\ni
that you haven’t picked before, and pick a prime p
strictly less than nums[i]
, then subtract p
from nums[i]
.Return true if you can make nums
a strictly increasing array using the above operation and false otherwise.
A strictly increasing array is an array whose each element is strictly greater than its preceding element.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,9,6,10]\nOutput: true\nExplanation: In the first operation: Pick i = 0 and p = 3, and then subtract 3 from nums[0], so that nums becomes [1,9,6,10].\nIn the second operation: i = 1, p = 7, subtract 7 from nums[1], so nums becomes equal to [1,2,6,10].\nAfter the second operation, nums is sorted in strictly increasing order, so the answer is true.\n\n
Example 2:
\n\n\nInput: nums = [6,8,11,12]\nOutput: true\nExplanation: Initially nums is sorted in strictly increasing order, so we don't need to make any operations.\n\n
Example 3:
\n\n\nInput: nums = [5,8,3]\nOutput: false\nExplanation: It can be proven that there is no way to perform operations to make nums sorted in strictly increasing order, so the answer is false.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
nums.length == n
You are given an array nums
consisting of positive integers.
You are also given an integer array queries
of size m
. For the ith
query, you want to make all of the elements of nums
equal to queries[i]
. You can perform the following operation on the array any number of times:
1
.Return an array answer
of size m
where answer[i]
is the minimum number of operations to make all elements of nums
equal to queries[i]
.
Note that after each query the array is reset to its original state.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,1,6,8], queries = [1,5]\nOutput: [14,10]\nExplanation: For the first query we can do the following operations:\n- Decrease nums[0] 2 times, so that nums = [1,1,6,8].\n- Decrease nums[2] 5 times, so that nums = [1,1,1,8].\n- Decrease nums[3] 7 times, so that nums = [1,1,1,1].\nSo the total number of operations for the first query is 2 + 5 + 7 = 14.\nFor the second query we can do the following operations:\n- Increase nums[0] 2 times, so that nums = [5,1,6,8].\n- Increase nums[1] 4 times, so that nums = [5,5,6,8].\n- Decrease nums[2] 1 time, so that nums = [5,5,5,8].\n- Decrease nums[3] 3 times, so that nums = [5,5,5,5].\nSo the total number of operations for the second query is 2 + 4 + 1 + 3 = 10.\n\n\n
Example 2:
\n\n\nInput: nums = [2,9,6,3], queries = [10]\nOutput: [20]\nExplanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.\n\n\n
\n
Constraints:
\n\nn == nums.length
m == queries.length
1 <= n, m <= 105
1 <= nums[i], queries[i] <= 109
There exists an undirected and unrooted tree with n
nodes indexed from 0
to n - 1
. You are given an integer n
and a 2D integer array edges of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree. You are also given an array coins
of size n
where coins[i]
can be either 0
or 1
, where 1
indicates the presence of a coin in the vertex i
.
Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times:
\n\n2
from the current vertex, orFind the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex.
\n\nNote that if you pass an edge several times, you need to count it into the answer several times.
\n\n\n
Example 1:
\n\nInput: coins = [1,0,0,0,0,1], edges = [[0,1],[1,2],[2,3],[3,4],[4,5]]\nOutput: 2\nExplanation: Start at vertex 2, collect the coin at vertex 0, move to vertex 3, collect the coin at vertex 5 then move back to vertex 2.\n\n\n
Example 2:
\n\nInput: coins = [0,0,0,1,1,0,0,1], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[5,6],[5,7]]\nOutput: 2\nExplanation: Start at vertex 0, collect the coins at vertices 4 and 3, move to vertex 2, collect the coin at vertex 7, then move back to vertex 0.\n\n\n
\n
Constraints:
\n\nn == coins.length
1 <= n <= 3 * 104
0 <= coins[i] <= 1
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
ai != bi
edges
represents a valid tree.nums1
and nums2
, return the smallest number that contains at least one digit from each array.\n\n
Example 1:
\n\n\nInput: nums1 = [4,1,3], nums2 = [5,7]\nOutput: 15\nExplanation: The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have.\n\n\n
Example 2:
\n\n\nInput: nums1 = [3,5,2,6], nums2 = [3,1,7]\nOutput: 3\nExplanation: The number 3 contains the digit 3 which exists in both arrays.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 9
1 <= nums1[i], nums2[i] <= 9
You are given a string s
, a string chars
of distinct characters and an integer array vals
of the same length as chars
.
The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0
.
The value of the character is defined in the following way:
\n\nchars
, then its value is its corresponding position (1-indexed) in the alphabet.\n\n\t'a'
is 1
, the value of 'b'
is 2
, and so on. The value of 'z'
is 26
.i
is the index where the character occurs in the string chars
, then its value is vals[i]
.Return the maximum cost among all substrings of the string s
.
\n
Example 1:
\n\n\nInput: s = "adaa", chars = "d", vals = [-1000]\nOutput: 2\nExplanation: The value of the characters "a" and "d" is 1 and -1000 respectively.\nThe substring with the maximum cost is "aa" and its cost is 1 + 1 = 2.\nIt can be proven that 2 is the maximum cost.\n\n\n
Example 2:
\n\n\nInput: s = "abc", chars = "abc", vals = [-1,-1,-1]\nOutput: 0\nExplanation: The value of the characters "a", "b" and "c" is -1, -1, and -1 respectively.\nThe substring with the maximum cost is the empty substring "" and its cost is 0.\nIt can be proven that 0 is the maximum cost.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consist of lowercase English letters.1 <= chars.length <= 26
chars
consist of distinct lowercase English letters.vals.length == chars.length
-1000 <= vals[i] <= 1000
You are given a 0-indexed integer array arr
and an integer k
. The array arr
is circular. In other words, the first element of the array is the next element of the last element, and the last element of the array is the previous element of the first element.
You can do the following operation any number of times:
\n\narr
and increase or decrease it by 1
.Return the minimum number of operations such that the sum of each subarray of length k
is equal.
A subarray is a contiguous part of the array.
\n\n\n
Example 1:
\n\n\nInput: arr = [1,4,1,3], k = 2\nOutput: 1\nExplanation: we can do one operation on index 1 to make its value equal to 3.\nThe array after the operation is [1,3,1,3]\n- Subarray starts at index 0 is [1, 3], and its sum is 4 \n- Subarray starts at index 1 is [3, 1], and its sum is 4 \n- Subarray starts at index 2 is [1, 3], and its sum is 4 \n- Subarray starts at index 3 is [3, 1], and its sum is 4 \n\n\n
Example 2:
\n\n\nInput: arr = [2,5,5,7], k = 3\nOutput: 5\nExplanation: we can do three operations on index 0 to make its value equal to 5 and two operations on index 3 to make its value equal to 5.\nThe array after the operations is [5,5,5,5]\n- Subarray starts at index 0 is [5, 5, 5], and its sum is 15\n- Subarray starts at index 1 is [5, 5, 5], and its sum is 15\n- Subarray starts at index 2 is [5, 5, 5], and its sum is 15\n- Subarray starts at index 3 is [5, 5, 5], and its sum is 15 \n\n\n
\n
Constraints:
\n\n1 <= k <= arr.length <= 105
1 <= arr[i] <= 109
There is a bi-directional graph with n
vertices, where each vertex is labeled from 0
to n - 1
. The edges in the graph are represented by a given 2D integer array edges
, where edges[i] = [ui, vi]
denotes an edge between vertex ui
and vertex vi
. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.
Return the length of the shortest cycle in the graph. If no cycle exists, return -1
.
A cycle is a path that starts and ends at the same node, and each edge in the path is used only once.
\n\n\n
Example 1:
\n\nInput: n = 7, edges = [[0,1],[1,2],[2,0],[3,4],[4,5],[5,6],[6,3]]\nOutput: 3\nExplanation: The cycle with the smallest length is : 0 -> 1 -> 2 -> 0 \n\n\n
Example 2:
\n\nInput: n = 4, edges = [[0,1],[0,2]]\nOutput: -1\nExplanation: There are no cycles in this graph.\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
1 <= edges.length <= 1000
edges[i].length == 2
0 <= ui, vi < n
ui != vi
You are given a binary string s
consisting only of zeroes and ones.
A substring of s
is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring.
Return the length of the longest balanced substring of s
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "01000111"\nOutput: 6\nExplanation: The longest balanced substring is "000111", which has length 6.\n\n\n
Example 2:
\n\n\nInput: s = "00111"\nOutput: 4\nExplanation: The longest balanced substring is "0011", which has length 4. \n\n\n
Example 3:
\n\n\nInput: s = "111"\nOutput: 0\nExplanation: There is no balanced substring except the empty substring, so the answer is 0.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 50
'0' <= s[i] <= '1'
You are given an integer array nums
. You need to create a 2D array from nums
satisfying the following conditions:
nums
.Return the resulting array. If there are multiple answers, return any of them.
\n\nNote that the 2D array can have a different number of elements on each row.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,4,1,2,3,1]\nOutput: [[1,3,4,2],[1,3],[1]]\nExplanation: We can create a 2D array that contains the following rows:\n- 1,3,4,2\n- 1,3\n- 1\nAll elements of nums were used, and each row of the 2D array contains distinct integers, so it is a valid answer.\nIt can be shown that we cannot have less than 3 rows in a valid array.\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: [[4,3,2,1]]\nExplanation: All elements of the array are distinct, so we can keep all of them in the first row of the 2D array.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= nums.length
There are two mice and n
different types of cheese, each type of cheese should be eaten by exactly one mouse.
A point of the cheese with index i
(0-indexed) is:
reward1[i]
if the first mouse eats it.reward2[i]
if the second mouse eats it.You are given a positive integer array reward1
, a positive integer array reward2
, and a non-negative integer k
.
Return the maximum points the mice can achieve if the first mouse eats exactly k
types of cheese.
\n
Example 1:
\n\n\nInput: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2\nOutput: 15\nExplanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese.\nThe total points are 4 + 4 + 3 + 4 = 15.\nIt can be proven that 15 is the maximum total points that the mice can achieve.\n\n\n
Example 2:
\n\n\nInput: reward1 = [1,1], reward2 = [1,1], k = 2\nOutput: 2\nExplanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese.\nThe total points are 1 + 1 = 2.\nIt can be proven that 2 is the maximum total points that the mice can achieve.\n\n\n
\n
Constraints:
\n\n1 <= n == reward1.length == reward2.length <= 105
1 <= reward1[i], reward2[i] <= 1000
0 <= k <= n
You are given an integer n
and an integer p
representing an array arr
of length n
where all elements are set to 0's, except position p
which is set to 1. You are also given an integer array banned
containing restricted positions. Perform the following operation on arr
:
k
if the single 1 is not set to a position in banned
.Return an integer array answer
with n
results where the ith
result is the minimum number of operations needed to bring the single 1 to position i
in arr
, or -1 if it is impossible.
\n
Example 1:
\n\nInput: n = 4, p = 0, banned = [1,2], k = 4
\n\nOutput: [0,-1,-1,1]
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 5, p = 0, banned = [2,4], k = 3
\n\nOutput: [0,-1,-1,-1,-1]
\n\nExplanation:
\n\n[0, 2]
because position 2 is in banned.Example 3:
\n\nInput: n = 4, p = 2, banned = [0,1,3], k = 1
\n\nOutput: [-1,-1,0,-1]
\n\nExplanation:
\n\nPerform operations of size 1 and 1 never changes its position.
\n\n
Constraints:
\n\n1 <= n <= 105
0 <= p <= n - 1
0 <= banned.length <= n - 1
0 <= banned[i] <= n - 1
1 <= k <= n
banned[i] != p
banned
are unique You are given a 0-indexed two-dimensional integer array nums
.
Return the largest prime number that lies on at least one of the diagonals of nums
. In case, no prime is present on any of the diagonals, return 0.
Note that:
\n\n1
and has no positive integer divisors other than 1
and itself.val
is on one of the diagonals of nums
if there exists an integer i
for which nums[i][i] = val
or an i
for which nums[i][nums.length - i - 1] = val
.In the above diagram, one diagonal is [1,5,9] and another diagonal is [3,5,7].
\n\n\n
Example 1:
\n\n\nInput: nums = [[1,2,3],[5,6,7],[9,10,11]]\nOutput: 11\nExplanation: The numbers 1, 3, 6, 9, and 11 are the only numbers present on at least one of the diagonals. Since 11 is the largest prime, we return 11.\n\n\n
Example 2:
\n\n\nInput: nums = [[1,2,3],[5,17,7],[9,11,10]]\nOutput: 17\nExplanation: The numbers 1, 3, 9, 10, and 17 are all present on at least one of the diagonals. 17 is the largest prime, so we return 17.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 300
nums.length == numsi.length
1 <= nums[i][j] <= 4*106
You are given a 0-indexed integer array nums
. There exists an array arr
of length nums.length
, where arr[i]
is the sum of |i - j|
over all j
such that nums[j] == nums[i]
and j != i
. If there is no such j
, set arr[i]
to be 0
.
Return the array arr
.
\n
Example 1:
\n\n\nInput: nums = [1,3,1,1,2]\nOutput: [5,0,3,4,0]\nExplanation: \nWhen i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. \nWhen i = 1, arr[1] = 0 because there is no other index with value 3.\nWhen i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. \nWhen i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. \nWhen i = 4, arr[4] = 0 because there is no other index with value 2. \n\n\n\n
Example 2:
\n\n\nInput: nums = [0,5,3]\nOutput: [0,0,0]\nExplanation: Since each element in nums is distinct, arr[i] = 0 for all i.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
\n
Note: This question is the same as 2121: Intervals Between Identical Elements.
\n", - "likes": 763, - "dislikes": 93, - "stats": "{\"totalAccepted\": \"22.6K\", \"totalSubmission\": \"72.3K\", \"totalAcceptedRaw\": 22569, \"totalSubmissionRaw\": 72335, \"acRate\": \"31.2%\"}", + "likes": 785, + "dislikes": 94, + "stats": "{\"totalAccepted\": \"24.4K\", \"totalSubmission\": \"78.1K\", \"totalAcceptedRaw\": 24414, \"totalSubmissionRaw\": 78138, \"acRate\": \"31.2%\"}", "similarQuestions": "[{\"title\": \"Remove Duplicates from Sorted Array\", \"titleSlug\": \"remove-duplicates-from-sorted-array\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Find All Duplicates in an Array\", \"titleSlug\": \"find-all-duplicates-in-an-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Operations to Make All Array Elements Equal\", \"titleSlug\": \"minimum-operations-to-make-all-array-elements-equal\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -99185,15 +99425,14 @@ "questionFrontendId": "2616", "title": "Minimize the Maximum Difference of Pairs", "content": "You are given a 0-indexed integer array nums
and an integer p
. Find p
pairs of indices of nums
such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p
pairs.
Note that for a pair of elements at the index i
and j
, the difference of this pair is |nums[i] - nums[j]|
, where |x|
represents the absolute value of x
.
Return the minimum maximum difference among all p
pairs. We define the maximum of an empty set to be zero.
\n
Example 1:
\n\n\nInput: nums = [10,1,2,7,1,3], p = 2\nOutput: 1\nExplanation: The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5. \nThe maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.\n\n\n
Example 2:
\n\n\nInput: nums = [4,2,1,2], p = 1\nOutput: 0\nExplanation: Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
0 <= p <= (nums.length)/2
You are given a 0-indexed m x n
integer matrix grid
. Your initial position is at the top-left cell (0, 0)
.
Starting from the cell (i, j)
, you can move to one of the following cells:
(i, k)
with j < k <= grid[i][j] + j
(rightward movement), or(k, j)
with i < k <= grid[i][j] + i
(downward movement).Return the minimum number of cells you need to visit to reach the bottom-right cell (m - 1, n - 1)
. If there is no valid path, return -1
.
\n
Example 1:
\n\nInput: grid = [[3,4,2,1],[4,2,3,1],[2,1,0,0],[2,4,0,0]]\nOutput: 4\nExplanation: The image above shows one of the paths that visits exactly 4 cells.\n\n\n
Example 2:
\n\nInput: grid = [[3,4,2,1],[4,2,1,1],[2,1,1,0],[3,4,1,0]]\nOutput: 3\nExplanation: The image above shows one of the paths that visits exactly 3 cells.\n\n\n
Example 3:
\n\nInput: grid = [[2,1,0],[1,0,0]]\nOutput: -1\nExplanation: It can be proven that no path exists.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
0 <= grid[i][j] < m * n
grid[m - 1][n - 1] == 0
Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
\n\nThere are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined
.
\n
Example 1:
\n\n\nInput: func = () => checkIfInstanceOf(new Date(), Date)\nOutput: true\nExplanation: The object returned by the Date constructor is, by definition, an instance of Date.\n\n\n
Example 2:
\n\n\nInput: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }\nOutput: true\nExplanation:\nclass Animal {};\nclass Dog extends Animal {};\ncheckIfInstanceOf(new Dog(), Animal); // true\n\nDog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.\n\n
Example 3:
\n\n\nInput: func = () => checkIfInstanceOf(Date, Date)\nOutput: false\nExplanation: A date constructor cannot logically be an instance of itself.\n\n\n
Example 4:
\n\n\nInput: func = () => checkIfInstanceOf(5, Number)\nOutput: true\nExplanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".\n\n", - "likes": 270, - "dislikes": 101, - "stats": "{\"totalAccepted\": \"27.1K\", \"totalSubmission\": \"97.4K\", \"totalAcceptedRaw\": 27120, \"totalSubmissionRaw\": 97435, \"acRate\": \"27.8%\"}", + "likes": 277, + "dislikes": 110, + "stats": "{\"totalAccepted\": \"30.7K\", \"totalSubmission\": \"108.6K\", \"totalAcceptedRaw\": 30653, \"totalSubmissionRaw\": 108609, \"acRate\": \"28.2%\"}", "similarQuestions": "[]", "categoryTitle": "JavaScript", "hints": [ @@ -99311,9 +99550,9 @@ "questionFrontendId": "2619", "title": "Array Prototype Last", "content": "
Write code that enhances all arrays such that you can call the array.last()
method on any array and it will return the last element. If there are no elements in the array, it should return -1
.
You may assume the array is the output of JSON.parse
.
\n
Example 1:
\n\n\nInput: nums = [null, {}, 3]\nOutput: 3\nExplanation: Calling nums.last() should return the last element: 3.\n\n\n
Example 2:
\n\n\nInput: nums = []\nOutput: -1\nExplanation: Because there are no elements, return -1.\n\n\n
\n
Constraints:
\n\narr
is a valid JSON array0 <= arr.length <= 1000
Given an integer n
, return a counter
function. This counter
function initially returns n
and then returns 1 more than the previous value every subsequent time it is called (n
, n + 1
, n + 2
, etc).
\n
Example 1:
\n\n\nInput: \nn = 10 \n["call","call","call"]\nOutput: [10,11,12]\nExplanation: \ncounter() = 10 // The first time counter() is called, it returns n.\ncounter() = 11 // Returns 1 more than the previous time.\ncounter() = 12 // Returns 1 more than the previous time.\n\n\n
Example 2:
\n\n\nInput: \nn = -2\n["call","call","call","call","call"]\nOutput: [-2,-1,0,1,2]\nExplanation: counter() initially returns -2. Then increases after each sebsequent call.\n\n\n
\n
Constraints:
\n\n-1000 <= n <= 1000
0 <= calls.length <= 1000
calls[i] === "call"
Given a positive integer millis
, write an asynchronous function that sleeps for millis
milliseconds. It can resolve any value.
\n
Example 1:
\n\n\nInput: millis = 100\nOutput: 100\nExplanation: It should return a promise that resolves after 100ms.\nlet t = Date.now();\nsleep(100).then(() => {\n console.log(Date.now() - t); // 100\n});\n\n\n
Example 2:
\n\n\nInput: millis = 200\nOutput: 200\nExplanation: It should return a promise that resolves after 200ms.\n\n\n
\n
Constraints:
\n\n1 <= millis <= 1000
Given a positive integer millis
, write an asynchronous function that sleeps for millis
milliseconds. It can resolve any value.
Note that minor deviation from millis
in the actual sleep duration is acceptable.
\n
Example 1:
\n\n\nInput: millis = 100\nOutput: 100\nExplanation: It should return a promise that resolves after 100ms.\nlet t = Date.now();\nsleep(100).then(() => {\n console.log(Date.now() - t); // 100\n});\n\n\n
Example 2:
\n\n\nInput: millis = 200\nOutput: 200\nExplanation: It should return a promise that resolves after 200ms.\n\n\n
\n
Constraints:
\n\n1 <= millis <= 1000
Write a class that allows getting and setting key-value pairs, however a time until expiration is associated with each key.
\n\nThe class has three public methods:
\n\nset(key, value, duration)
: accepts an integer key
, an integer value
, and a duration
in milliseconds. Once the duration
has elapsed, the key should be inaccessible. The method should return true
if the same un-expired key already exists and false
otherwise. Both the value and duration should be overwritten if the key already exists.
get(key)
: if an un-expired key exists, it should return the associated value. Otherwise it should return -1
.
count()
: returns the count of un-expired keys.
\n
Example 1:
\n\n\nInput: \nactions = ["TimeLimitedCache", "set", "get", "count", "get"]\nvalues = [[], [1, 42, 100], [1], [], [1]]\ntimeDelays = [0, 0, 50, 50, 150]\nOutput: [null, false, 42, 1, -1]\nExplanation:\nAt t=0, the cache is constructed.\nAt t=0, a key-value pair (1: 42) is added with a time limit of 100ms. The value doesn't exist so false is returned.\nAt t=50, key=1 is requested and the value of 42 is returned.\nAt t=50, count() is called and there is one active key in the cache.\nAt t=100, key=1 expires.\nAt t=150, get(1) is called but -1 is returned because the cache is empty.\n\n\n
Example 2:
\n\n\nInput: \nactions = ["TimeLimitedCache", "set", "set", "get", "get", "get", "count"]\nvalues = [[], [1, 42, 50], [1, 50, 100], [1], [1], [1], []]\ntimeDelays = [0, 0, 40, 50, 120, 200, 250]\nOutput: [null, false, true, 50, 50, -1, 0]\nExplanation:\nAt t=0, the cache is constructed.\nAt t=0, a key-value pair (1: 42) is added with a time limit of 50ms. The value doesn't exist so false is returned.\nAt t=40, a key-value pair (1: 50) is added with a time limit of 100ms. A non-expired value already existed so true is returned and the old value was overwritten.\nAt t=50, get(1) is called which returned 50.\nAt t=120, get(1) is called which returned 50.\nAt t=140, key=1 expires.\nAt t=200, get(1) is called but the cache is empty so -1 is returned.\nAt t=250, count() returns 0 because the cache is empty.\n\n\n
\n
Constraints:
\n\n0 <= key, value <= 109
0 <= duration <= 1000
1 <= actions.length <= 100
actions.length === values.length
actions.length === timeDelays.length
0 <= timeDelays[i] <= 1450
actions[i]
is one of "TimeLimitedCache", "set", "get" and "count"Given a function fn
, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
\n\nYou can assume there are 3 possible input functions: sum
, fib
, and factorial
.
sum
accepts two integers a
and b
and returns a + b
. Assume that if a value has already been cached for the arguments (b, a)
where a != b
, it cannot be used for the arguments (a, b)
. For example, if the arguments are (3, 2)
and (2, 3)
, two separate calls should be made.fib
accepts a single integer n
and returns 1
if n <= 1
or fib(n - 1) + fib(n - 2)
otherwise.factorial
accepts a single integer n
and returns 1
if n <= 1
or factorial(n - 1) * n
otherwise.\n
Example 1:
\n\n\nInput:\nfnName = "sum"\nactions = ["call","call","getCallCount","call","getCallCount"]\nvalues = [[2,2],[2,2],[],[1,2],[]]\nOutput: [4,4,1,3,2]\nExplanation:\nconst sum = (a, b) => a + b;\nconst memoizedSum = memoize(sum);\nmemoizedSum(2, 2); // "call" - returns 4. sum() was called as (2, 2) was not seen before.\nmemoizedSum(2, 2); // "call" - returns 4. However sum() was not called because the same inputs were seen before.\n// "getCallCount" - total call count: 1\nmemoizedSum(1, 2); // "call" - returns 3. sum() was called as (1, 2) was not seen before.\n// "getCallCount" - total call count: 2\n\n\n
Example 2:
\n\n\nInput:\nfnName = "factorial"\nactions = ["call","call","call","getCallCount","call","getCallCount"]\nvalues = [[2],[3],[2],[],[3],[]]\nOutput: [2,6,2,2,6,2]\nExplanation:\nconst factorial = (n) => (n <= 1) ? 1 : (n * factorial(n - 1));\nconst memoFactorial = memoize(factorial);\nmemoFactorial(2); // "call" - returns 2.\nmemoFactorial(3); // "call" - returns 6.\nmemoFactorial(2); // "call" - returns 2. However factorial was not called because 2 was seen before.\n// "getCallCount" - total call count: 2\nmemoFactorial(3); // "call" - returns 6. However factorial was not called because 3 was seen before.\n// "getCallCount" - total call count: 2\n\n\n
Example 3:
\n\n\nInput:\nfnName = "fib"\nactions = ["call","getCallCount"]\nvalues = [[5],[]]\nOutput: [8,1]\nExplanation:\nfib(5) = 8 // "call"\n// "getCallCount" - total call count: 1\n\n\n
\n
Constraints:
\n\n0 <= a, b <= 105
1 <= n <= 10
1 <= actions.length <= 105
actions.length === values.length
actions[i]
is one of "call" and "getCallCount"fnName
is one of "sum", "factorial" and "fib"Write code that enhances all arrays such that you can call the snail(rowsCount, colsCount)
method that transforms the 1D array into a 2D array organised in the pattern known as snail traversal order. Invalid input values should output an empty array. If rowsCount * colsCount !== nums.length
, the input is considered invalid.
Snail traversal order starts at the top left cell with the first value of the current array. It then moves through the entire first column from top to bottom, followed by moving to the next column on the right and traversing it from bottom to top. This pattern continues, alternating the direction of traversal with each column, until the entire current array is covered. For example, when given the input array [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]
with rowsCount = 5
and colsCount = 4
, the desired output matrix is shown below. Note that iterating the matrix following the arrows corresponds to the order of numbers in the original array.
\n\n
\n
Example 1:
\n\n\nInput: \nnums = [19, 10, 3, 7, 9, 8, 5, 2, 1, 17, 16, 14, 12, 18, 6, 13, 11, 20, 4, 15]\nrowsCount = 5\ncolsCount = 4\nOutput: \n[\n [19,17,16,15],\n [10,1,14,4],\n [3,2,12,20],\n [7,5,18,11],\n [9,8,6,13]\n]\n\n\n
Example 2:
\n\n\nInput: \nnums = [1,2,3,4]\nrowsCount = 1\ncolsCount = 4\nOutput: [[1, 2, 3, 4]]\n\n\n
Example 3:
\n\n\nInput: \nnums = [1,3]\nrowsCount = 2\ncolsCount = 2\nOutput: []\nExplanation: 2 multiplied by 2 is 4, and the original array [1,3] has a length of 2; therefore, the input is invalid.\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 250
1 <= nums[i] <= 1000
1 <= rowsCount <= 250
1 <= colsCount <= 250
\n", - "likes": 107, - "dislikes": 45, - "stats": "{\"totalAccepted\": \"12.9K\", \"totalSubmission\": \"19.4K\", \"totalAcceptedRaw\": 12937, \"totalSubmissionRaw\": 19446, \"acRate\": \"66.5%\"}", + "likes": 114, + "dislikes": 46, + "stats": "{\"totalAccepted\": \"14.8K\", \"totalSubmission\": \"22K\", \"totalAcceptedRaw\": 14796, \"totalSubmissionRaw\": 22006, \"acRate\": \"67.2%\"}", "similarQuestions": "[{\"title\": \"Array Prototype Last\", \"titleSlug\": \"array-prototype-last\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Group By\", \"titleSlug\": \"group-by\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Array Upper Bound\", \"titleSlug\": \"array-upper-bound\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "JavaScript", "hints": [ @@ -99494,9 +99733,9 @@ "questionFrontendId": "2625", "title": "Flatten Deeply Nested Array", "content": "
Given a multi-dimensional array arr
and a depth n
, return a flattened version of that array.
A multi-dimensional array is a recursive data structure that contains integers or other multi-dimensional arrays.
\n\nA flattened array is a version of that array with some or all of the sub-arrays removed and replaced with the actual elements in that sub-array. This flattening operation should only be done if the current depth of nesting is less than n
. The depth of the elements in the first array are considered to be 0
.
Please solve it without the built-in Array.flat
method.
\n
Example 1:
\n\n\nInput\narr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]\nn = 0\nOutput\n[1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]\n\nExplanation\nPassing a depth of n=0 will always result in the original array. This is because the smallest possible depth of a subarray (0) is not less than n=0. Thus, no subarray should be flattened.\n\n
Example 2:
\n\n\nInput\narr = [1, 2, 3, [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]\nn = 1\nOutput\n[1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12, 13, 14, 15]\n\nExplanation\nThe subarrays starting with 4, 7, and 13 are all flattened. This is because their depth of 0 is less than 1. However [9, 10, 11] remains unflattened because its depth is 1.\n\n
Example 3:
\n\n\nInput\narr = [[1, 2, 3], [4, 5, 6], [7, 8, [9, 10, 11], 12], [13, 14, 15]]\nn = 2\nOutput\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]\n\nExplanation\nThe maximum depth of any subarray is 1. Thus, all of them are flattened.\n\n
\n
Constraints:
\n\n0 <= count of numbers in arr <= 105
0 <= count of subarrays in arr <= 105
maxDepth <= 1000
-1000 <= each number <= 1000
0 <= n <= 1000
Given an integer array nums
, a reducer function fn
, and an initial value init
, return the final result obtained by executing the fn
function on each element of the array, sequentially, passing in the return value from the calculation on the preceding element.
This result is achieved through the following operations: val = fn(init, nums[0]), val = fn(val, nums[1]), val = fn(val, nums[2]), ...
until every element in the array has been processed. The ultimate value of val
is then returned.
If the length of the array is 0, the function should return init
.
Please solve it without using the built-in Array.reduce
method.
\n
Example 1:
\n\n\nInput: \nnums = [1,2,3,4]\nfn = function sum(accum, curr) { return accum + curr; }\ninit = 0\nOutput: 10\nExplanation:\ninitially, the value is init=0.\n(0) + nums[0] = 1\n(1) + nums[1] = 3\n(3) + nums[2] = 6\n(6) + nums[3] = 10\nThe final answer is 10.\n\n\n
Example 2:
\n\n\nInput: \nnums = [1,2,3,4]\nfn = function sum(accum, curr) { return accum + curr * curr; }\ninit = 100\nOutput: 130\nExplanation:\ninitially, the value is init=100.\n(100) + nums[0] * nums[0] = 101\n(101) + nums[1] * nums[1] = 105\n(105) + nums[2] * nums[2] = 114\n(114) + nums[3] * nums[3] = 130\nThe final answer is 130.\n\n\n
Example 3:
\n\n\nInput: \nnums = []\nfn = function sum(accum, curr) { return 0; }\ninit = 25\nOutput: 25\nExplanation: For empty arrays, the answer is always init.\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 1000
0 <= nums[i] <= 1000
0 <= init <= 1000
Given a function fn
and a time in milliseconds t
, return a debounced version of that function.
A debounced function is a function whose execution is delayed by t
milliseconds and whose execution is cancelled if it is called again within that window of time. The debounced function should also receive the passed parameters.
For example, let's say t = 50ms
, and the function was called at 30ms
, 60ms
, and 100ms
.
The first 2 function calls would be cancelled, and the 3rd function call would be executed at 150ms
.
If instead t = 35ms
, The 1st call would be cancelled, the 2nd would be executed at 95ms
, and the 3rd would be executed at 135ms
.
The above diagram shows how debounce will transform events. Each rectangle represents 100ms and the debounce time is 400ms. Each color represents a different set of inputs.
\n\nPlease solve it without using lodash's _.debounce()
function.
\n
Example 1:
\n\n\nInput: \nt = 50\ncalls = [\n {"t": 50, inputs: [1]},\n {"t": 75, inputs: [2]}\n]\nOutput: [{"t": 125, inputs: [2]}]\nExplanation:\nlet start = Date.now();\nfunction log(...inputs) { \n console.log([Date.now() - start, inputs ])\n}\nconst dlog = debounce(log, 50);\nsetTimeout(() => dlog(1), 50);\nsetTimeout(() => dlog(2), 75);\n\nThe 1st call is cancelled by the 2nd call because the 2nd call occurred before 100ms\nThe 2nd call is delayed by 50ms and executed at 125ms. The inputs were (2).\n\n\n
Example 2:
\n\n\nInput: \nt = 20\ncalls = [\n {"t": 50, inputs: [1]},\n {"t": 100, inputs: [2]}\n]\nOutput: [{"t": 70, inputs: [1]}, {"t": 120, inputs: [2]}]\nExplanation:\nThe 1st call is delayed until 70ms. The inputs were (1).\nThe 2nd call is delayed until 120ms. The inputs were (2).\n\n\n
Example 3:
\n\n\nInput: \nt = 150\ncalls = [\n {"t": 50, inputs: [1, 2]},\n {"t": 300, inputs: [3, 4]},\n {"t": 300, inputs: [5, 6]}\n]\nOutput: [{"t": 200, inputs: [1,2]}, {"t": 450, inputs: [5, 6]}]\nExplanation:\nThe 1st call is delayed by 150ms and ran at 200ms. The inputs were (1, 2).\nThe 2nd call is cancelled by the 3rd call\nThe 3rd call is delayed by 150ms and ran at 450ms. The inputs were (5, 6).\n\n\n
\n
Constraints:
\n\n0 <= t <= 1000
1 <= calls.length <= 10
0 <= calls[i].t <= 1000
0 <= calls[i].inputs.length <= 10
Given an array of functions [f1, f2, f3, ..., fn]
, return a new function fn
that is the function composition of the array of functions.
The function composition of [f(x), g(x), h(x)]
is fn(x) = f(g(h(x)))
.
The function composition of an empty list of functions is the identity function f(x) = x
.
You may assume each function in the array accepts one integer as input and returns one integer as output.
\n\n\n
Example 1:
\n\n\nInput: functions = [x => x + 1, x => x * x, x => 2 * x], x = 4\nOutput: 65\nExplanation:\nEvaluating from right to left ...\nStarting with x = 4.\n2 * (4) = 8\n(8) * (8) = 64\n(64) + 1 = 65\n\n\n
Example 2:
\n\n\nInput: functions = [x => 10 * x, x => 10 * x, x => 10 * x], x = 1\nOutput: 1000\nExplanation:\nEvaluating from right to left ...\n10 * (1) = 10\n10 * (10) = 100\n10 * (100) = 1000\n\n\n
Example 3:
\n\n\nInput: functions = [], x = 42\nOutput: 42\nExplanation:\nThe composition of zero functions is the identity function\n\n
\n
Constraints:
\n\n-1000 <= x <= 1000
0 <= functions.length <= 1000
Given a function fn
, return a memoized version of that function.
A memoized function is a function that will never be called twice with the same inputs. Instead it will return a cached value.
\n\nfn
can be any function and there are no constraints on what type of values it accepts. Inputs are considered identical if they are ===
to each other.
\n
Example 1:
\n\n\nInput: \ngetInputs = () => [[2,2],[2,2],[1,2]]\nfn = function (a, b) { return a + b; }\nOutput: [{"val":4,"calls":1},{"val":4,"calls":1},{"val":3,"calls":2}]\nExplanation:\nconst inputs = getInputs();\nconst memoized = memoize(fn);\nfor (const arr of inputs) {\n memoized(...arr);\n}\n\nFor the inputs of (2, 2): 2 + 2 = 4, and it required a call to fn().\nFor the inputs of (2, 2): 2 + 2 = 4, but those inputs were seen before so no call to fn() was required.\nFor the inputs of (1, 2): 1 + 2 = 3, and it required another call to fn() for a total of 2.\n\n\n
Example 2:
\n\n\nInput: \ngetInputs = () => [[{},{}],[{},{}],[{},{}]] \nfn = function (a, b) { return ({...a, ...b}); }\nOutput: [{"val":{},"calls":1},{"val":{},"calls":2},{"val":{},"calls":3}]\nExplanation:\nMerging two empty objects will always result in an empty object. It may seem like there should only be 1 call to fn() because of cache-hits, however none of those objects are === to each other.\n\n\n
Example 3:
\n\n\nInput: \ngetInputs = () => { const o = {}; return [[o,o],[o,o],[o,o]]; }\nfn = function (a, b) { return ({...a, ...b}); }\nOutput: [{"val":{},"calls":1},{"val":{},"calls":1},{"val":{},"calls":1}]\nExplanation:\nMerging two empty objects will always result in an empty object. The 2nd and 3rd third function calls result in a cache-hit. This is because every object passed in is identical.\n\n\n
\n
Constraints:
\n\n1 <= inputs.length <= 105
0 <= inputs.flat().length <= 105
inputs[i][j] != NaN
Write code that enhances all arrays such that you can call the array.groupBy(fn)
method on any array and it will return a grouped version of the array.
A grouped array is an object where each key is the output of fn(arr[i])
and each value is an array containing all items in the original array which generate that key.
The provided callback fn
will accept an item in the array and return a string key.
The order of each value list should be the order the items appear in the array. Any order of keys is acceptable.
\n\nPlease solve it without lodash's _.groupBy
function.
\n
Example 1:
\n\n\nInput: \narray = [\n {"id":"1"},\n {"id":"1"},\n {"id":"2"}\n], \nfn = function (item) { \n return item.id; \n}\nOutput: \n{ \n "1": [{"id": "1"}, {"id": "1"}], \n "2": [{"id": "2"}] \n}\nExplanation:\nOutput is from array.groupBy(fn).\nThe selector function gets the "id" out of each item in the array.\nThere are two objects with an "id" of 1. Both of those objects are put in the first array.\nThere is one object with an "id" of 2. That object is put in the second array.\n\n\n
Example 2:
\n\n\nInput: \narray = [\n [1, 2, 3],\n [1, 3, 5],\n [1, 5, 9]\n]\nfn = function (list) { \n return String(list[0]); \n}\nOutput: \n{ \n "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]] \n}\nExplanation:\nThe array can be of any type. In this case, the selector function defines the key as being the first element in the array. \nAll the arrays have 1 as their first element so they are grouped together.\n{\n "1": [[1, 2, 3], [1, 3, 5], [1, 5, 9]]\n}\n\n\n
Example 3:
\n\n\nInput: \narray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nfn = function (n) { \n return String(n > 5);\n}\nOutput:\n{\n "true": [6, 7, 8, 9, 10],\n "false": [1, 2, 3, 4, 5]\n}\nExplanation:\nThe selector function splits the array by whether each number is greater than 5.\n\n\n
\n
Constraints:
\n\n0 <= array.length <= 105
fn
returns a stringGiven an integer array arr
and a filtering function fn
, return a filtered array filteredArr
.
The fn
function takes one or two arguments:
arr[i]
- number from the arr
i
- index of arr[i]
filteredArr
should only contain the elements from the arr
for which the expression fn(arr[i], i)
evaluates to a truthy value. A truthy value is a value where Boolean(value)
returns true
.
Please solve it without the built-in Array.filter
method.
\n
Example 1:
\n\n\nInput: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }\nOutput: [20,30]\nExplanation:\nconst newArray = filter(arr, fn); // [20, 30]\nThe function filters out values that are not greater than 10\n\n
Example 2:
\n\n\nInput: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }\nOutput: [1]\nExplanation:\nfn can also accept the index of each element\nIn this case, the function removes elements not at index 0\n\n\n
Example 3:
\n\n\nInput: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }\nOutput: [-2,0,1,2]\nExplanation:\nFalsey values such as 0 should be filtered out\n\n\n
\n
Constraints:
\n\n0 <= arr.length <= 1000
-109 <= arr[i] <= 109
Given an integer array arr
and a mapping function fn
, return a new array with a transformation applied to each element.
The returned array should be created such that returnedArray[i] = fn(arr[i], i)
.
Please solve it without the built-in Array.map
method.
\n
Example 1:
\n\n\nInput: arr = [1,2,3], fn = function plusone(n) { return n + 1; }\nOutput: [2,3,4]\nExplanation:\nconst newArray = map(arr, plusone); // [2,3,4]\nThe function increases each value in the array by one. \n\n\n
Example 2:
\n\n\nInput: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }\nOutput: [1,3,5]\nExplanation: The function increases each value by the index it resides in.\n\n\n
Example 3:
\n\n\nInput: arr = [10,20,30], fn = function constant() { return 42; }\nOutput: [42,42,42]\nExplanation: The function always returns 42.\n\n\n
\n
Constraints:
\n\n0 <= arr.length <= 1000
-109 <= arr[i] <= 109
fn
returns an integer.Given an asynchronous function fn
and a time t
in milliseconds, return a new time limited version of the input function. fn
takes arguments provided to the time limited function.
The time limited function should follow these rules:
\n\nfn
completes within the time limit of t
milliseconds, the time limited function should resolve with the result.fn
exceeds the time limit, the time limited function should reject with the string "Time Limit Exceeded"
.\n
Example 1:
\n\n\nInput: \nfn = async (n) => { \n await new Promise(res => setTimeout(res, 100)); \n return n * n; \n}\ninputs = [5]\nt = 50\nOutput: {"rejected":"Time Limit Exceeded","time":50}\nExplanation:\nconst limited = timeLimit(fn, t)\nconst start = performance.now()\nlet result;\ntry {\n const res = await limited(...inputs)\n result = {"resolved": res, "time": Math.floor(performance.now() - start)};\n} catch (err) {\n result = {"rejected": err, "time": Math.floor(performance.now() - start)};\n}\nconsole.log(result) // Output\n\nThe provided function is set to resolve after 100ms. However, the time limit is set to 50ms. It rejects at t=50ms because the time limit was reached.\n\n\n
Example 2:
\n\n\nInput: \nfn = async (n) => { \n await new Promise(res => setTimeout(res, 100)); \n return n * n; \n}\ninputs = [5]\nt = 150\nOutput: {"resolved":25,"time":100}\nExplanation:\nThe function resolved 5 * 5 = 25 at t=100ms. The time limit is never reached.\n\n\n
Example 3:
\n\n\nInput: \nfn = async (a, b) => { \n await new Promise(res => setTimeout(res, 120)); \n return a + b; \n}\ninputs = [5,10]\nt = 150\nOutput: {"resolved":15,"time":120}\nExplanation:\n\u200b\u200b\u200b\u200bThe function resolved 5 + 10 = 15 at t=120ms. The time limit is never reached.\n\n\n
Example 4:
\n\n\nInput: \nfn = async () => { \n throw "Error";\n}\ninputs = []\nt = 1000\nOutput: {"rejected":"Error","time":0}\nExplanation:\nThe function immediately throws an error.\n\n
\n
Constraints:
\n\n0 <= inputs.length <= 10
0 <= t <= 1000
fn
returns a promiseYou are given a 0-indexed m x n
integer matrix grid
. The width of a column is the maximum length of its integers.
grid = [[-10], [3], [12]]
, the width of the only column is 3
since -10
is of length 3
.Return an integer array ans
of size n
where ans[i]
is the width of the ith
column.
The length of an integer x
with len
digits is equal to len
if x
is non-negative, and len + 1
otherwise.
\n
Example 1:
\n\n\nInput: grid = [[1],[22],[333]]\nOutput: [3]\nExplanation: In the 0th column, 333 is of length 3.\n\n\n
Example 2:
\n\n\nInput: grid = [[-15,1,3],[15,7,12],[5,6,-2]]\nOutput: [3,1,2]\nExplanation: \nIn the 0th column, only -15 is of length 3.\nIn the 1st column, all integers are of length 1. \nIn the 2nd column, both 12 and -2 are of length 2.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 100
-109 <= grid[r][c] <= 109
We define the conversion array conver
of an array arr
as follows:
conver[i] = arr[i] + max(arr[0..i])
where max(arr[0..i])
is the maximum value of arr[j]
over 0 <= j <= i
.We also define the score of an array arr
as the sum of the values of the conversion array of arr
.
Given a 0-indexed integer array nums
of length n
, return an array ans
of length n
where ans[i]
is the score of the prefix nums[0..i]
.
\n
Example 1:
\n\n\nInput: nums = [2,3,7,5,10]\nOutput: [4,10,24,36,56]\nExplanation: \nFor the prefix [2], the conversion array is [4] hence the score is 4\nFor the prefix [2, 3], the conversion array is [4, 6] hence the score is 10\nFor the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24\nFor the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36\nFor the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,2,4,8,16]\nOutput: [2,4,8,16,32,64]\nExplanation: \nFor the prefix [1], the conversion array is [2] hence the score is 2\nFor the prefix [1, 1], the conversion array is [2, 2] hence the score is 4\nFor the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8\nFor the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16\nFor the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32\nFor the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
Given the root
of a binary tree, replace the value of each node in the tree with the sum of all its cousins' values.
Two nodes of a binary tree are cousins if they have the same depth with different parents.
\n\nReturn the root
of the modified tree.
Note that the depth of a node is the number of edges in the path from the root node to it.
\n\n\n
Example 1:
\n\nInput: root = [5,4,9,1,10,null,7]\nOutput: [0,0,0,7,7,null,11]\nExplanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.\n- Node with value 5 does not have any cousins so its sum is 0.\n- Node with value 4 does not have any cousins so its sum is 0.\n- Node with value 9 does not have any cousins so its sum is 0.\n- Node with value 1 has a cousin with value 7 so its sum is 7.\n- Node with value 10 has a cousin with value 7 so its sum is 7.\n- Node with value 7 has cousins with values 1 and 10 so its sum is 11.\n\n\n
Example 2:
\n\nInput: root = [3,1,2]\nOutput: [0,0,0]\nExplanation: The diagram above shows the initial binary tree and the binary tree after changing the value of each node.\n- Node with value 3 does not have any cousins so its sum is 0.\n- Node with value 1 does not have any cousins so its sum is 0.\n- Node with value 2 does not have any cousins so its sum is 0.\n\n\n
\n
Constraints:
\n\n[1, 105]
.1 <= Node.val <= 104
There is a directed weighted graph that consists of n
nodes numbered from 0
to n - 1
. The edges of the graph are initially represented by the given array edges
where edges[i] = [fromi, toi, edgeCosti]
meaning that there is an edge from fromi
to toi
with the cost edgeCosti
.
Implement the Graph
class:
Graph(int n, int[][] edges)
initializes the object with n
nodes and the given edges.addEdge(int[] edge)
adds an edge to the list of edges where edge = [from, to, edgeCost]
. It is guaranteed that there is no edge between the two nodes before adding this one.int shortestPath(int node1, int node2)
returns the minimum cost of a path from node1
to node2
. If no path exists, return -1
. The cost of a path is the sum of the costs of the edges in the path.\n
Example 1:
\n\nInput\n["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"]\n[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]]\nOutput\n[null, 6, -1, null, 6]\n\nExplanation\nGraph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);\ng.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6.\ng.shortestPath(0, 3); // return -1. There is no path from 0 to 3.\ng.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above.\ng.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
0 <= edges.length <= n * (n - 1)
edges[i].length == edge.length == 3
0 <= fromi, toi, from, to, node1, node2 <= n - 1
1 <= edgeCosti, edgeCost <= 106
100
calls will be made for addEdge
.100
calls will be made for shortestPath
.Given a m x n
binary matrix mat
, find the 0-indexed position of the row that contains the maximum count of ones, and the number of ones in that row.
In case there are multiple rows that have the maximum count of ones, the row with the smallest row number should be selected.
\n\nReturn an array containing the index of the row, and the number of ones in it.
\n\n\n
Example 1:
\n\n\nInput: mat = [[0,1],[1,0]]\nOutput: [0,1]\nExplanation: Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1)
. So, the answer is [0,1]. \n
\n\nExample 2:
\n\n\nInput: mat = [[0,0,0],[0,1,1]]\nOutput: [1,2]\nExplanation: The row indexed 1 has the maximum count of ones\n\n(2)
. So we return its index,1
, and the count. So, the answer is [1,2].\n
Example 3:
\n\n\nInput: mat = [[0,0],[1,1],[0,0]]\nOutput: [1,2]\nExplanation: The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j]
is either 0
or 1
.You are given two integer arrays nums
and divisors
.
The divisibility score of divisors[i]
is the number of indices j
such that nums[j]
is divisible by divisors[i]
.
Return the integer divisors[i]
with the maximum divisibility score. If multiple integers have the maximum score, return the smallest one.
\n
Example 1:
\n\nInput: nums = [2,9,15,50], divisors = [5,3,7,2]
\n\nOutput: 2
\n\nExplanation:
\n\nThe divisibility score of divisors[0]
is 2 since nums[2]
and nums[3]
are divisible by 5.
The divisibility score of divisors[1]
is 2 since nums[1]
and nums[2]
are divisible by 3.
The divisibility score of divisors[2]
is 0 since none of the numbers in nums
is divisible by 7.
The divisibility score of divisors[3]
is 2 since nums[0]
and nums[3]
are divisible by 2.
As divisors[0]
, divisors[1]
, and divisors[3]
have the same divisibility score, we return the smaller one which is divisors[3]
.
Example 2:
\n\nInput: nums = [4,7,9,3,9], divisors = [5,2,3]
\n\nOutput: 3
\n\nExplanation:
\n\nThe divisibility score of divisors[0]
is 0 since none of numbers in nums
is divisible by 5.
The divisibility score of divisors[1]
is 1 since only nums[0]
is divisible by 2.
The divisibility score of divisors[2]
is 3 since nums[2]
, nums[3]
and nums[4]
are divisible by 3.
Example 3:
\n\nInput: nums = [20,14,21,10], divisors = [10,16,20]
\n\nOutput: 10
\n\nExplanation:
\n\nThe divisibility score of divisors[0]
is 2 since nums[0]
and nums[3]
are divisible by 10.
The divisibility score of divisors[1]
is 0 since none of the numbers in nums
is divisible by 16.
The divisibility score of divisors[2]
is 1 since nums[0]
is divisible by 20.
\n
Constraints:
\n\n1 <= nums.length, divisors.length <= 1000
1 <= nums[i], divisors[i] <= 109
Given a string word
to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word
becomes valid.
A string is called valid if it can be formed by concatenating the string "abc" several times.
\n\n\n
Example 1:
\n\n\nInput: word = "b"\nOutput: 2\nExplanation: Insert the letter "a" right before "b", and the letter "c" right next to "b" to obtain the valid string "abc".\n\n\n
Example 2:
\n\n\nInput: word = "aaa"\nOutput: 6\nExplanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc".\n\n\n
Example 3:
\n\n\nInput: word = "abc"\nOutput: 0\nExplanation: word is already valid. No modifications are needed. \n\n\n
\n
Constraints:
\n\n1 <= word.length <= 50
word
consists of letters "a", "b" and "c" only. There exists an undirected and unrooted tree with n
nodes indexed from 0
to n - 1
. You are given the integer n
and a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
Each node has an associated price. You are given an integer array price
, where price[i]
is the price of the ith
node.
The price sum of a given path is the sum of the prices of all nodes lying on that path.
\n\nAdditionally, you are given a 2D integer array trips
, where trips[i] = [starti, endi]
indicates that you start the ith
trip from the node starti
and travel to the node endi
by any path you like.
Before performing your first trip, you can choose some non-adjacent nodes and halve the prices.
\n\nReturn the minimum total price sum to perform all the given trips.
\n\n\n
Example 1:
\n\nInput: n = 4, edges = [[0,1],[1,2],[1,3]], price = [2,2,10,6], trips = [[0,3],[2,1],[2,3]]\nOutput: 23\nExplanation: The diagram above denotes the tree after rooting it at node 2. The first part shows the initial tree and the second part shows the tree after choosing nodes 0, 2, and 3, and making their price half.\nFor the 1st trip, we choose path [0,1,3]. The price sum of that path is 1 + 2 + 3 = 6.\nFor the 2nd trip, we choose path [2,1]. The price sum of that path is 2 + 5 = 7.\nFor the 3rd trip, we choose path [2,1,3]. The price sum of that path is 5 + 2 + 3 = 10.\nThe total price sum of all trips is 6 + 7 + 10 = 23.\nIt can be proven, that 23 is the minimum answer that we can achieve.\n\n\n
Example 2:
\n\nInput: n = 2, edges = [[0,1]], price = [2,2], trips = [[0,0]]\nOutput: 1\nExplanation: The diagram above denotes the tree after rooting it at node 0. The first part shows the initial tree and the second part shows the tree after choosing node 0, and making its price half.\nFor the 1st trip, we choose path [0]. The price sum of that path is 1.\nThe total price sum of all trips is 1. It can be proven, that 1 is the minimum answer that we can achieve.\n\n\n
\n
Constraints:
\n\n1 <= n <= 50
edges.length == n - 1
0 <= ai, bi <= n - 1
edges
represents a valid tree.price.length == n
price[i]
is an even integer.1 <= price[i] <= 1000
1 <= trips.length <= 100
0 <= starti, endi <= n - 1
Write a generator function that returns a generator object which yields the fibonacci sequence.
\n\nThe fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2
.
The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13
.
\n
Example 1:
\n\n\nInput: callCount = 5\nOutput: [0,1,1,2,3]\nExplanation:\nconst gen = fibGenerator();\ngen.next().value; // 0\ngen.next().value; // 1\ngen.next().value; // 1\ngen.next().value; // 2\ngen.next().value; // 3\n\n\n
Example 2:
\n\n\nInput: callCount = 0\nOutput: []\nExplanation: gen.next() is never called so nothing is outputted\n\n\n
\n
Constraints:
\n\n0 <= callCount <= 50
Given a multi-dimensional array of integers, return a generator object which yields integers in the same order as inorder traversal.
\n\nA multi-dimensional array is a recursive data structure that contains both integers and other multi-dimensional arrays.
\n\ninorder traversal iterates over each array from left to right, yielding any integers it encounters or applying inorder traversal to any arrays it encounters.
\n\n\n
Example 1:
\n\n\nInput: arr = [[[6]],[1,3],[]]\nOutput: [6,1,3]\nExplanation:\nconst generator = inorderTraversal(arr);\ngenerator.next().value; // 6\ngenerator.next().value; // 1\ngenerator.next().value; // 3\ngenerator.next().done; // true\n\n\n
Example 2:
\n\n\nInput: arr = []\nOutput: []\nExplanation: There are no integers so the generator doesn't yield anything.\n\n\n
\n
Constraints:
\n\n0 <= arr.flat().length <= 105
0 <= arr.flat()[i] <= 105
maxNestingDepth <= 105
\nCan you solve this without creating a new flattened version of the array?", - "likes": 165, + "likes": 167, "dislikes": 11, - "stats": "{\"totalAccepted\": \"14.4K\", \"totalSubmission\": \"18K\", \"totalAcceptedRaw\": 14357, \"totalSubmissionRaw\": 18037, \"acRate\": \"79.6%\"}", + "stats": "{\"totalAccepted\": \"15.8K\", \"totalSubmission\": \"19.7K\", \"totalAcceptedRaw\": 15778, \"totalSubmissionRaw\": 19729, \"acRate\": \"80.0%\"}", "similarQuestions": "[{\"title\": \"Flatten Deeply Nested Array\", \"titleSlug\": \"flatten-deeply-nested-array\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Generate Fibonacci Sequence\", \"titleSlug\": \"generate-fibonacci-sequence\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Design Cancellable Function\", \"titleSlug\": \"design-cancellable-function\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "categoryTitle": "JavaScript", "hints": [ @@ -100342,9 +100581,9 @@ "questionFrontendId": "2650", "title": "Design Cancellable Function", "content": "
Sometimes you have a long running task, and you may wish to cancel it before it completes. To help with this goal, write a function cancellable
that accepts a generator object and returns an array of two values: a cancel function and a promise.
You may assume the generator function will only yield promises. It is your function's responsibility to pass the values resolved by the promise back to the generator. If the promise rejects, your function should throw that error back to the generator.
\n\nIf the cancel callback is called before the generator is done, your function should throw an error back to the generator. That error should be the string "Cancelled"
(Not an Error
object). If the error was caught, the returned promise should resolve with the next value that was yielded or returned. Otherwise, the promise should reject with the thrown error. No more code should be executed.
When the generator is done, the promise your function returned should resolve the value the generator returned. If, however, the generator throws an error, the returned promise should reject with the error.
\n\nAn example of how your code would be used:
\n\n\nfunction* tasks() {\n const val = yield new Promise(resolve => resolve(2 + 2));\n yield new Promise(resolve => setTimeout(resolve, 100));\n return val + 1; // calculation shouldn't be done.\n}\nconst [cancel, promise] = cancellable(tasks());\nsetTimeout(cancel, 50);\npromise.catch(console.log); // logs "Cancelled" at t=50ms\n\n\n
If instead cancel()
was not called or was called after t=100ms
, the promise would have resolved 5
.
\n
Example 1:
\n\n\nInput: \ngeneratorFunction = function*() { \n return 42; \n}\ncancelledAt = 100\nOutput: {"resolved": 42}\nExplanation:\nconst generator = generatorFunction();\nconst [cancel, promise] = cancellable(generator);\nsetTimeout(cancel, 100);\npromise.then(console.log); // resolves 42 at t=0ms\n\nThe generator immediately yields 42 and finishes. Because of that, the returned promise immediately resolves 42. Note that cancelling a finished generator does nothing.\n\n\n
Example 2:
\n\n\nInput:\ngeneratorFunction = function*() { \n const msg = yield new Promise(res => res("Hello")); \n throw `Error: ${msg}`; \n}\ncancelledAt = null\nOutput: {"rejected": "Error: Hello"}\nExplanation:\nA promise is yielded. The function handles this by waiting for it to resolve and then passes the resolved value back to the generator. Then an error is thrown which has the effect of causing the promise to reject with the same thrown error.\n\n\n
Example 3:
\n\n\nInput: \ngeneratorFunction = function*() { \n yield new Promise(res => setTimeout(res, 200)); \n return "Success"; \n}\ncancelledAt = 100\nOutput: {"rejected": "Cancelled"}\nExplanation:\nWhile the function is waiting for the yielded promise to resolve, cancel() is called. This causes an error message to be sent back to the generator. Since this error is uncaught, the returned promise rejected with this error.\n\n\n
Example 4:
\n\n\nInput:\ngeneratorFunction = function*() { \n let result = 0; \n yield new Promise(res => setTimeout(res, 100));\n result += yield new Promise(res => res(1)); \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n return result;\n}\ncancelledAt = null\nOutput: {"resolved": 2}\nExplanation:\n4 promises are yielded. Two of those promises have their values added to the result. After 200ms, the generator finishes with a value of 2, and that value is resolved by the returned promise.\n\n\n
Example 5:
\n\n\nInput: \ngeneratorFunction = function*() { \n let result = 0; \n try { \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n yield new Promise(res => setTimeout(res, 100)); \n result += yield new Promise(res => res(1)); \n } catch(e) { \n return result; \n } \n return result; \n}\ncancelledAt = 150\nOutput: {"resolved": 1}\nExplanation:\nThe first two yielded promises resolve and cause the result to increment. However, at t=150ms, the generator is cancelled. The error sent to the generator is caught and the result is returned and finally resolved by the returned promise.\n\n\n
Example 6:
\n\n\nInput: \ngeneratorFunction = function*() { \n try { \n yield new Promise((resolve, reject) => reject("Promise Rejected")); \n } catch(e) { \n let a = yield new Promise(resolve => resolve(2));\n let b = yield new Promise(resolve => resolve(2)); \n return a + b; \n }; \n}\ncancelledAt = null\nOutput: {"resolved": 4}\nExplanation:\nThe first yielded promise immediately rejects. This error is caught. Because the generator hasn't been cancelled, execution continues as usual. It ends up resolving 2 + 2 = 4.\n\n
\n
Constraints:
\n\ncancelledAt == null or 0 <= cancelledAt <= 1000
generatorFunction
returns a generator objectYou are given a positive integer arrivalTime
denoting the arrival time of a train in hours, and another positive integer delayedTime
denoting the amount of delay in hours.
Return the time when the train will arrive at the station.
\n\nNote that the time in this problem is in 24-hours format.
\n\n\n
Example 1:
\n\n\nInput: arrivalTime = 15, delayedTime = 5 \nOutput: 20 \nExplanation: Arrival time of the train was 15:00 hours. It is delayed by 5 hours. Now it will reach at 15+5 = 20 (20:00 hours).\n\n\n
Example 2:
\n\n\nInput: arrivalTime = 13, delayedTime = 11\nOutput: 0\nExplanation: Arrival time of the train was 13:00 hours. It is delayed by 11 hours. Now it will reach at 13+11=24 (Which is denoted by 00:00 in 24 hours format so return 0).\n\n\n
\n
Constraints:
\n\n1 <= arrivaltime < 24
1 <= delayedTime <= 24
Given a positive integer n
, find the sum of all integers in the range [1, n]
inclusive that are divisible by 3
, 5
, or 7
.
Return an integer denoting the sum of all numbers in the given range satisfying the constraint.
\n\n\n
Example 1:
\n\n\nInput: n = 7\nOutput: 21\nExplanation: Numbers in the range\n\n[1, 7]
that are divisible by3
,5,
or7
are3, 5, 6, 7
. The sum of these numbers is21
.\n
Example 2:
\n\n\nInput: n = 10\nOutput: 40\nExplanation: Numbers in the range\n\n[1, 10] that are
divisible by3
,5,
or7
are3, 5, 6, 7, 9, 10
. The sum of these numbers is 40.\n
Example 3:
\n\n\nInput: n = 9\nOutput: 30\nExplanation: Numbers in the range\n\n[1, 9]
that are divisible by3
,5
, or7
are3, 5, 6, 7, 9
. The sum of these numbers is30
.\n
\n
Constraints:
\n\n1 <= n <= 103
Given an integer array nums
containing n
integers, find the beauty of each subarray of size k
.
The beauty of a subarray is the xth
smallest integer in the subarray if it is negative, or 0
if there are fewer than x
negative integers.
Return an integer array containing n - k + 1
integers, which denote the beauty of the subarrays in order from the first index in the array.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\t\n
Example 1:
\n\n\nInput: nums = [1,-1,-3,-2,3], k = 3, x = 2\nOutput: [-1,-2,-2]\nExplanation: There are 3 subarrays with size k = 3. \nThe first subarray is\n\n[1, -1, -3]
and the 2nd smallest negative integer is -1. \nThe second subarray is[-1, -3, -2]
and the 2nd smallest negative integer is -2. \nThe third subarray is[-3, -2, 3]
and the 2nd smallest negative integer is -2.
Example 2:
\n\n\nInput: nums = [-1,-2,-3,-4,-5], k = 2, x = 2\nOutput: [-1,-2,-3,-4]\nExplanation: There are 4 subarrays with size k = 2.\nFor\n\n[-1, -2]
, the 2nd smallest negative integer is -1.\nFor[-2, -3]
, the 2nd smallest negative integer is -2.\nFor[-3, -4]
, the 2nd smallest negative integer is -3.\nFor[-4, -5]
, the 2nd smallest negative integer is -4.
Example 3:
\n\n\nInput: nums = [-3,1,2,-3,0,-3], k = 2, x = 1\nOutput: [-3,0,-3,-3,-3]\nExplanation: There are 5 subarrays with size k = 2.\nFor\n\n[-3, 1]
, the 1st smallest negative integer is -3.\nFor[1, 2]
, there is no negative integer so the beauty is 0.\nFor[2, -3]
, the 1st smallest negative integer is -3.\nFor[-3, 0]
, the 1st smallest negative integer is -3.\nFor[0, -3]
, the 1st smallest negative integer is -3.
\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
1 <= k <= n
1 <= x <= k
-50 <= nums[i] <= 50
You are given a 0-indexed array nums
consisiting of positive integers. You can do the following operation on the array any number of times:
i
such that 0 <= i < n - 1
and replace either of nums[i]
or nums[i+1]
with their gcd value.Return the minimum number of operations to make all elements of nums
equal to 1
. If it is impossible, return -1
.
The gcd of two integers is the greatest common divisor of the two integers.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,6,3,4]\nOutput: 4\nExplanation: We can do the following operations:\n- Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4].\n- Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4].\n- Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4].\n- Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].\n\n\n
Example 2:
\n\n\nInput: nums = [2,10,6,14]\nOutput: -1\nExplanation: It can be shown that it is impossible to make all the elements equal to 1.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 50
1 <= nums[i] <= 106
You are given a 0-indexed integer array nums
and an integer k
. Your task is to perform the following operation exactly k
times in order to maximize your score:
m
from nums
.m
from the array.m + 1
to the array.m
.Return the maximum score you can achieve after performing the operation exactly k
times.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5], k = 3\nOutput: 18\nExplanation: We need to choose exactly 3 elements from nums to maximize the sum.\nFor the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6]\nFor the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7]\nFor the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8]\nSo, we will return 18.\nIt can be proven, that 18 is the maximum answer that we can achieve.\n\n\n
Example 2:
\n\n\nInput: nums = [5,5,5], k = 2\nOutput: 11\nExplanation: We need to choose exactly 2 elements from nums to maximize the sum.\nFor the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6]\nFor the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7]\nSo, we will return 11.\nIt can be proven, that 11 is the maximum answer that we can achieve.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 100
\n\n", - "likes": 390, + "likes": 402, "dislikes": 51, - "stats": "{\"totalAccepted\": \"85.7K\", \"totalSubmission\": \"104.7K\", \"totalAcceptedRaw\": 85689, \"totalSubmissionRaw\": 104737, \"acRate\": \"81.8%\"}", + "stats": "{\"totalAccepted\": \"91.5K\", \"totalSubmission\": \"114.8K\", \"totalAcceptedRaw\": 91541, \"totalSubmissionRaw\": 114764, \"acRate\": \"79.8%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -100571,9 +100810,9 @@ "questionFrontendId": "2657", "title": "Find the Prefix Common Array of Two Arrays", "content": "
You are given two 0-indexed integer permutations A
and B
of length n
.
A prefix common array of A
and B
is an array C
such that C[i]
is equal to the count of numbers that are present at or before the index i
in both A
and B
.
Return the prefix common array of A
and B
.
A sequence of n
integers is called a permutation if it contains all integers from 1
to n
exactly once.
\n
Example 1:
\n\n\nInput: A = [1,3,2,4], B = [3,1,2,4]\nOutput: [0,2,3,4]\nExplanation: At i = 0: no number is common, so C[0] = 0.\nAt i = 1: 1 and 3 are common in A and B, so C[1] = 2.\nAt i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.\nAt i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.\n\n\n
Example 2:
\n\n\nInput: A = [2,3,1], B = [3,1,2]\nOutput: [0,1,3]\nExplanation: At i = 0: no number is common, so C[0] = 0.\nAt i = 1: only 3 is common in A and B, so C[1] = 1.\nAt i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.\n\n\n
\n
Constraints:
\n\n1 <= A.length == B.length == n <= 50
1 <= A[i], B[i] <= n
It is guaranteed that A and B are both a permutation of n integers.
You are given a 0-indexed 2D matrix grid
of size m x n
, where (r, c)
represents:
grid[r][c] = 0
, orgrid[r][c]
fish, if grid[r][c] > 0
.A fisher can start at any water cell (r, c)
and can do the following operations any number of times:
(r, c)
, orReturn the maximum number of fish the fisher can catch if he chooses his starting cell optimally, or 0
if no water cell exists.
An adjacent cell of the cell (r, c)
, is one of the cells (r, c + 1)
, (r, c - 1)
, (r + 1, c)
or (r - 1, c)
if it exists.
\n
Example 1:
\n\nInput: grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]]\nOutput: 7\nExplanation: The fisher can start at cell\n\n(1,3)
and collect 3 fish, then move to cell(2,3)
and collect 4 fish.\n
Example 2:
\n\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]\nOutput: 1\nExplanation: The fisher can start at cells (0,0) or (3,3) and collect a single fish. \n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 10
0 <= grid[i][j] <= 10
You are given an integer array nums
containing distinct numbers, and you can perform the following operations until the array is empty:
Return an integer denoting the number of operations it takes to make nums
empty.
\n
Example 1:
\n\n\nInput: nums = [3,4,-1]\nOutput: 5\n\n\n
Operation | \n\t\t\tArray | \n\t\t
---|---|
1 | \n\t\t\t[4, -1, 3] | \n\t\t
2 | \n\t\t\t[-1, 3, 4] | \n\t\t
3 | \n\t\t\t[3, 4] | \n\t\t
4 | \n\t\t\t[4] | \n\t\t
5 | \n\t\t\t[] | \n\t\t
Example 2:
\n\n\nInput: nums = [1,2,4,3]\nOutput: 5\n\n\n
Operation | \n\t\t\tArray | \n\t\t
---|---|
1 | \n\t\t\t[2, 4, 3] | \n\t\t
2 | \n\t\t\t[4, 3] | \n\t\t
3 | \n\t\t\t[3, 4] | \n\t\t
4 | \n\t\t\t[4] | \n\t\t
5 | \n\t\t\t[] | \n\t\t
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 3\n\n\n
Operation | \n\t\t\tArray | \n\t\t
---|---|
1 | \n\t\t\t[2, 3] | \n\t\t
2 | \n\t\t\t[3] | \n\t\t
3 | \n\t\t\t[] | \n\t\t
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
nums
are distinct.You are given two 0-indexed integer arrays player1
and player2
, representing the number of pins that player 1 and player 2 hit in a bowling game, respectively.
The bowling game consists of n
turns, and the number of pins in each turn is exactly 10.
Assume a player hits xi
pins in the ith turn. The value of the ith turn for the player is:
2xi
if the player hits 10 pins in either (i - 1)th or (i - 2)th turn.xi
.The score of the player is the sum of the values of their n
turns.
Return
\n\n\n
Example 1:
\n\nInput: player1 = [5,10,3,2], player2 = [6,5,7,3]
\n\nOutput: 1
\n\nExplanation:
\n\nThe score of player 1 is 5 + 10 + 2*3 + 2*2 = 25.
\n\nThe score of player 2 is 6 + 5 + 7 + 3 = 21.
\nExample 2:
\n\nInput: player1 = [3,5,7,6], player2 = [8,10,10,2]
\n\nOutput: 2
\n\nExplanation:
\n\nThe score of player 1 is 3 + 5 + 7 + 6 = 21.
\n\nThe score of player 2 is 8 + 10 + 2*10 + 2*2 = 42.
\nExample 3:
\n\nInput: player1 = [2,3], player2 = [4,1]
\n\nOutput: 0
\n\nExplanation:
\n\nThe score of player1 is 2 + 3 = 5.
\n\nThe score of player2 is 4 + 1 = 5.
\nExample 4:
\n\nInput: player1 = [1,1,1,10,10,10,10], player2 = [10,10,10,10,1,1,1]
\n\nOutput: 2
\n\nExplanation:
\n\nThe score of player1 is 1 + 1 + 1 + 10 + 2*10 + 2*10 + 2*10 = 73.
\n\nThe score of player2 is 10 + 2*10 + 2*10 + 2*10 + 2*1 + 2*1 + 1 = 75.
\n\n
Constraints:
\n\nn == player1.length == player2.length
1 <= n <= 1000
0 <= player1[i], player2[i] <= 10
You are given a 0-indexed integer array arr
, and an m x n
integer matrix mat
. arr
and mat
both contain all the integers in the range [1, m * n]
.
Go through each index i
in arr
starting from index 0
and paint the cell in mat
containing the integer arr[i]
.
Return the smallest index i
at which either a row or a column will be completely painted in mat
.
\n
Example 1:
\n\nInput: arr = [1,3,4,2], mat = [[1,4],[2,3]]\nOutput: 2\nExplanation: The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].\n\n\n
Example 2:
\n\nInput: arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]\nOutput: 3\nExplanation: The second column becomes fully painted at arr[3].\n\n\n
\n
Constraints:
\n\nm == mat.length
n = mat[i].length
arr.length == m * n
1 <= m, n <= 105
1 <= m * n <= 105
1 <= arr[i], mat[r][c] <= m * n
arr
are unique.mat
are unique.You are given an array start
where start = [startX, startY]
represents your initial position (startX, startY)
in a 2D space. You are also given the array target
where target = [targetX, targetY]
represents your target position (targetX, targetY)
.
The cost of going from a position (x1, y1)
to any other position in the space (x2, y2)
is |x2 - x1| + |y2 - y1|
.
There are also some special roads. You are given a 2D array specialRoads
where specialRoads[i] = [x1i, y1i, x2i, y2i, costi]
indicates that the ith
special road goes in one direction from (x1i, y1i)
to (x2i, y2i)
with a cost equal to costi
. You can use each special road any number of times.
Return the minimum cost required to go from (startX, startY)
to (targetX, targetY)
.
\n
Example 1:
\n\nInput: start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]
\n\nOutput: 5
\n\nExplanation:
\n\nspecialRoads[0]
with the cost 2.specialRoads[1]
with the cost 1.So the total cost is 1 + 2 + 1 + 1 = 5.
\nExample 2:
\n\nInput: start = [3,2], target = [5,7], specialRoads = [[5,7,3,2,1],[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]
\n\nOutput: 7
\n\nExplanation:
\n\nIt is optimal not to use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.
\n\nNote that the specialRoads[0]
is directed from (5,7) to (3,2).
Example 3:
\n\nInput: start = [1,1], target = [10,4], specialRoads = [[4,2,1,1,3],[1,2,7,4,4],[10,3,6,1,2],[6,1,1,2,3]]
\n\nOutput: 8
\n\nExplanation:
\n\nspecialRoads[1]
with the cost 4.\n
Constraints:
\n\nstart.length == target.length == 2
1 <= startX <= targetX <= 105
1 <= startY <= targetY <= 105
1 <= specialRoads.length <= 200
specialRoads[i].length == 5
startX <= x1i, x2i <= targetX
startY <= y1i, y2i <= targetY
1 <= costi <= 105
A string is beautiful if:
\n\nk
letters of the English lowercase alphabet.2
or more which is a palindrome.You are given a beautiful string s
of length n
and a positive integer k
.
Return the lexicographically smallest string of length n
, which is larger than s
and is beautiful. If there is no such string, return an empty string.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
.
"abcd"
is lexicographically larger than "abcc"
because the first position they differ is at the fourth character, and d
is greater than c
.\n
Example 1:
\n\n\nInput: s = "abcz", k = 26\nOutput: "abda"\nExplanation: The string "abda" is beautiful and lexicographically larger than the string "abcz".\nIt can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda".\n\n\n
Example 2:
\n\n\nInput: s = "dc", k = 4\nOutput: ""\nExplanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.\n\n\n
\n
Constraints:
\n\n1 <= n == s.length <= 105
4 <= k <= 26
s
is a beautiful string.Write a function createCounter
. It should accept an initial integer init
. It should return an object with three functions.
The three functions are:
\n\nincrement()
increases the current value by 1 and then returns it.decrement()
reduces the current value by 1 and then returns it.reset()
sets the current value to init
and then returns it.\n
Example 1:
\n\n\nInput: init = 5, calls = ["increment","reset","decrement"]\nOutput: [6,5,4]\nExplanation:\nconst counter = createCounter(5);\ncounter.increment(); // 6\ncounter.reset(); // 5\ncounter.decrement(); // 4\n\n\n
Example 2:
\n\n\nInput: init = 0, calls = ["increment","increment","decrement","reset","reset"]\nOutput: [1,2,1,0,0]\nExplanation:\nconst counter = createCounter(0);\ncounter.increment(); // 1\ncounter.increment(); // 2\ncounter.decrement(); // 1\ncounter.reset(); // 0\ncounter.reset(); // 0\n\n\n
\n
Constraints:
\n\n-1000 <= init <= 1000
0 <= calls.length <= 1000
calls[i]
is one of "increment", "decrement" and "reset"Given a function fn
, return a new function that is identical to the original function except that it ensures fn
is called at most once.
fn
.undefined
.\n
Example 1:
\n\n\nInput: fn = (a,b,c) => (a + b + c), calls = [[1,2,3],[2,3,6]]\nOutput: [{"calls":1,"value":6}]\nExplanation:\nconst onceFn = once(fn);\nonceFn(1, 2, 3); // 6\nonceFn(2, 3, 6); // undefined, fn was not called\n\n\n
Example 2:
\n\n\nInput: fn = (a,b,c) => (a * b * c), calls = [[5,7,4],[2,3,6],[4,6,8]]\nOutput: [{"calls":1,"value":140}]\nExplanation:\nconst onceFn = once(fn);\nonceFn(5, 7, 4); // 140\nonceFn(2, 3, 6); // undefined, fn was not called\nonceFn(4, 6, 8); // undefined, fn was not called\n\n\n
\n
Constraints:
\n\ncalls
is a valid JSON array1 <= calls.length <= 10
1 <= calls[i].length <= 100
2 <= JSON.stringify(calls).length <= 1000
createHelloWorld
. It should return a new function that always returns "Hello World"
.\n\n
Example 1:
\n\n\nInput: args = []\nOutput: "Hello World"\nExplanation:\nconst f = createHelloWorld();\nf(); // "Hello World"\n\nThe function returned by createHelloWorld should always return "Hello World".\n\n\n
Example 2:
\n\n\nInput: args = [{},null,42]\nOutput: "Hello World"\nExplanation:\nconst f = createHelloWorld();\nf({}, null, 42); // "Hello World"\n\nAny arguments could be passed to the function but it should still always return "Hello World".\n\n\n
\n
Constraints:
\n\n0 <= args.length <= 10
You are given a 0-indexed array nums
of length n
.
The distinct difference array of nums
is an array diff
of length n
such that diff[i]
is equal to the number of distinct elements in the suffix nums[i + 1, ..., n - 1]
subtracted from the number of distinct elements in the prefix nums[0, ..., i]
.
Return the distinct difference array of nums
.
Note that nums[i, ..., j]
denotes the subarray of nums
starting at index i
and ending at index j
inclusive. Particularly, if i > j
then nums[i, ..., j]
denotes an empty subarray.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: [-3,-1,1,3,5]\nExplanation: For index i = 0, there is 1 element in the prefix and 4 distinct elements in the suffix. Thus, diff[0] = 1 - 4 = -3.\nFor index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1.\nFor index i = 2, there are 3 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 3 - 2 = 1.\nFor index i = 3, there are 4 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 4 - 1 = 3.\nFor index i = 4, there are 5 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 5 - 0 = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,3,4,2]\nOutput: [-2,-1,0,2,3]\nExplanation: For index i = 0, there is 1 element in the prefix and 3 distinct elements in the suffix. Thus, diff[0] = 1 - 3 = -2.\nFor index i = 1, there are 2 distinct elements in the prefix and 3 distinct elements in the suffix. Thus, diff[1] = 2 - 3 = -1.\nFor index i = 2, there are 2 distinct elements in the prefix and 2 distinct elements in the suffix. Thus, diff[2] = 2 - 2 = 0.\nFor index i = 3, there are 3 distinct elements in the prefix and 1 distinct element in the suffix. Thus, diff[3] = 3 - 1 = 2.\nFor index i = 4, there are 3 distinct elements in the prefix and no elements in the suffix. Thus, diff[4] = 3 - 0 = 3.\n\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 50
1 <= nums[i] <= 50
Design a data structure that keeps track of the values in it and answers some queries regarding their frequencies.
\n\nImplement the FrequencyTracker
class.
FrequencyTracker()
: Initializes the FrequencyTracker
object with an empty array initially.void add(int number)
: Adds number
to the data structure.void deleteOne(int number)
: Deletes one occurrence of number
from the data structure. The data structure may not contain number
, and in this case nothing is deleted.bool hasFrequency(int frequency)
: Returns true
if there is a number in the data structure that occurs frequency
number of times, otherwise, it returns false
.\n
Example 1:
\n\n\nInput\n["FrequencyTracker", "add", "add", "hasFrequency"]\n[[], [3], [3], [2]]\nOutput\n[null, null, null, true]\n\nExplanation\nFrequencyTracker frequencyTracker = new FrequencyTracker();\nfrequencyTracker.add(3); // The data structure now contains [3]\nfrequencyTracker.add(3); // The data structure now contains [3, 3]\nfrequencyTracker.hasFrequency(2); // Returns true, because 3 occurs twice\n\n\n\n
Example 2:
\n\n\nInput\n["FrequencyTracker", "add", "deleteOne", "hasFrequency"]\n[[], [1], [1], [1]]\nOutput\n[null, null, null, false]\n\nExplanation\nFrequencyTracker frequencyTracker = new FrequencyTracker();\nfrequencyTracker.add(1); // The data structure now contains [1]\nfrequencyTracker.deleteOne(1); // The data structure becomes empty []\nfrequencyTracker.hasFrequency(1); // Returns false, because the data structure is empty\n\n\n\n
Example 3:
\n\n\nInput\n["FrequencyTracker", "hasFrequency", "add", "hasFrequency"]\n[[], [2], [3], [1]]\nOutput\n[null, false, null, true]\n\nExplanation\nFrequencyTracker frequencyTracker = new FrequencyTracker();\nfrequencyTracker.hasFrequency(2); // Returns false, because the data structure is empty\nfrequencyTracker.add(3); // The data structure now contains [3]\nfrequencyTracker.hasFrequency(1); // Returns true, because 3 occurs once\n\n\n\n
\n
Constraints:
\n\n1 <= number <= 105
1 <= frequency <= 105
2 * 105
calls will be made to add
, deleteOne
, and hasFrequency
in total.You are given an integer n
representing an array colors
of length n
where all elements are set to 0's meaning uncolored. You are also given a 2D integer array queries
where queries[i] = [indexi, colori]
. For the ith
query:
colors[indexi]
to colori
.colors
set to the same color (regardless of colori
).Return an array answer
of the same length as queries
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
\n\nOutput: [0,1,1,0,2]
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 1, queries = [[0,100000]]
\n\nOutput: [0]
\n\nExplanation:
\n\nAfter the 1st query colors = [100000]. The count of adjacent pairs with the same color is 0.
\n\n
Constraints:
\n\n1 <= n <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= indexi <= n - 1
1 <= colori <= 105
You are given an integer n
representing an array colors
of length n
where all elements are set to 0's meaning uncolored. You are also given a 2D integer array queries
where queries[i] = [indexi, colori]
. For the ith
query:
colors[indexi]
to colori
.colors
which have the same color (regardless of colori
).Return an array answer
of the same length as queries
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: n = 4, queries = [[0,2],[1,2],[3,1],[1,1],[2,1]]
\n\nOutput: [0,1,1,0,2]
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 1, queries = [[0,100000]]
\n\nOutput: [0]
\n\nExplanation:
\n\nAfter the 1st query colors = [100000]. The count of adjacent pairs with the same color is 0.
\n\n
Constraints:
\n\n1 <= n <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= indexi <= n - 1
1 <= colori <= 105
You are given an integer n
representing the number of nodes in a perfect binary tree consisting of nodes numbered from 1
to n
. The root of the tree is node 1
and each node i
in the tree has two children where the left child is the node 2 * i
and the right child is 2 * i + 1
.
Each node in the tree also has a cost represented by a given 0-indexed integer array cost
of size n
where cost[i]
is the cost of node i + 1
. You are allowed to increment the cost of any node by 1
any number of times.
Return the minimum number of increments you need to make the cost of paths from the root to each leaf node equal.
\n\nNote:
\n\n\n
Example 1:
\n\nInput: n = 7, cost = [1,5,2,2,3,3,1]\nOutput: 6\nExplanation: We can do the following increments:\n- Increase the cost of node 4 one time.\n- Increase the cost of node 3 three times.\n- Increase the cost of node 7 two times.\nEach path from the root to a leaf will have a total cost of 9.\nThe total increments we did is 1 + 3 + 2 = 6.\nIt can be shown that this is the minimum answer we can achieve.\n\n\n
Example 2:
\n\nInput: n = 3, cost = [5,3,3]\nOutput: 0\nExplanation: The two paths already have equal total costs, so no increments are needed.\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
n + 1
is a power of 2
cost.length == n
1 <= cost[i] <= 104
Given an array arr
and a chunk size size
, return a chunked array.
A chunked array contains the original elements in arr
, but consists of subarrays each of length size
. The length of the last subarray may be less than size
if arr.length
is not evenly divisible by size
.
You may assume the array is the output of JSON.parse
. In other words, it is valid JSON.
Please solve it without using lodash's _.chunk
function.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5], size = 1\nOutput: [[1],[2],[3],[4],[5]]\nExplanation: The arr has been split into subarrays each with 1 element.\n\n\n
Example 2:
\n\n\nInput: arr = [1,9,6,3,2], size = 3\nOutput: [[1,9,6],[3,2]]\nExplanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.\n\n\n
Example 3:
\n\n\nInput: arr = [8,5,3,2,6], size = 6\nOutput: [[8,5,3,2,6]]\nExplanation: Size is greater than arr.length thus all elements are in the first subarray.\n\n\n
Example 4:
\n\n\nInput: arr = [], size = 1\nOutput: []\nExplanation: There are no elements to be chunked so an empty array is returned.\n\n
\n
Constraints:
\n\narr
is a valid JSON array2 <= JSON.stringify(arr).length <= 105
1 <= size <= arr.length + 1
Given an array arr
and a chunk size size
, return a chunked array.
A chunked array contains the original elements in arr
, but consists of subarrays each of length size
. The length of the last subarray may be less than size
if arr.length
is not evenly divisible by size
.
Please solve it without using lodash's _.chunk
function.
\n
Example 1:
\n\n\nInput: arr = [1,2,3,4,5], size = 1\nOutput: [[1],[2],[3],[4],[5]]\nExplanation: The arr has been split into subarrays each with 1 element.\n\n\n
Example 2:
\n\n\nInput: arr = [1,9,6,3,2], size = 3\nOutput: [[1,9,6],[3,2]]\nExplanation: The arr has been split into subarrays with 3 elements. However, only two elements are left for the 2nd subarray.\n\n\n
Example 3:
\n\n\nInput: arr = [8,5,3,2,6], size = 6\nOutput: [[8,5,3,2,6]]\nExplanation: Size is greater than arr.length thus all elements are in the first subarray.\n\n\n
Example 4:
\n\n\nInput: arr = [], size = 1\nOutput: []\nExplanation: There are no elements to be chunked so an empty array is returned.\n\n
\n
Constraints:
\n\n2 <= arr.length <= 105
1 <= size <= arr.length + 1
You are given a 0-indexed array of strings details
. Each element of details
provides information about a given passenger compressed into a string of length 15
. The system is such that:
Return the number of passengers who are strictly more than 60 years old.
\n\n\n
Example 1:
\n\n\nInput: details = ["7868190130M7522","5303914400F9211","9273338290F4010"]\nOutput: 2\nExplanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old.\n\n\n
Example 2:
\n\n\nInput: details = ["1313579440F2036","2921522980M5644"]\nOutput: 0\nExplanation: None of the passengers are older than 60.\n\n\n
\n
Constraints:
\n\n1 <= details.length <= 100
details[i].length == 15
details[i] consists of digits from '0' to '9'.
details[i][10] is either 'M' or 'F' or 'O'.
You are given a 0-indexed 2D integer array nums
. Initially, your score is 0
. Perform the following operations until the matrix becomes empty:
Return the final score.
\n\n
Example 1:
\n\n\nInput: nums = [[7,2,1],[6,4,2],[6,5,3],[3,2,1]]\nOutput: 15\nExplanation: In the first operation, we remove 7, 6, 6, and 3. We then add 7 to our score. Next, we remove 2, 4, 5, and 2. We add 5 to our score. Lastly, we remove 1, 2, 3, and 1. We add 3 to our score. Thus, our final score is 7 + 5 + 3 = 15.\n\n\n
Example 2:
\n\n\nInput: nums = [[1]]\nOutput: 1\nExplanation: We remove 1 and add it to the answer. We return 1.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 300
1 <= nums[i].length <= 500
0 <= nums[i][j] <= 103
You are given a 0-indexed integer array nums
of length n
and an integer k
. In an operation, you can choose an element and multiply it by 2
.
Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1]
that can be obtained after applying the operation on nums at most k
times.
Note that a | b
denotes the bitwise or between two integers a
and b
.
\n
Example 1:
\n\n\nInput: nums = [12,9], k = 1\nOutput: 30\nExplanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30.\n\n\n
Example 2:
\n\n\nInput: nums = [8,1,2], k = 2\nOutput: 35\nExplanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 15
You are given a 0-indexed integer array nums
representing the strength of some heroes. The power of a group of heroes is defined as follows:
i0
, i1
, ... ,ik
be the indices of the heroes in a group. Then, the power of this group is max(nums[i0], nums[i1], ... ,nums[ik])2 * min(nums[i0], nums[i1], ... ,nums[ik])
.Return the sum of the power of all non-empty groups of heroes possible. Since the sum could be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [2,1,4]\nOutput: 141\nExplanation: \n1st group: [2] has power = 22 * 2 = 8.\n2nd group: [1] has power = 12 * 1 = 1. \n3rd group: [4] has power = 42 * 4 = 64. \n4th group: [2,1] has power = 22 * 1 = 4. \n5th group: [2,4] has power = 42 * 2 = 32. \n6th group: [1,4] has power = 42 * 1 = 16. \n\u200b\u200b\u200b\u200b\u200b\u200b\u200b7th group: [2,1,4] has power = 42\u200b\u200b\u200b\u200b\u200b\u200b\u200b * 1 = 16. \nThe sum of powers of all groups is 8 + 1 + 64 + 4 + 32 + 16 + 16 = 141.\n\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1]\nOutput: 7\nExplanation: A total of 7 groups are possible, and the power of each group will be 1. Therefore, the sum of the powers of all groups is 7.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
There are n
friends that are playing a game. The friends are sitting in a circle and are numbered from 1
to n
in clockwise order. More formally, moving clockwise from the ith
friend brings you to the (i+1)th
friend for 1 <= i < n
, and moving clockwise from the nth
friend brings you to the 1st
friend.
The rules of the game are as follows:
\n\n1st
friend receives the ball.
1st
friend passes it to the friend who is k
steps away from them in the clockwise direction.2 * k
steps away from them in the clockwise direction.3 * k
steps away from them in the clockwise direction, and so on and so forth.In other words, on the ith
turn, the friend holding the ball should pass it to the friend who is i * k
steps away from them in the clockwise direction.
The game is finished when some friend receives the ball for the second time.
\n\nThe losers of the game are friends who did not receive the ball in the entire game.
\n\nGiven the number of friends, n
, and an integer k
, return the array answer, which contains the losers of the game in the ascending order.
\n
Example 1:
\n\n\nInput: n = 5, k = 2\nOutput: [4,5]\nExplanation: The game goes as follows:\n1) Start at 1st friend and pass the ball to the friend who is 2 steps away from them - 3rd friend.\n2) 3rd friend passes the ball to the friend who is 4 steps away from them - 2nd friend.\n3) 2nd friend passes the ball to the friend who is 6 steps away from them - 3rd friend.\n4) The game ends as 3rd friend receives the ball for the second time.\n\n\n
Example 2:
\n\n\nInput: n = 4, k = 4\nOutput: [2,3,4]\nExplanation: The game goes as follows:\n1) Start at the 1st friend and pass the ball to the friend who is 4 steps away from them - 1st friend.\n2) The game ends as 1st friend receives the ball for the second time.\n\n\n
\n
Constraints:
\n\n1 <= k <= n <= 50
A 0-indexed array derived
with length n
is derived by computing the bitwise XOR (⊕) of adjacent values in a binary array original
of length n
.
Specifically, for each index i
in the range [0, n - 1]
:
i = n - 1
, then derived[i] = original[i] ⊕ original[0]
.derived[i] = original[i] ⊕ original[i + 1]
.Given an array derived
, your task is to determine whether there exists a valid binary array original
that could have formed derived
.
Return true if such an array exists or false otherwise.
\n\n\n
Example 1:
\n\n\nInput: derived = [1,1,0]\nOutput: true\nExplanation: A valid original array that gives derived is [0,1,0].\nderived[0] = original[0] ⊕ original[1] = 0 ⊕ 1 = 1 \nderived[1] = original[1] ⊕ original[2] = 1 ⊕ 0 = 1\nderived[2] = original[2] ⊕ original[0] = 0 ⊕ 0 = 0\n\n\n
Example 2:
\n\n\nInput: derived = [1,1]\nOutput: true\nExplanation: A valid original array that gives derived is [0,1].\nderived[0] = original[0] ⊕ original[1] = 1\nderived[1] = original[1] ⊕ original[0] = 1\n\n\n
Example 3:
\n\n\nInput: derived = [1,0]\nOutput: false\nExplanation: There is no valid original array that gives derived.\n\n\n
\n
Constraints:
\n\nn == derived.length
1 <= n <= 105
derived
are either 0's or 1'sYou are given a 0-indexed m x n
matrix grid
consisting of positive integers.
You can start at any cell in the first column of the matrix, and traverse the grid in the following way:
\n\n(row, col)
, you can move to any of the cells: (row - 1, col + 1)
, (row, col + 1)
and (row + 1, col + 1)
such that the value of the cell you move to, should be strictly bigger than the value of the current cell.Return the maximum number of moves that you can perform.
\n\n\n
Example 1:
\n\nInput: grid = [[2,4,3,5],[5,4,9,3],[3,4,2,11],[10,9,13,15]]\nOutput: 3\nExplanation: We can start at the cell (0, 0) and make the following moves:\n- (0, 0) -> (0, 1).\n- (0, 1) -> (1, 2).\n- (1, 2) -> (2, 3).\nIt can be shown that it is the maximum number of moves that can be made.\n\n
Example 2:
\n\n\n\n\n\nInput: grid = [[3,2,4],[2,1,9],[1,1,7]]\nOutput: 0\nExplanation: Starting from any cell in the first column we cannot perform any moves.\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
1 <= grid[i][j] <= 106
You are given an integer n
. There is an undirected graph with n
vertices, numbered from 0
to n - 1
. You are given a 2D integer array edges
where edges[i] = [ai, bi]
denotes that there exists an undirected edge connecting vertices ai
and bi
.
Return the number of complete connected components of the graph.
\n\nA connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.
\n\nA connected component is said to be complete if there exists an edge between every pair of its vertices.
\n\n\n
Example 1:
\n\n\nInput: n = 6, edges = [[0,1],[0,2],[1,2],[3,4]]\nOutput: 3\nExplanation: From the picture above, one can see that all of the components of this graph are complete.\n\n\n
Example 2:
\n\n\nInput: n = 6, edges = [[0,1],[0,2],[1,2],[3,4],[3,5]]\nOutput: 1\nExplanation: The component containing vertices 0, 1, and 2 is complete since there is an edge between every pair of two vertices. On the other hand, the component containing vertices 3, 4, and 5 is not complete since there is no edge between vertices 4 and 5. Thus, the number of complete components in this graph is 1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 50
0 <= edges.length <= n * (n - 1) / 2
edges[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
Enhance all functions to have the callPolyfill
method. The method accepts an object obj
as its first parameter and any number of additional arguments. The obj
becomes the this
context for the function. The additional arguments are passed to the function (that the callPolyfill
method belongs on).
For example if you had the function:
\n\n\nfunction tax(price, taxRate) {\n const totalCost = price * (1 + taxRate);\n console.log(`The cost of ${this.item} is ${totalCost}`);\n}\n\n\n
Calling this function like tax(10, 0.1)
will log "The cost of undefined is 11"
. This is because the this
context was not defined.
However, calling the function like tax.callPolyfill({item: "salad"}, 10, 0.1)
will log "The cost of salad is 11"
. The this
context was appropriately set, and the function logged an appropriate output.
Please solve this without using the built-in Function.call
method.
\n
Example 1:
\n\n\nInput:\nfn = function add(b) {\n return this.a + b;\n}\nargs = [{"a": 5}, 7]\nOutput: 12\nExplanation:\nfn.callPolyfill({"a": 5}, 7); // 12\ncallPolyfill sets the "this" context to {"a": 5}. 7 is passed as an argument.\n\n\n
Example 2:
\n\n\nInput: \nfn = function tax(price, taxRate) { \n return `The cost of the ${this.item} is ${price * taxRate}`; \n}\nargs = [{"item": "burger"}, 10, 1.1]\nOutput: "The cost of the burger is 11"\nExplanation: callPolyfill sets the "this" context to {"item": "burger"}. 10 and 1.1 are passed as additional arguments.\n\n\n
\n
Constraints:
\n\ntypeof args[0] == 'object' and args[0] != null
1 <= args.length <= 100
2 <= JSON.stringify(args[0]).length <= 105
Design an EventEmitter
class. This interface is similar (but with some differences) to the one found in Node.js or the Event Target interface of the DOM. The EventEmitter
should allow for subscribing to events and emitting them.
Your EventEmitter
class should have the following two methods:
subscribe
are referentially identical.subscribe
method should also return an object with an unsubscribe
method that enables the user to unsubscribe. When it is called, the callback should be removed from the list of subscriptions and undefined
should be returned.\n
Example 1:
\n\n\nInput: \nactions = ["EventEmitter", "emit", "subscribe", "subscribe", "emit"], \nvalues = [[], ["firstEvent"], ["firstEvent", "function cb1() { return 5; }"], ["firstEvent", "function cb1() { return 6; }"], ["firstEvent"]]\nOutput: [[],["emitted",[]],["subscribed"],["subscribed"],["emitted",[5,6]]]\nExplanation: \nconst emitter = new EventEmitter();\nemitter.emit("firstEvent"); // [], no callback are subscribed yet\nemitter.subscribe("firstEvent", function cb1() { return 5; });\nemitter.subscribe("firstEvent", function cb2() { return 6; });\nemitter.emit("firstEvent"); // [5, 6], returns the output of cb1 and cb2\n\n\n
Example 2:
\n\n\nInput: \nactions = ["EventEmitter", "subscribe", "emit", "emit"], \nvalues = [[], ["firstEvent", "function cb1(...args) { return args.join(','); }"], ["firstEvent", [1,2,3]], ["firstEvent", [3,4,6]]]\nOutput: [[],["subscribed"],["emitted",["1,2,3"]],["emitted",["3,4,6"]]]\nExplanation: Note that the emit method should be able to accept an OPTIONAL array of arguments.\n\nconst emitter = new EventEmitter();\nemitter.subscribe("firstEvent, function cb1(...args) { return args.join(','); });\nemitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]\nemitter.emit("firstEvent", [3, 4, 6]); // ["3,4,6"]\n\n\n
Example 3:
\n\n\nInput: \nactions = ["EventEmitter", "subscribe", "emit", "unsubscribe", "emit"], \nvalues = [[], ["firstEvent", "(...args) => args.join(',')"], ["firstEvent", [1,2,3]], [0], ["firstEvent", [4,5,6]]]\nOutput: [[],["subscribed"],["emitted",["1,2,3"]],["unsubscribed",0],["emitted",[]]]\nExplanation:\nconst emitter = new EventEmitter();\nconst sub = emitter.subscribe("firstEvent", (...args) => args.join(','));\nemitter.emit("firstEvent", [1, 2, 3]); // ["1,2,3"]\nsub.unsubscribe(); // undefined\nemitter.emit("firstEvent", [4, 5, 6]); // [], there are no subscriptions\n\n\n
Example 4:
\n\n\nInput: \nactions = ["EventEmitter", "subscribe", "subscribe", "unsubscribe", "emit"], \nvalues = [[], ["firstEvent", "x => x + 1"], ["firstEvent", "x => x + 2"], [0], ["firstEvent", [5]]]\nOutput: [[],["subscribed"],["subscribed"],["unsubscribed",0],["emitted",[7]]]\nExplanation:\nconst emitter = new EventEmitter();\nconst sub1 = emitter.subscribe("firstEvent", x => x + 1);\nconst sub2 = emitter.subscribe("firstEvent", x => x + 2);\nsub1.unsubscribe(); // undefined\nemitter.emit("firstEvent", [5]); // [7]\n\n
\n
Constraints:
\n\n1 <= actions.length <= 10
values.length === actions.length
EventEmitter
, emit
, subscribe
, and unsubscribe
.EventEmitter
action doesn't take any arguments.emit
action takes between either 1 or 2 arguments. The first argument is the name of the event we want to emit, and the 2nd argument is passed to the callback functions.subscribe
action takes 2 arguments, where the first one is the event name and the second is the callback function.unsubscribe
action takes one argument, which is the 0-indexed order of the subscription made before.Create a class ArrayWrapper
that accepts an array of integers in its constructor. This class should have two features:
+
operator, the resulting value is the sum of all the elements in both arrays.String()
function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3]
.\n
Example 1:
\n\n\nInput: nums = [[1,2],[3,4]], operation = "Add"\nOutput: 10\nExplanation:\nconst obj1 = new ArrayWrapper([1,2]);\nconst obj2 = new ArrayWrapper([3,4]);\nobj1 + obj2; // 10\n\n\n
Example 2:
\n\n\nInput: nums = [[23,98,42,70]], operation = "String"\nOutput: "[23,98,42,70]"\nExplanation:\nconst obj = new ArrayWrapper([23,98,42,70]);\nString(obj); // "[23,98,42,70]"\n\n\n
Example 3:
\n\n\nInput: nums = [[],[]], operation = "Add"\nOutput: 0\nExplanation:\nconst obj1 = new ArrayWrapper([]);\nconst obj2 = new ArrayWrapper([]);\nobj1 + obj2; // 0\n\n\n
\n
Constraints:
\n\n0 <= nums.length <= 1000
0 <= nums[i] <= 1000
Note: nums is the array passed to the constructor
You are given a string s
consisting only of uppercase English letters.
You can apply some operations to this string where, in one operation, you can remove any occurrence of one of the substrings "AB"
or "CD"
from s
.
Return the minimum possible length of the resulting string that you can obtain.
\n\nNote that the string concatenates after removing the substring and could produce new "AB"
or "CD"
substrings.
\n
Example 1:
\n\n\nInput: s = "ABFCACDB"\nOutput: 2\nExplanation: We can do the following operations:\n- Remove the substring "ABFCACDB", so s = "FCACDB".\n- Remove the substring "FCACDB", so s = "FCAB".\n- Remove the substring "FCAB", so s = "FC".\nSo the resulting length of the string is 2.\nIt can be shown that it is the minimum length that we can obtain.\n\n
Example 2:
\n\n\nInput: s = "ACBBD"\nOutput: 5\nExplanation: We cannot do any operations on the string so the length remains the same.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of uppercase English letters.You are given a string s
consisting of lowercase English letters, and you are allowed to perform operations on it. In one operation, you can replace a character in s
with another lowercase English letter.
Your task is to make s
a palindrome with the minimum number of operations possible. If there are multiple palindromes that can be made using the minimum number of operations, make the lexicographically smallest one.
A string a
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, string a
has a letter that appears earlier in the alphabet than the corresponding letter in b
.
Return the resulting palindrome string.
\n\n\n
Example 1:
\n\n\nInput: s = "egcfe"\nOutput: "efcfe"\nExplanation: The minimum number of operations to make "egcfe" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "efcfe", by changing 'g'.\n\n\n
Example 2:
\n\n\nInput: s = "abcd"\nOutput: "abba"\nExplanation: The minimum number of operations to make "abcd" a palindrome is 2, and the lexicographically smallest palindrome string we can get by modifying two characters is "abba".\n\n\n
Example 3:
\n\n\nInput: s = "seven"\nOutput: "neven"\nExplanation: The minimum number of operations to make "seven" a palindrome is 1, and the lexicographically smallest palindrome string we can get by modifying one character is "neven".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists of only lowercase English letters.Given a positive integer n
, return the punishment number of n
.
The punishment number of n
is defined as the sum of the squares of all integers i
such that:
1 <= i <= n
i * i
can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i
.\n
Example 1:
\n\n\nInput: n = 10\nOutput: 182\nExplanation: There are exactly 3 integers i that satisfy the conditions in the statement:\n- 1 since 1 * 1 = 1\n- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1.\n- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0.\nHence, the punishment number of 10 is 1 + 81 + 100 = 182\n\n\n
Example 2:
\n\n\nInput: n = 37\nOutput: 1478\nExplanation: There are exactly 4 integers i that satisfy the conditions in the statement:\n- 1 since 1 * 1 = 1. \n- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. \n- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. \n- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.\nHence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
Given a positive integer n
, return the punishment number of n
.
The punishment number of n
is defined as the sum of the squares of all integers i
such that:
1 <= i <= n
i * i
can be partitioned into contiguous substrings such that the sum of the integer values of these substrings equals i
.\n
Example 1:
\n\n\nInput: n = 10\nOutput: 182\nExplanation: There are exactly 3 integers i in the range [1, 10] that satisfy the conditions in the statement:\n- 1 since 1 * 1 = 1\n- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 and 1 with a sum equal to 8 + 1 == 9.\n- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 and 0 with a sum equal to 10 + 0 == 10.\nHence, the punishment number of 10 is 1 + 81 + 100 = 182\n\n\n
Example 2:
\n\n\nInput: n = 37\nOutput: 1478\nExplanation: There are exactly 4 integers i in the range [1, 37] that satisfy the conditions in the statement:\n- 1 since 1 * 1 = 1. \n- 9 since 9 * 9 = 81 and 81 can be partitioned into 8 + 1. \n- 10 since 10 * 10 = 100 and 100 can be partitioned into 10 + 0. \n- 36 since 36 * 36 = 1296 and 1296 can be partitioned into 1 + 29 + 6.\nHence, the punishment number of 37 is 1 + 81 + 100 + 1296 = 1478\n\n\n
\n
Constraints:
\n\n1 <= n <= 1000
You are given an undirected weighted connected graph containing n
nodes labeled from 0
to n - 1
, and an integer array edges
where edges[i] = [ai, bi, wi]
indicates that there is an edge between nodes ai
and bi
with weight wi
.
Some edges have a weight of -1
(wi = -1
), while others have a positive weight (wi > 0
).
Your task is to modify all edges with a weight of -1
by assigning them positive integer values in the range [1, 2 * 109]
so that the shortest distance between the nodes source
and destination
becomes equal to an integer target
. If there are multiple modifications that make the shortest distance between source
and destination
equal to target
, any of them will be considered correct.
Return an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from source
to destination
equal to target
, or an empty array if it's impossible.
Note: You are not allowed to modify the weights of edges with initial positive weights.
\n\n\n
Example 1:
\n\n\nInput: n = 5, edges = [[4,1,-1],[2,0,-1],[0,3,-1],[4,3,-1]], source = 0, destination = 1, target = 5\nOutput: [[4,1,1],[2,0,1],[0,3,3],[4,3,1]]\nExplanation: The graph above shows a possible modification to the edges, making the distance from 0 to 1 equal to 5.\n\n\n
Example 2:
\n\n\nInput: n = 3, edges = [[0,1,-1],[0,2,5]], source = 0, destination = 2, target = 6\nOutput: []\nExplanation: The graph above contains the initial edges. It is not possible to make the distance from 0 to 2 equal to 6 by modifying the edge with weight -1. So, an empty array is returned.\n\n\n
Example 3:
\n\n\nInput: n = 4, edges = [[1,0,4],[1,2,3],[2,3,5],[0,3,-1]], source = 0, destination = 2, target = 6\nOutput: [[1,0,4],[1,2,3],[2,3,5],[0,3,1]]\nExplanation: The graph above shows a modified graph having the shortest distance from 0 to 2 as 6.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
1 <= edges.length <= n * (n - 1) / 2
edges[i].length == 3
0 <= ai, bi < n
wi = -1
or 1 <= wi <= 107
ai != bi
0 <= source, destination < n
source != destination
1 <= target <= 109
argumentsLength
that returns the count of arguments passed to it.\n\n
Example 1:
\n\n\nInput: args = [5]\nOutput: 1\nExplanation:\nargumentsLength(5); // 1\n\nOne value was passed to the function so it should return 1.\n\n\n
Example 2:
\n\n\nInput: args = [{}, null, "3"]\nOutput: 3\nExplanation: \nargumentsLength({}, null, "3"); // 3\n\nThree values were passed to the function so it should return 3.\n\n\n
\n
Constraints:
\n\nargs
is a valid JSON array0 <= args.length <= 100
Write a function expect
that helps developers test their code. It should take in any value val
and return an object with the following two functions.
toBe(val)
accepts another value and returns true
if the two values ===
each other. If they are not equal, it should throw an error "Not Equal"
.notToBe(val)
accepts another value and returns true
if the two values !==
each other. If they are equal, it should throw an error "Equal"
.\n
Example 1:
\n\n\nInput: func = () => expect(5).toBe(5)\nOutput: {"value": true}\nExplanation: 5 === 5 so this expression returns true.\n\n\n
Example 2:
\n\n\nInput: func = () => expect(5).toBe(null)\nOutput: {"error": "Not Equal"}\nExplanation: 5 !== null so this expression throw the error "Not Equal".\n\n\n
Example 3:
\n\n\nInput: func = () => expect(5).notToBe(null)\nOutput: {"value": true}\nExplanation: 5 !== null so this expression returns true.\n\n", - "likes": 771, - "dislikes": 185, - "stats": "{\"totalAccepted\": \"255K\", \"totalSubmission\": \"406.7K\", \"totalAcceptedRaw\": 254998, \"totalSubmissionRaw\": 406703, \"acRate\": \"62.7%\"}", + "likes": 826, + "dislikes": 200, + "stats": "{\"totalAccepted\": \"293.8K\", \"totalSubmission\": \"466.7K\", \"totalAcceptedRaw\": 293799, \"totalSubmissionRaw\": 466661, \"acRate\": \"63.0%\"}", "similarQuestions": "[]", "categoryTitle": "JavaScript", "hints": [], @@ -102228,9 +102473,9 @@ "questionFrontendId": "2705", "title": "Compact Object", "content": "
Given an object or array obj
, return a compact object.
A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value)
returns false
.
You may assume the obj
is the output of JSON.parse
. In other words, it is valid JSON.
\n
Example 1:
\n\n\nInput: obj = [null, 0, false, 1]\nOutput: [1]\nExplanation: All falsy values have been removed from the array.\n\n\n
Example 2:
\n\n\nInput: obj = {"a": null, "b": [false, 1]}\nOutput: {"b": [1]}\nExplanation: obj["a"] and obj["b"][0] had falsy values and were removed.\n\n
Example 3:
\n\n\nInput: obj = [null, 0, 5, [0], [false, 16]]\nOutput: [5, [], [16]]\nExplanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.\n\n\n
\n
Constraints:
\n\nobj
is a valid JSON object2 <= JSON.stringify(obj).length <= 106
You are given an integer array prices
representing the prices of various chocolates in a store. You are also given a single integer money
, which represents your initial amount of money.
You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.
\n\nReturn the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money
. Note that the leftover must be non-negative.
\n
Example 1:
\n\n\nInput: prices = [1,2,2], money = 3\nOutput: 0\nExplanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.\n\n\n
Example 2:
\n\n\nInput: prices = [3,2,3], money = 3\nOutput: 3\nExplanation: You cannot buy 2 chocolates without going in debt, so we return 3.\n\n\n
\n
Constraints:
\n\n2 <= prices.length <= 50
1 <= prices[i] <= 100
1 <= money <= 100
You are given a 0-indexed string s
and a dictionary of words dictionary
. You have to break s
into one or more non-overlapping substrings such that each substring is present in dictionary
. There may be some extra characters in s
which are not present in any of the substrings.
Return the minimum number of extra characters left over if you break up s
optimally.
\n
Example 1:
\n\n\nInput: s = "leetscode", dictionary = ["leet","code","leetcode"]\nOutput: 1\nExplanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.\n\n\n\n
Example 2:
\n\n\nInput: s = "sayhelloworld", dictionary = ["hello","world"]\nOutput: 3\nExplanation: We can break s in two substrings: "hello" from index 3 to 7 and "world" from index 8 to 12. The characters at indices 0, 1, 2 are not used in any substring and thus are considered as extra characters. Hence, we return 3.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 50
1 <= dictionary.length <= 50
1 <= dictionary[i].length <= 50
dictionary[i]
and s
consists of only lowercase English lettersdictionary
contains distinct wordsYou are given a 0-indexed integer array nums
representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength, where the strength of a group of students of indices i0
, i1
, i2
, ... , ik
is defined as nums[i0] * nums[i1] * nums[i2] * ... * nums[ik\u200b]
.
Return the maximum strength of a group the teacher can create.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,-1,-5,2,5,-9]\nOutput: 1350\nExplanation: One way to form a group of maximal strength is to group the students at indices [0,2,3,4,5]. Their strength is 3 * (-5) * 2 * 5 * (-9) = 1350, which we can show is optimal.\n\n\n
Example 2:
\n\n\nInput: nums = [-4,-5,-4]\nOutput: 20\nExplanation: Group the students at indices [0, 1] . Then, we’ll have a resulting strength of 20. We cannot achieve greater strength.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 13
-9 <= nums[i] <= 9
You are given a 0-indexed integer array nums
, and you are allowed to traverse between its indices. You can traverse between index i
and index j
, i != j
, if and only if gcd(nums[i], nums[j]) > 1
, where gcd
is the greatest common divisor.
Your task is to determine if for every pair of indices i
and j
in nums, where i < j
, there exists a sequence of traversals that can take us from i
to j
.
Return true
if it is possible to traverse between all such pairs of indices, or false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [2,3,6]\nOutput: true\nExplanation: In this example, there are 3 possible pairs of indices: (0, 1), (0, 2), and (1, 2).\nTo go from index 0 to index 1, we can use the sequence of traversals 0 -> 2 -> 1, where we move from index 0 to index 2 because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1, and then move from index 2 to index 1 because gcd(nums[2], nums[1]) = gcd(6, 3) = 3 > 1.\nTo go from index 0 to index 2, we can just go directly because gcd(nums[0], nums[2]) = gcd(2, 6) = 2 > 1. Likewise, to go from index 1 to index 2, we can just go directly because gcd(nums[1], nums[2]) = gcd(3, 6) = 3 > 1.\n\n\n
Example 2:
\n\n\nInput: nums = [3,9,5]\nOutput: false\nExplanation: No sequence of traversals can take us from index 0 to index 2 in this example. So, we return false.\n\n\n
Example 3:
\n\n\nInput: nums = [4,3,12,8]\nOutput: true\nExplanation: There are 6 possible pairs of indices to traverse between: (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), and (2, 3). A valid sequence of traversals exists for each pair, so we return true.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
Given a positive integer num
represented as a string, return the integer num
without trailing zeros as a string.
\n
Example 1:
\n\n\nInput: num = "51230100"\nOutput: "512301"\nExplanation: Integer "51230100" has 2 trailing zeros, we remove them and return integer "512301".\n\n\n
Example 2:
\n\n\nInput: num = "123"\nOutput: "123"\nExplanation: Integer "123" has no trailing zeros, we return integer "123".\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 1000
num
consists of only digits.num
doesn't have any leading zeros.Given a 2D grid
of size m x n
, you should find the matrix answer
of size m x n
.
The cell answer[r][c]
is calculated by looking at the diagonal values of the cell grid[r][c]
:
leftAbove[r][c]
be the number of distinct values on the diagonal to the left and above the cell grid[r][c]
not including the cell grid[r][c]
itself.rightBelow[r][c]
be the number of distinct values on the diagonal to the right and below the cell grid[r][c]
, not including the cell grid[r][c]
itself.answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|
.A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until the end of the matrix is reached.
\n\n(2, 3)
colored gray:\n\n\tReturn the matrix answer
.
\n
Example 1:
\n\nInput: grid = [[1,2,3],[3,1,5],[3,2,1]]
\n\nOutput: Output: [[1,1,0],[1,0,1],[0,1,1]]
\n\nExplanation:
\n\nTo calculate the answer
cells:
answer | \n\t\t\tleft-above elements | \n\t\t\tleftAbove | \n\t\t\tright-below elements | \n\t\t\trightBelow | \n\t\t\t|leftAbove - rightBelow| | \n\t\t
---|---|---|---|---|---|
[0][0] | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t[grid[1][1], grid[2][2]] | \n\t\t\t|{1, 1}| = 1 | \n\t\t\t1 | \n\t\t
[0][1] | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t[grid[1][2]] | \n\t\t\t|{5}| = 1 | \n\t\t\t1 | \n\t\t
[0][2] | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
[1][0] | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t[grid[2][1]] | \n\t\t\t|{2}| = 1 | \n\t\t\t1 | \n\t\t
[1][1] | \n\t\t\t[grid[0][0]] | \n\t\t\t|{1}| = 1 | \n\t\t\t[grid[2][2]] | \n\t\t\t|{1}| = 1 | \n\t\t\t0 | \n\t\t
[1][2] | \n\t\t\t[grid[0][1]] | \n\t\t\t|{2}| = 1 | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
[2][0] | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
[2][1] | \n\t\t\t[grid[1][0]] | \n\t\t\t|{3}| = 1 | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
[2][2] | \n\t\t\t[grid[0][0], grid[1][1]] | \n\t\t\t|{1, 1}| = 1 | \n\t\t\t[] | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
Example 2:
\n\nInput: grid = [[1]]
\n\nOutput: Output: [[0]]
\n\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n, grid[i][j] <= 50
You are given a 0-indexed binary string s
of length n
on which you can apply two types of operations:
i
and invert all characters from index 0
to index i
(both inclusive), with a cost of i + 1
i
and invert all characters from index i
to index n - 1
(both inclusive), with a cost of n - i
Return the minimum cost to make all characters of the string equal.
\n\nInvert a character means if its value is '0' it becomes '1' and vice-versa.
\n\n\n
Example 1:
\n\n\nInput: s = "0011"\nOutput: 2\nExplanation: Apply the second operation with\n\ni = 2
to obtains = "0000" for a cost of 2
. It can be shown that 2 is the minimum cost to make all characters equal.\n
Example 2:
\n\n\nInput: s = "010101"\nOutput: 9\nExplanation: Apply the first operation with i = 2 to obtain s = "101101" for a cost of 3.\nApply the first operation with i = 1 to obtain s = "011101" for a cost of 2. \nApply the first operation with i = 0 to obtain s = "111101" for a cost of 1. \nApply the second operation with i = 4 to obtain s = "111110" for a cost of 2.\nApply the second operation with i = 5 to obtain s = "111111" for a cost of 1. \nThe total cost to make all characters equal is 9. It can be shown that 9 is the minimum cost to make all characters equal.\n\n\n
\n
Constraints:
\n\n1 <= s.length == n <= 105
s[i]
is either '0'
or '1'
Given a 1-indexed m x n
integer matrix mat
, you can select any cell in the matrix as your starting cell.
From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.
\n\nYour task is to find the maximum number of cells that you can visit in the matrix by starting from some cell.
\n\nReturn an integer denoting the maximum number of cells that can be visited.
\n\n\n
Example 1:
\n\n\nInput: mat = [[3,1],[3,4]]\nOutput: 2\nExplanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2. \n\n\n
Example 2:
\n\n\nInput: mat = [[1,1],[1,1]]\nOutput: 1\nExplanation: Since the cells must be strictly increasing, we can only visit one cell in this example. \n\n\n
Example 3:
\n\n\nInput: mat = [[3,1,6],[-9,5,7]]\nOutput: 4\nExplanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4. \n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 105
1 <= m * n <= 105
-105 <= mat[i][j] <= 105
Given a function fn
, an array of arguments args
, and a timeout t
in milliseconds, return a cancel function cancelFn
.
After a delay of cancelTimeMs
, the returned cancel function cancelFn
will be invoked.
\nsetTimeout(cancelFn, cancelTimeMs)\n\n\n
Initially, the execution of the function fn
should be delayed by t
milliseconds.
If, before the delay of t
milliseconds, the function cancelFn
is invoked, it should cancel the delayed execution of fn
. Otherwise, if cancelFn
is not invoked within the specified delay t
, fn
should be executed with the provided args
as arguments.
\n
Example 1:
\n\n\nInput: fn = (x) => x * 5, args = [2], t = 20\nOutput: [{"time": 20, "returned": 10}]\nExplanation: \nconst cancelTimeMs = 50;\nconst cancelFn = cancellable((x) => x * 5, [2], 20);\nsetTimeout(cancelFn, cancelTimeMs);\n\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms.\n\n\n
Example 2:
\n\n\nInput: fn = (x) => x**2, args = [2], t = 100\nOutput: []\nExplanation: \nconst cancelTimeMs = 50;\nconst cancelFn = cancellable((x) => x**2, [2], 100);\nsetTimeout(cancelFn, cancelTimeMs);\n\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened before the execution of fn(2) at 100ms, resulting in fn(2) never being called.\n\n\n
Example 3:
\n\n\nInput: fn = (x1, x2) => x1 * x2, args = [2,4], t = 30\nOutput: [{"time": 30, "returned": 8}]\nExplanation: \nconst cancelTimeMs = 100;\nconst cancelFn = cancellable((x1, x2) => x1 * x2, [2,4], 30);\nsetTimeout(cancelFn, cancelTimeMs);\n\nThe cancellation was scheduled to occur after a delay of cancelTimeMs (100ms), which happened after the execution of fn(2,4) at 30ms.\n\n\n
\n
Constraints:
\n\nfn
is a functionargs
is a valid JSON array1 <= args.length <= 10
20 <= t <= 1000
10 <= cancelTimeMs <= 1000
Given a string s
, you have two types of operation:
i
in the string, and let c
be the character in position i
. Delete the closest occurrence of c
to the left of i
(if exists).i
in the string, and let c
be the character in position i
. Delete the closest occurrence of c
to the right of i
(if exists).Your task is to minimize the length of s
by performing the above operations zero or more times.
Return an integer denoting the length of the minimized string.
\n\n\n
Example 1:
\n\nInput: s = "aaabc"
\n\nOutput: 3
\n\nExplanation:
\n\ni = 1
so c
is 'a', then we remove s[2]
as it is closest 'a' character to the right of s[1]
.s
becomes "aabc" after this.i = 1
so c
is 'a', then we remove s[0]
as it is closest 'a' character to the left of s[1]
.s
becomes "abc" after this.Example 2:
\n\nInput: s = "cbbd"
\n\nOutput: 3
\n\nExplanation:
\n\ni = 2
so c
is 'b', then we remove s[1]
as it is closest 'b' character to the left of s[1]
.s
becomes "cbd" after this.Example 3:
\n\nInput: s = "baadccab"
\n\nOutput: 4
\n\nExplanation:
\n\ni = 6
so c
is 'a', then we remove s[2]
as it is closest 'a' character to the left of s[6]
.s
becomes "badccab" after this.i = 0
so c
is 'b', then we remove s[6]
as it is closest 'b' character to the right of s[0]
.s
becomes "badcca" fter this.i = 3
so c
is 'c', then we remove s[4]
as it is closest 'c' character to the right of s[3]
.s
becomes "badca" after this.i = 4
so c
is 'a', then we remove s[1]
as it is closest 'a' character to the left of s[4]
.s
becomes "bdca" after this.\n
Constraints:
\n\n1 <= s.length <= 100
s
contains only lowercase English lettersYou are given a 0-indexed permutation of n
integers nums
.
A permutation is called semi-ordered if the first number equals 1
and the last number equals n
. You can perform the below operation as many times as you want until you make nums
a semi-ordered permutation:
nums
, then swap them.Return the minimum number of operations to make nums
a semi-ordered permutation.
A permutation is a sequence of integers from 1
to n
of length n
containing each number exactly once.
\n
Example 1:
\n\n\nInput: nums = [2,1,4,3]\nOutput: 2\nExplanation: We can make the permutation semi-ordered using these sequence of operations: \n1 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3].\n2 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4].\nIt can be proved that there is no sequence of less than two operations that make nums a semi-ordered permutation. \n\n\n
Example 2:
\n\n\nInput: nums = [2,4,1,3]\nOutput: 3\nExplanation: We can make the permutation semi-ordered using these sequence of operations:\n1 - swap i = 1 and j = 2. The permutation becomes [2,1,4,3].\n2 - swap i = 0 and j = 1. The permutation becomes [1,2,4,3].\n3 - swap i = 2 and j = 3. The permutation becomes [1,2,3,4].\nIt can be proved that there is no sequence of less than three operations that make nums a semi-ordered permutation.\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,4,2,5]\nOutput: 0\nExplanation: The permutation is already a semi-ordered permutation.\n\n\n
\n
Constraints:
\n\n2 <= nums.length == n <= 50
1 <= nums[i] <= 50
nums is a permutation.
You are given an integer n
and a 0-indexed 2D array queries
where queries[i] = [typei, indexi, vali]
.
Initially, there is a 0-indexed n x n
matrix filled with 0
's. For each query, you must apply one of the following changes:
typei == 0
, set the values in the row with indexi
to vali
, overwriting any previous values.typei == 1
, set the values in the column with indexi
to vali
, overwriting any previous values.Return the sum of integers in the matrix after all queries are applied.
\n\n\n
Example 1:
\n\nInput: n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]]\nOutput: 23\nExplanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23. \n\n\n
Example 2:
\n\nInput: n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]]\nOutput: 17\nExplanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
1 <= queries.length <= 5 * 104
queries[i].length == 3
0 <= typei <= 1
0 <= indexi < n
0 <= vali <= 105
You are given two numeric strings num1
and num2
and two integers max_sum
and min_sum
. We denote an integer x
to be good if:
num1 <= x <= num2
min_sum <= digit_sum(x) <= max_sum
.Return the number of good integers. Since the answer may be large, return it modulo 109 + 7
.
Note that digit_sum(x)
denotes the sum of the digits of x
.
\n
Example 1:
\n\n\nInput: num1 = "1", num2 = "12", min_sum
= 1, max_sum = 8\nOutput: 11\nExplanation: There are 11 integers whose sum of digits lies between 1 and 8 are 1,2,3,4,5,6,7,8,10,11, and 12. Thus, we return 11.\n
\n\nExample 2:
\n\n\nInput: num1 = "1", num2 = "5", min_sum
= 1, max_sum = 5\nOutput: 5\nExplanation: The 5 integers whose sum of digits lies between 1 and 5 are 1,2,3,4, and 5. Thus, we return 5.\n
\n\n\n
Constraints:
\n\n1 <= num1 <= num2 <= 1022
1 <= min_sum <= max_sum <= 400
Given an array of asynchronous functions functions
, return a new promise promise
. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel.
promise
resolves:
functions
were resolved successfully in parallel. The resolved value of promise
should be an array of all the resolved values of promises in the same order as they were in the functions
. The promise
should resolve when all the asynchronous functions in the array have completed execution in parallel.promise
rejects:
functions
were rejected. promise
should also reject with the reason of the first rejection.Please solve it without using the built-in Promise.all
function.
\n
Example 1:
\n\n\nInput: functions = [\n () => new Promise(resolve => setTimeout(() => resolve(5), 200))\n]\nOutput: {"t": 200, "resolved": [5]}\nExplanation: \npromiseAll(functions).then(console.log); // [5]\n\nThe single function was resolved at 200ms with a value of 5.\n\n\n
Example 2:
\n\n\nInput: functions = [\n () => new Promise(resolve => setTimeout(() => resolve(1), 200)), \n () => new Promise((resolve, reject) => setTimeout(() => reject("Error"), 100))\n]\nOutput: {"t": 100, "rejected": "Error"}\nExplanation: Since one of the promises rejected, the returned promise also rejected with the same error at the same time.\n\n\n
Example 3:
\n\n\nInput: functions = [\n () => new Promise(resolve => setTimeout(() => resolve(4), 50)), \n () => new Promise(resolve => setTimeout(() => resolve(10), 150)), \n () => new Promise(resolve => setTimeout(() => resolve(16), 100))\n]\nOutput: {"t": 150, "resolved": [4, 10, 16]}\nExplanation: All the promises resolved with a value. The returned promise resolved when the last promise resolved.\n\n\n
\n
Constraints:
\n\nfunctions
is an array of functions that returns promises1 <= functions.length <= 10
Given two arrays arr1
and arr2
, return a new array joinedArray
. All the objects in each of the two inputs arrays will contain an id
field that has an integer value.
joinedArray
is an array formed by merging arr1
and arr2
based on their id
key. The length of joinedArray
should be the length of unique values of id
. The returned array should be sorted in ascending order based on the id
key.
If a given id
exists in one array but not the other, the single object with that id
should be included in the result array without modification.
If two objects share an id
, their properties should be merged into a single object:
arr2
should override the value from arr1
.\n
Example 1:
\n\n\nInput: \narr1 = [\n {"id": 1, "x": 1},\n {"id": 2, "x": 9}\n], \narr2 = [\n {"id": 3, "x": 5}\n]\nOutput: \n[\n {"id": 1, "x": 1},\n {"id": 2, "x": 9},\n {"id": 3, "x": 5}\n]\nExplanation: There are no duplicate ids so arr1 is simply concatenated with arr2.\n\n\n
Example 2:
\n\n\nInput: \narr1 = [\n {"id": 1, "x": 2, "y": 3},\n {"id": 2, "x": 3, "y": 6}\n], \narr2 = [\n {"id": 2, "x": 10, "y": 20},\n {"id": 3, "x": 0, "y": 0}\n]\nOutput: \n[\n {"id": 1, "x": 2, "y": 3},\n {"id": 2, "x": 10, "y": 20},\n {"id": 3, "x": 0, "y": 0}\n]\nExplanation: The two objects with id=1 and id=3 are included in the result array without modifiction. The two objects with id=2 are merged together. The keys from arr2 override the values in arr1.\n\n\n
Example 3:
\n\n\nInput: \narr1 = [\n {"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}\n]\narr2 = [\n {"id": 1, "b": {"c": 84}, "v": [1, 3]}\n]\nOutput: [\n {"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}\n]\nExplanation: The two objects with id=1 are merged together. For the keys "b" and "v" the values from arr2 are used. Since the key "y" only exists in arr1, that value is taken form arr1.\n\n
\n
Constraints:
\n\narr1
and arr2
are valid JSON arraysarr1
and arr2
has a unique integer id
key2 <= JSON.stringify(arr1).length <= 106
2 <= JSON.stringify(arr2).length <= 106
promise1
and promise2
, return a new promise. promise1
and promise2
will both resolve with a number. The returned promise should resolve with the sum of the two numbers.\n\n
Example 1:
\n\n\nInput: \npromise1 = new Promise(resolve => setTimeout(() => resolve(2), 20)), \npromise2 = new Promise(resolve => setTimeout(() => resolve(5), 60))\nOutput: 7\nExplanation: The two input promises resolve with the values of 2 and 5 respectively. The returned promise should resolve with a value of 2 + 5 = 7. The time the returned promise resolves is not judged for this problem.\n\n\n
Example 2:
\n\n\nInput: \npromise1 = new Promise(resolve => setTimeout(() => resolve(10), 50)), \npromise2 = new Promise(resolve => setTimeout(() => resolve(-12), 30))\nOutput: -2\nExplanation: The two input promises resolve with the values of 10 and -12 respectively. The returned promise should resolve with a value of 10 + -12 = -2.\n\n\n
\n
Constraints:
\n\npromise1
and promise2
are promises that resolve with a numberGiven an array arr
and a function fn
, return a sorted array sortedArr
. You can assume fn
only returns numbers and those numbers determine the sort order of sortedArr
. sortedArr
must be sorted in ascending order by fn
output.
You may assume that fn
will never duplicate numbers for a given array.
\n
Example 1:
\n\n\nInput: arr = [5, 4, 1, 2, 3], fn = (x) => x\nOutput: [1, 2, 3, 4, 5]\nExplanation: fn simply returns the number passed to it so the array is sorted in ascending order.\n\n\n
Example 2:
\n\n\nInput: arr = [{"x": 1}, {"x": 0}, {"x": -1}], fn = (d) => d.x\nOutput: [{"x": -1}, {"x": 0}, {"x": 1}]\nExplanation: fn returns the value for the "x" key. So the array is sorted based on that value.\n\n\n
Example 3:
\n\n\nInput: arr = [[3, 4], [5, 2], [10, 1]], fn = (x) => x[1]\nOutput: [[10, 1], [5, 2], [3, 4]]\nExplanation: arr is sorted in ascending order by number at index=1. \n\n\n
\n
Constraints:
\n\narr
is a valid JSON arrayfn
is a function that returns a number1 <= arr.length <= 5 * 105
Given a function fn
, an array of arguments args
, and an interval time t
, return a cancel function cancelFn
.
After a delay of cancelTimeMs
, the returned cancel function cancelFn
will be invoked.
\nsetTimeout(cancelFn, cancelTimeMs)\n\n\n
The function fn
should be called with args
immediately and then called again every t
milliseconds until cancelFn
is called at cancelTimeMs
ms.
\n
Example 1:
\n\n\nInput: fn = (x) => x * 2, args = [4], t = 35\nOutput: \n[\n {"time": 0, "returned": 8},\n {"time": 35, "returned": 8},\n {"time": 70, "returned": 8},\n {"time": 105, "returned": 8},\n {"time": 140, "returned": 8},\n {"time": 175, "returned": 8}\n]\nExplanation: \nconst cancelTimeMs = 190;\nconst cancelFn = cancellable((x) => x * 2, [4], 35);\nsetTimeout(cancelFn, cancelTimeMs);\n\nEvery 35ms, fn(4) is called. Until t=190ms, then it is cancelled.\n1st fn call is at 0ms. fn(4) returns 8.\n2nd fn call is at 35ms. fn(4) returns 8.\n3rd fn call is at 70ms. fn(4) returns 8.\n4th fn call is at 105ms. fn(4) returns 8.\n5th fn call is at 140ms. fn(4) returns 8.\n6th fn call is at 175ms. fn(4) returns 8.\nCancelled at 190ms\n\n\n
Example 2:
\n\n\nInput: fn = (x1, x2) => (x1 * x2), args = [2, 5], t = 30\nOutput: \n[\n {"time": 0, "returned": 10},\n {"time": 30, "returned": 10},\n {"time": 60, "returned": 10},\n {"time": 90, "returned": 10},\n {"time": 120, "returned": 10},\n {"time": 150, "returned": 10}\n]\nExplanation: \nconst cancelTimeMs = 165; \nconst cancelFn = cancellable((x1, x2) => (x1 * x2), [2, 5], 30) \nsetTimeout(cancelFn, cancelTimeMs)\n\nEvery 30ms, fn(2, 5) is called. Until t=165ms, then it is cancelled.\n1st fn call is at 0ms \n2nd fn call is at 30ms \n3rd fn call is at 60ms \n4th fn call is at 90ms \n5th fn call is at 120ms \n6th fn call is at 150ms\nCancelled at 165ms\n\n\n
Example 3:
\n\n\nInput: fn = (x1, x2, x3) => (x1 + x2 + x3), args = [5, 1, 3], t = 50\nOutput: \n[\n {"time": 0, "returned": 9},\n {"time": 50, "returned": 9},\n {"time": 100, "returned": 9},\n {"time": 150, "returned": 9}\n]\nExplanation: \nconst cancelTimeMs = 180;\nconst cancelFn = cancellable((x1, x2, x3) => (x1 + x2 + x3), [5, 1, 3], 50)\nsetTimeout(cancelFn, cancelTimeMs)\n\nEvery 50ms, fn(5, 1, 3) is called. Until t=180ms, then it is cancelled. \n1st fn call is at 0ms\n2nd fn call is at 50ms\n3rd fn call is at 100ms\n4th fn call is at 150ms\nCancelled at 180ms\n\n\n
\n
Constraints:
\n\nfn
is a functionargs
is a valid JSON array1 <= args.length <= 10
30 <= t <= 100
10 <= cancelTimeMs <= 500
Design a Calculator
class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator
class constructor should accept a number which serves as the initial value of result
.
Your Calculator
class should have the following methods:
add
- This method adds the given number value
to the result
and returns the updated Calculator
.subtract
- This method subtracts the given number value
from the result
and returns the updated Calculator
.multiply
- This method multiplies the result
by the given number value
and returns the updated Calculator
.divide
- This method divides the result
by the given number value
and returns the updated Calculator
. If the passed value is 0
, an error "Division by zero is not allowed"
should be thrown.power
- This method raises the result
to the power of the given number value
and returns the updated Calculator
.getResult
- This method returns the result
.Solutions within 10-5
of the actual result are considered correct.
\n
Example 1:
\n\n\nInput: \nactions = ["Calculator", "add", "subtract", "getResult"], \nvalues = [10, 5, 7]\nOutput: 8\nExplanation: \nnew Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8\n\n\n
Example 2:
\n\n\nInput: \nactions = ["Calculator", "multiply", "power", "getResult"], \nvalues = [2, 5, 2]\nOutput: 100\nExplanation: \nnew Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100\n\n\n
Example 3:
\n\n\nInput: \nactions = ["Calculator", "divide", "getResult"], \nvalues = [20, 0]\nOutput: "Division by zero is not allowed"\nExplanation: \nnew Calculator(20).divide(0).getResult() // 20 / 0 \n\nThe error should be thrown because we cannot divide by zero.\n\n\n
\n
Constraints:
\n\nactions
is a valid JSON array of stringsvalues
is a valid JSON array of numbers2 <= actions.length <= 2 * 104
1 <= values.length <= 2 * 104 - 1
actions[i]
is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"Given an object or an array, return if it is empty.
\n\nYou may assume the object or array is the output of JSON.parse
.
\n
Example 1:
\n\n\nInput: obj = {"x": 5, "y": 42}\nOutput: false\nExplanation: The object has 2 key-value pairs so it is not empty.\n\n\n
Example 2:
\n\n\nInput: obj = {}\nOutput: true\nExplanation: The object doesn't have any key-value pairs so it is empty.\n\n\n
Example 3:
\n\n\nInput: obj = [null, false, 0]\nOutput: false\nExplanation: The array has 3 elements so it is not empty.\n\n\n
\n
Constraints:
\n\nobj
is a valid JSON object or array2 <= JSON.stringify(obj).length <= 105
\nCan you solve it in O(1) time?", - "likes": 194, + "likes": 202, "dislikes": 14, - "stats": "{\"totalAccepted\": \"85.1K\", \"totalSubmission\": \"105K\", \"totalAcceptedRaw\": 85123, \"totalSubmissionRaw\": 104998, \"acRate\": \"81.1%\"}", + "stats": "{\"totalAccepted\": \"98.4K\", \"totalSubmission\": \"120.8K\", \"totalAcceptedRaw\": 98424, \"totalSubmissionRaw\": 120805, \"acRate\": \"81.5%\"}", "similarQuestions": "[]", "categoryTitle": "JavaScript", "hints": [], @@ -103021,9 +103266,9 @@ "questionFrontendId": "2728", "title": "Count Houses in a Circular Street", "content": null, - "likes": 53, + "likes": 57, "dislikes": 12, - "stats": "{\"totalAccepted\": \"2.6K\", \"totalSubmission\": \"3K\", \"totalAcceptedRaw\": 2579, \"totalSubmissionRaw\": 3021, \"acRate\": \"85.4%\"}", + "stats": "{\"totalAccepted\": \"2.8K\", \"totalSubmission\": \"3.3K\", \"totalAcceptedRaw\": 2801, \"totalSubmissionRaw\": 3282, \"acRate\": \"85.3%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -103056,9 +103301,9 @@ "questionFrontendId": "2729", "title": "Check if The Number is Fascinating", "content": "
You are given an integer n
that consists of exactly 3
digits.
We call the number n
fascinating if, after the following modification, the resulting number contains all the digits from 1
to 9
exactly once and does not contain any 0
's:
n
with the numbers 2 * n
and 3 * n
.Return true
if n
is fascinating, or false
otherwise.
Concatenating two numbers means joining them together. For example, the concatenation of 121
and 371
is 121371
.
\n
Example 1:
\n\n\nInput: n = 192\nOutput: true\nExplanation: We concatenate the numbers n = 192 and 2 * n = 384 and 3 * n = 576. The resulting number is 192384576. This number contains all the digits from 1 to 9 exactly once.\n\n\n
Example 2:
\n\n\nInput: n = 100\nOutput: false\nExplanation: We concatenate the numbers n = 100 and 2 * n = 200 and 3 * n = 300. The resulting number is 100200300. This number does not satisfy any of the conditions.\n\n\n
\n
Constraints:
\n\n100 <= n <= 999
You are given a digit string s
that consists of digits from 0 to 9.
A string is called semi-repetitive if there is at most one adjacent pair of the same digit. For example, "0010"
, "002020"
, "0123"
, "2002"
, and "54944"
are semi-repetitive while the following are not: "00101022"
(adjacent same digit pairs are 00 and 22), and "1101234883"
(adjacent same digit pairs are 11 and 88).
Return the length of the longest semi-repetitive substring of s
.
\n
Example 1:
\n\nInput: s = "52233"
\n\nOutput: 4
\n\nExplanation:
\n\nThe longest semi-repetitive substring is "5223". Picking the whole string "52233" has two adjacent same digit pairs 22 and 33, but at most one is allowed.
\nExample 2:
\n\nInput: s = "5494"
\n\nOutput: 4
\n\nExplanation:
\n\ns
is a semi-repetitive string.
Example 3:
\n\nInput: s = "1111111"
\n\nOutput: 2
\n\nExplanation:
\n\nThe longest semi-repetitive substring is "11". Picking the substring "111" has two adjacent same digit pairs, but at most one is allowed.
\n\n
Constraints:
\n\n1 <= s.length <= 50
'0' <= s[i] <= '9'
Some robots are standing on an infinite number line with their initial coordinates given by a 0-indexed integer array nums
and will start moving once given the command to move. The robots will move a unit distance each second.
You are given a string s
denoting the direction in which robots will move on command. 'L'
means the robot will move towards the left side or negative side of the number line, whereas 'R'
means the robot will move towards the right side or positive side of the number line.
If two robots collide, they will start moving in opposite directions.
\n\nReturn the sum of distances between all the pairs of robots d
seconds after the command. Since the sum can be very large, return it modulo 109 + 7
.
Note:
\n\ni
and j
, pair (i,j)
and pair (j,i)
are considered the same pair.\n
Example 1:
\n\n\nInput: nums = [-2,0,2], s = "RLL", d = 3\nOutput: 8\nExplanation: \nAfter 1 second, the positions are [-1,-1,1]. Now, the robot at index 0 will move left, and the robot at index 1 will move right.\nAfter 2 seconds, the positions are [-2,0,0]. Now, the robot at index 1 will move left, and the robot at index 2 will move right.\nAfter 3 seconds, the positions are [-3,-1,1].\nThe distance between the robot at index 0 and 1 is abs(-3 - (-1)) = 2.\nThe distance between the robot at index 0 and 2 is abs(-3 - 1) = 4.\nThe distance between the robot at index 1 and 2 is abs(-1 - 1) = 2.\nThe sum of the pairs of all distances = 2 + 4 + 2 = 8.\n\n\n
Example 2:
\n\n\nInput: nums = [1,0], s = "RL", d = 2\nOutput: 5\nExplanation: \nAfter 1 second, the positions are [2,-1].\nAfter 2 seconds, the positions are [3,-2].\nThe distance between the two robots is abs(-2 - 3) = 5.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
-2 * 109 <= nums[i] <= 2 * 109
0 <= d <= 109
nums.length == s.length
s
consists of 'L' and 'R' onlynums[i]
will be unique.You are given a 0-indexed m x n
binary matrix grid
.
Let us call a non-empty subset of rows good if the sum of each column of the subset is at most half of the length of the subset.
\n\nMore formally, if the length of the chosen subset of rows is k
, then the sum of each column should be at most floor(k / 2)
.
Return an integer array that contains row indices of a good subset sorted in ascending order.
\n\nIf there are multiple good subsets, you can return any of them. If there are no good subsets, return an empty array.
\n\nA subset of rows of the matrix grid
is any matrix that can be obtained by deleting some (possibly none or all) rows from grid
.
\n
Example 1:
\n\n\nInput: grid = [[0,1,1,0],[0,0,0,1],[1,1,1,1]]\nOutput: [0,1]\nExplanation: We can choose the 0th and 1st rows to create a good subset of rows.\nThe length of the chosen subset is 2.\n- The sum of the 0th column is 0 + 0 = 0, which is at most half of the length of the subset.\n- The sum of the 1st column is 1 + 0 = 1, which is at most half of the length of the subset.\n- The sum of the 2nd column is 1 + 0 = 1, which is at most half of the length of the subset.\n- The sum of the 3rd column is 0 + 1 = 1, which is at most half of the length of the subset.\n\n\n
Example 2:
\n\n\nInput: grid = [[0]]\nOutput: [0]\nExplanation: We can choose the 0th row to create a good subset of rows.\nThe length of the chosen subset is 1.\n- The sum of the 0th column is 0, which is at most half of the length of the subset.\n\n\n
Example 3:
\n\n\nInput: grid = [[1,1,1],[1,1,1]]\nOutput: []\nExplanation: It is impossible to choose any subset of rows to create a good subset.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m <= 104
1 <= n <= 5
grid[i][j]
is either 0
or 1
.Given an integer array nums
containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1
if there is no such number.
Return the selected integer.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,2,1,4]\nOutput: 2\nExplanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2]\nOutput: -1\nExplanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer.\n\n\n
Example 3:
\n\n\nInput: nums = [2,1,3]\nOutput: 2\nExplanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. \n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
nums
are distinctGiven a string s
consisting of lowercase English letters. Perform the following operation:
Return the lexicographically smallest string after performing the operation.
\n\n\n
Example 1:
\n\nInput: s = "cbabc"
\n\nOutput: "baabc"
\n\nExplanation:
\n\nPerform the operation on the substring starting at index 0, and ending at index 1 inclusive.
\nExample 2:
\n\nInput: s = "aa"
\n\nOutput: "az"
\n\nExplanation:
\n\nPerform the operation on the last letter.
\nExample 3:
\n\nInput: s = "acbbc"
\n\nOutput: "abaab"
\n\nExplanation:
\n\nPerform the operation on the substring starting at index 1, and ending at index 4 inclusive.
\nExample 4:
\n\nInput: s = "leetcode"
\n\nOutput: "kddsbncd"
\n\nExplanation:
\n\nPerform the operation on the entire string.
\n\n
Constraints:
\n\n1 <= s.length <= 3 * 105
s
consists of lowercase English lettersYou are given a 0-indexed integer array nums
of size n
representing the cost of collecting different chocolates. The cost of collecting the chocolate at the index i
is nums[i]
. Each chocolate is of a different type, and initially, the chocolate at the index i
is of ith
type.
In one operation, you can do the following with an incurred cost of x
:
ith
type to ((i + 1) mod n)th
type for all chocolates.Return the minimum cost to collect chocolates of all types, given that you can perform as many operations as you would like.
\n\n\n
Example 1:
\n\n\nInput: nums = [20,1,15], x = 5\nOutput: 13\nExplanation: Initially, the chocolate types are [0,1,2]. We will buy the 1st type of chocolate at a cost of 1.\nNow, we will perform the operation at a cost of 5, and the types of chocolates will become [1,2,0]. We will buy the 2nd type of chocolate at a cost of 1.\nNow, we will again perform the operation at a cost of 5, and the chocolate types will become [2,0,1]. We will buy the 0th type of chocolate at a cost of 1. \nThus, the total cost will become (1 + 5 + 1 + 5 + 1) = 13. We can prove that this is optimal.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3], x = 4\nOutput: 6\nExplanation: We will collect all three types of chocolates at their own price without performing any operations. Therefore, the total cost is 1 + 2 + 3 = 6.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 109
1 <= x <= 109
You are given two 0-indexed integer arrays nums1
and nums2
, each of length n
, and a 1-indexed 2D array queries
where queries[i] = [xi, yi]
.
For the ith
query, find the maximum value of nums1[j] + nums2[j]
among all indices j
(0 <= j < n)
, where nums1[j] >= xi
and nums2[j] >= yi
, or -1 if there is no j
satisfying the constraints.
Return an array answer
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\n\nInput: nums1 = [4,3,1,2], nums2 = [2,4,9,5], queries = [[4,1],[1,3],[2,5]]\nOutput: [6,10,7]\nExplanation: \nFor the 1st query\n\nxi = 4
andyi = 1
, we can select indexj = 0
sincenums1[j] >= 4
andnums2[j] >= 1
. The sumnums1[j] + nums2[j]
is 6, and we can show that 6 is the maximum we can obtain.\n\nFor the 2nd queryxi = 1
andyi = 3
, we can select indexj = 2
sincenums1[j] >= 1
andnums2[j] >= 3
. The sumnums1[j] + nums2[j]
is 10, and we can show that 10 is the maximum we can obtain. \n\nFor the 3rd queryxi = 2
andyi = 5
, we can select indexj = 3
sincenums1[j] >= 2
andnums2[j] >= 5
. The sumnums1[j] + nums2[j]
is 7, and we can show that 7 is the maximum we can obtain.\n\nTherefore, we return[6,10,7]
.\n
Example 2:
\n\n\nInput: nums1 = [3,2,5], nums2 = [2,3,4], queries = [[4,4],[3,2],[1,1]]\nOutput: [9,9,9]\nExplanation: For this example, we can use index j = 2
for all the queries since it satisfies the constraints for each query.\n
\n\nExample 3:
\n\n\nInput: nums1 = [2,1], nums2 = [2,3], queries = [[3,3]]\nOutput: [-1]\nExplanation: There is one query in this example with\n\nxi
= 3 andyi
= 3. For every index, j, either nums1[j] <xi
or nums2[j] <yi
. Hence, there is no solution. \n
\n
Constraints:
\n\nnums1.length == nums2.length
n == nums1.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 109
1 <= queries.length <= 105
queries[i].length == 2
xi == queries[i][1]
yi == queries[i][2]
1 <= xi, yi <= 109
A truck has two fuel tanks. You are given two integers, mainTank
representing the fuel present in the main tank in liters and additionalTank
representing the fuel present in the additional tank in liters.
The truck has a mileage of 10
km per liter. Whenever 5
liters of fuel get used up in the main tank, if the additional tank has at least 1
liters of fuel, 1
liters of fuel will be transferred from the additional tank to the main tank.
Return the maximum distance which can be traveled.
\n\nNote: Injection from the additional tank is not continuous. It happens suddenly and immediately for every 5 liters consumed.
\n\n\n
Example 1:
\n\n\nInput: mainTank = 5, additionalTank = 10\nOutput: 60\nExplanation: \nAfter spending 5 litre of fuel, fuel remaining is (5 - 5 + 1) = 1 litre and distance traveled is 50km.\nAfter spending another 1 litre of fuel, no fuel gets injected in the main tank and the main tank becomes empty.\nTotal distance traveled is 60km.\n\n\n
Example 2:
\n\n\nInput: mainTank = 1, additionalTank = 2\nOutput: 10\nExplanation: \nAfter spending 1 litre of fuel, the main tank becomes empty.\nTotal distance traveled is 10km.\n\n\n\n
\n
Constraints:
\n\n1 <= mainTank, additionalTank <= 100
You are given a positive integer array nums
.
Partition nums
into two arrays, nums1
and nums2
, such that:
nums
belongs to either the array nums1
or the array nums2
.The value of the partition is |max(nums1) - min(nums2)|
.
Here, max(nums1)
denotes the maximum element of the array nums1
, and min(nums2)
denotes the minimum element of the array nums2
.
Return the integer denoting the value of such partition.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,2,4]\nOutput: 1\nExplanation: We can partition the array nums into nums1 = [1,2] and nums2 = [3,4].\n- The maximum element of the array nums1 is equal to 2.\n- The minimum element of the array nums2 is equal to 3.\nThe value of the partition is |2 - 3| = 1. \nIt can be proven that 1 is the minimum value out of all partitions.\n\n\n
Example 2:
\n\n\nInput: nums = [100,1,10]\nOutput: 9\nExplanation: We can partition the array nums into nums1 = [10] and nums2 = [100,1].\n- The maximum element of the array nums1 is equal to 10.\n- The minimum element of the array nums2 is equal to 1.\nThe value of the partition is |10 - 1| = 9.\nIt can be proven that 9 is the minimum value out of all partitions.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed integer array nums
containing n
distinct positive integers. A permutation of nums
is called special if:
0 <= i < n - 1
, either nums[i] % nums[i+1] == 0
or nums[i+1] % nums[i] == 0
.Return the total number of special permutations. As the answer could be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [2,3,6]\nOutput: 2\nExplanation: [3,6,2] and [2,6,3] are the two special permutations of nums.\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,3]\nOutput: 2\nExplanation: [3,1,4] and [4,1,3] are the two special permutations of nums.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 14
1 <= nums[i] <= 109
You are given two 0-indexed integer arrays, cost
and time
, of size n
representing the costs and the time taken to paint n
different walls respectively. There are two painters available:
ith
wall in time[i]
units of time and takes cost[i]
units of money.1
unit of time at a cost of 0
. But the free painter can only be used if the paid painter is already occupied.Return the minimum amount of money required to paint the n
walls.
\n
Example 1:
\n\n\nInput: cost = [1,2,3,2], time = [1,2,3,2]\nOutput: 3\nExplanation: The walls at index 0 and 1 will be painted by the paid painter, and it will take 3 units of time; meanwhile, the free painter will paint the walls at index 2 and 3, free of cost in 2 units of time. Thus, the total cost is 1 + 2 = 3.\n\n\n
Example 2:
\n\n\nInput: cost = [2,3,4,2], time = [1,1,1,1]\nOutput: 4\nExplanation: The walls at index 0 and 3 will be painted by the paid painter, and it will take 2 units of time; meanwhile, the free painter will paint the walls at index 1 and 2, free of cost in 2 units of time. Thus, the total cost is 2 + 2 = 4.\n\n\n
\n
Constraints:
\n\n1 <= cost.length <= 500
cost.length == time.length
1 <= cost[i] <= 106
1 <= time[i] <= 500
You are given a 0-indexed array words
consisting of distinct strings.
The string words[i]
can be paired with the string words[j]
if:
words[i]
is equal to the reversed string of words[j]
.0 <= i < j < words.length
.Return the maximum number of pairs that can be formed from the array words
.
Note that each string can belong in at most one pair.
\n\n\n
Example 1:
\n\n\nInput: words = ["cd","ac","dc","ca","zz"]\nOutput: 2\nExplanation: In this example, we can form 2 pair of strings in the following way:\n- We pair the 0th string with the 2nd string, as the reversed string of word[0] is "dc" and is equal to words[2].\n- We pair the 1st string with the 3rd string, as the reversed string of word[1] is "ca" and is equal to words[3].\nIt can be proven that 2 is the maximum number of pairs that can be formed.\n\n
Example 2:
\n\n\nInput: words = ["ab","ba","cc"]\nOutput: 1\nExplanation: In this example, we can form 1 pair of strings in the following way:\n- We pair the 0th string with the 1st string, as the reversed string of words[1] is "ab" and is equal to words[0].\nIt can be proven that 1 is the maximum number of pairs that can be formed.\n\n\n
Example 3:
\n\n\nInput: words = ["aa","ab"]\nOutput: 0\nExplanation: In this example, we are unable to form any pair of strings.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 50
words[i].length == 2
words
consists of distinct strings.words[i]
contains only lowercase English letters.You are given three integers x
, y
, and z
.
You have x
strings equal to "AA"
, y
strings equal to "BB"
, and z
strings equal to "AB"
. You want to choose some (possibly all or none) of these strings and concatenate them in some order to form a new string. This new string must not contain "AAA"
or "BBB"
as a substring.
Return the maximum possible length of the new string.
\n\nA substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: x = 2, y = 5, z = 1\nOutput: 12\nExplanation: We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB". \nThat string has length 12, and we can show that it is impossible to construct a string of longer length.\n\n\n
Example 2:
\n\n\nInput: x = 3, y = 2, z = 2\nOutput: 14\nExplanation: We can concatenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA". \nThat string has length 14, and we can show that it is impossible to construct a string of longer length.\n\n\n
\n
Constraints:
\n\n1 <= x, y, z <= 50
You are given a 0-indexed array words
containing n
strings.
Let's define a join operation join(x, y)
between two strings x
and y
as concatenating them into xy
. However, if the last character of x
is equal to the first character of y
, one of them is deleted.
For example join("ab", "ba") = "aba"
and join("ab", "cde") = "abcde"
.
You are to perform n - 1
join operations. Let str0 = words[0]
. Starting from i = 1
up to i = n - 1
, for the ith
operation, you can do one of the following:
stri = join(stri - 1, words[i])
stri = join(words[i], stri - 1)
Your task is to minimize the length of strn - 1
.
Return an integer denoting the minimum possible length of strn - 1
.
\n
Example 1:
\n\n\nInput: words = ["aa","ab","bc"]\nOutput: 4\nExplanation: In this example, we can perform join operations in the following order to minimize the length of str2: \nstr0 = "aa"\nstr1 = join(str0, "ab") = "aab"\nstr2 = join(str1, "bc") = "aabc" \nIt can be shown that the minimum possible length of str2 is 4.\n\n
Example 2:
\n\n\nInput: words = ["ab","b"]\nOutput: 2\nExplanation: In this example, str0 = "ab", there are two ways to get str1: \njoin(str0, "b") = "ab" or join("b", str0) = "bab". \nThe first string, "ab", has the minimum length. Hence, the answer is 2.\n\n\n
Example 3:
\n\n\nInput: words = ["aaa","c","aba"]\nOutput: 6\nExplanation: In this example, we can perform join operations in the following order to minimize the length of str2: \nstr0 = "aaa"\nstr1 = join(str0, "c") = "aaac"\nstr2 = join("aba", str1) = "abaaac"\nIt can be shown that the minimum possible length of str2 is 6.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 50
words[i]
is an English lowercase letterYou are given an integer n
denoting the total number of servers and a 2D 0-indexed integer array logs
, where logs[i] = [server_id, time]
denotes that the server with id server_id
received a request at time time
.
You are also given an integer x
and a 0-indexed integer array queries
.
Return a 0-indexed integer array arr
of length queries.length
where arr[i]
represents the number of servers that did not receive any requests during the time interval [queries[i] - x, queries[i]]
.
Note that the time intervals are inclusive.
\n\n\n
Example 1:
\n\n\nInput: n = 3, logs = [[1,3],[2,6],[1,5]], x = 5, queries = [10,11]\nOutput: [1,2]\nExplanation: \nFor queries[0]: The servers with ids 1 and 2 get requests in the duration of [5, 10]. Hence, only server 3 gets zero requests.\nFor queries[1]: Only the server with id 2 gets a request in duration of [6,11]. Hence, the servers with ids 1 and 3 are the only servers that do not receive any requests during that time period.\n\n\n\n
Example 2:
\n\n\nInput: n = 3, logs = [[2,4],[2,1],[1,2],[3,1]], x = 2, queries = [3,4]\nOutput: [0,1]\nExplanation: \nFor queries[0]: All servers get at least one request in the duration of [1, 3].\nFor queries[1]: Only server with id 3 gets no request in the duration [2,4].\n\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= logs.length <= 105
1 <= queries.length <= 105
logs[i].length == 2
1 <= logs[i][0] <= n
1 <= logs[i][1] <= 106
1 <= x <= 105
x < queries[i] <= 106
You are given a 0-indexed integer array nums
. A pair of indices i
, j
where 0 <= i < j < nums.length
is called beautiful if the first digit of nums[i]
and the last digit of nums[j]
are coprime.
Return the total number of beautiful pairs in nums
.
Two integers x
and y
are coprime if there is no integer greater than 1 that divides both of them. In other words, x
and y
are coprime if gcd(x, y) == 1
, where gcd(x, y)
is the greatest common divisor of x
and y
.
\n
Example 1:
\n\n\nInput: nums = [2,5,1,4]\nOutput: 5\nExplanation: There are 5 beautiful pairs in nums:\nWhen i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1.\nWhen i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1.\nWhen i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1.\nWhen i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1.\nWhen i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1.\nThus, we return 5.\n\n\n
Example 2:
\n\n\nInput: nums = [11,21,12]\nOutput: 2\nExplanation: There are 2 beautiful pairs:\nWhen i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1.\nWhen i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1.\nThus, we return 2.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 9999
nums[i] % 10 != 0
You are given two integers num1
and num2
.
In one operation, you can choose integer i
in the range [0, 60]
and subtract 2i + num2
from num1
.
Return the integer denoting the minimum number of operations needed to make num1
equal to 0
.
If it is impossible to make num1
equal to 0
, return -1
.
\n
Example 1:
\n\n\nInput: num1 = 3, num2 = -2\nOutput: 3\nExplanation: We can make 3 equal to 0 with the following operations:\n- We choose i = 2 and subtract 22 + (-2) from 3, 3 - (4 + (-2)) = 1.\n- We choose i = 2 and subtract 22 + (-2) from 1, 1 - (4 + (-2)) = -1.\n- We choose i = 0 and subtract 20 + (-2) from -1, (-1) - (1 + (-2)) = 0.\nIt can be proven, that 3 is the minimum number of operations that we need to perform.\n\n\n
Example 2:
\n\n\nInput: num1 = 5, num2 = 7\nOutput: -1\nExplanation: It can be proven, that it is impossible to make 5 equal to 0 with the given operation.\n\n\n
\n
Constraints:
\n\n1 <= num1 <= 109
-109 <= num2 <= 109
You are given a binary array nums
.
A subarray of an array is good if it contains exactly one element with the value 1
.
Return an integer denoting the number of ways to split the array nums
into good subarrays. As the number may be too large, return it modulo 109 + 7
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [0,1,0,0,1]\nOutput: 3\nExplanation: There are 3 ways to split nums into good subarrays:\n- [0,1] [0,0,1]\n- [0,1,0] [0,1]\n- [0,1,0,0] [1]\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,0]\nOutput: 1\nExplanation: There is 1 way to split nums into good subarrays:\n- [0,1,0]\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 1
There are n
1-indexed robots, each having a position on a line, health, and movement direction.
You are given 0-indexed integer arrays positions
, healths
, and a string directions
(directions[i]
is either 'L' for left or 'R' for right). All integers in positions
are unique.
All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide.
\n\nIf two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line.
\n\nYour task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array.
\n\nReturn an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur.
\n\nNote: The positions may be unsorted.
\n\n\n
Example 1:
\n\n\nInput: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR"\nOutput: [2,17,9,15,10]\nExplanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].\n\n\n
Example 2:
\n\n\nInput: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL"\nOutput: [14]\nExplanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14].\n\n\n
Example 3:
\n\n\nInput: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL"\nOutput: []\nExplanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, [].\n\n
\n
Constraints:
\n\n1 <= positions.length == healths.length == directions.length == n <= 105
1 <= positions[i], healths[i] <= 109
directions[i] == 'L'
or directions[i] == 'R'
positions
are distinctYou are given a 0-indexed integer array nums
and an integer threshold
.
Find the length of the longest subarray of nums
starting at index l
and ending at index r
(0 <= l <= r < nums.length)
that satisfies the following conditions:
nums[l] % 2 == 0
i
in the range [l, r - 1]
, nums[i] % 2 != nums[i + 1] % 2
i
in the range [l, r]
, nums[i] <= threshold
Return an integer denoting the length of the longest such subarray.
\n\nNote: A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,2,5,4], threshold = 5\nOutput: 3\nExplanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 3 => [2,5,4]. This subarray satisfies the conditions.\nHence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.\n\n
Example 2:
\n\n\nInput: nums = [1,2], threshold = 2\nOutput: 1\nExplanation: In this example, we can select the subarray that starts at l = 1 and ends at r = 1 => [2]. \nIt satisfies all the conditions and we can show that 1 is the maximum possible achievable length.\n\n\n
Example 3:
\n\n\nInput: nums = [2,3,4,5], threshold = 4\nOutput: 3\nExplanation: In this example, we can select the subarray that starts at l = 0 and ends at r = 2 => [2,3,4]. \nIt satisfies all the conditions.\nHence, the answer is the length of the subarray, 3. We can show that 3 is the maximum possible achievable length.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= threshold <= 100
You are given an integer n
. We say that two integers x
and y
form a prime number pair if:
1 <= x <= y <= n
x + y == n
x
and y
are prime numbersReturn the 2D sorted list of prime number pairs [xi, yi]
. The list should be sorted in increasing order of xi
. If there are no prime number pairs at all, return an empty array.
Note: A prime number is a natural number greater than 1
with only two factors, itself and 1
.
\n
Example 1:
\n\n\nInput: n = 10\nOutput: [[3,7],[5,5]]\nExplanation: In this example, there are two prime pairs that satisfy the criteria. \nThese pairs are [3,7] and [5,5], and we return them in the sorted order as described in the problem statement.\n\n\n
Example 2:
\n\n\nInput: n = 2\nOutput: []\nExplanation: We can show that there is no prime number pair that gives a sum of 2, so we return an empty array. \n\n\n
\n
Constraints:
\n\n1 <= n <= 106
You are given a 0-indexed integer array nums
. A subarray of nums
is called continuous if:
i
, i + 1
, ..., j
be the indices in the subarray. Then, for each pair of indices i <= i1, i2 <= j
, 0 <= |nums[i1] - nums[i2]| <= 2
.Return the total number of continuous subarrays.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [5,4,2,4]\nOutput: 8\nExplanation: \nContinuous subarray of size 1: [5], [4], [2], [4].\nContinuous subarray of size 2: [5,4], [4,2], [2,4].\nContinuous subarray of size 3: [4,2,4].\nThere are no subarrys of size 4.\nTotal continuous subarrays = 4 + 3 + 1 = 8.\nIt can be shown that there are no more continuous subarrays.\n\n\n
\n\n
Example 2:
\n\n\nInput: nums = [1,2,3]\nOutput: 6\nExplanation: \nContinuous subarray of size 1: [1], [2], [3].\nContinuous subarray of size 2: [1,2], [2,3].\nContinuous subarray of size 3: [1,2,3].\nTotal continuous subarrays = 3 + 2 + 1 = 6.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
The imbalance number of a 0-indexed integer array arr
of length n
is defined as the number of indices in sarr = sorted(arr)
such that:
0 <= i < n - 1
, andsarr[i+1] - sarr[i] > 1
Here, sorted(arr)
is the function that returns the sorted version of arr
.
Given a 0-indexed integer array nums
, return the sum of imbalance numbers of all its subarrays.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,1,4]\nOutput: 3\nExplanation: There are 3 subarrays with non-zero imbalance numbers:\n- Subarray [3, 1] with an imbalance number of 1.\n- Subarray [3, 1, 4] with an imbalance number of 1.\n- Subarray [1, 4] with an imbalance number of 1.\nThe imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 3. \n\n\n
Example 2:
\n\n\nInput: nums = [1,3,3,3,5]\nOutput: 8\nExplanation: There are 7 subarrays with non-zero imbalance numbers:\n- Subarray [1, 3] with an imbalance number of 1.\n- Subarray [1, 3, 3] with an imbalance number of 1.\n- Subarray [1, 3, 3, 3] with an imbalance number of 1.\n- Subarray [1, 3, 3, 3, 5] with an imbalance number of 2. \n- Subarray [3, 3, 3, 5] with an imbalance number of 1. \n- Subarray [3, 3, 5] with an imbalance number of 1.\n- Subarray [3, 5] with an imbalance number of 1.\nThe imbalance number of all other subarrays is 0. Hence, the sum of imbalance numbers of all the subarrays of nums is 8.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= nums.length
You are given a 0-indexed integer array nums
. A subarray s
of length m
is called alternating if:
m
is greater than 1
.s1 = s0 + 1
.s
looks like [s0, s1, s0, s1,...,s(m-1) % 2]
. In other words, s1 - s0 = 1
, s2 - s1 = -1
, s3 - s2 = 1
, s4 - s3 = -1
, and so on up to s[m - 1] - s[m - 2] = (-1)m
.Return the maximum length of all alternating subarrays present in nums
or -1
if no such subarray exists.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\nInput: nums = [2,3,4,3,4]
\n\nOutput: 4
\n\nExplanation:
\n\nThe alternating subarrays are [2, 3]
, [3,4]
, [3,4,3]
, and [3,4,3,4]
. The longest of these is [3,4,3,4]
, which is of length 4.
Example 2:
\n\nInput: nums = [4,5,6]
\n\nOutput: 2
\n\nExplanation:
\n\n[4,5]
and [5,6]
are the only two alternating subarrays. They are both of length 2.
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 104
You are given a 0-indexed integer array nums
representing the initial positions of some marbles. You are also given two 0-indexed integer arrays moveFrom
and moveTo
of equal length.
Throughout moveFrom.length
steps, you will change the positions of the marbles. On the ith
step, you will move all marbles at position moveFrom[i]
to position moveTo[i]
.
After completing all the steps, return the sorted list of occupied positions.
\n\nNotes:
\n\n\n
Example 1:
\n\n\nInput: nums = [1,6,7,8], moveFrom = [1,7,2], moveTo = [2,9,5]\nOutput: [5,6,8,9]\nExplanation: Initially, the marbles are at positions 1,6,7,8.\nAt the i = 0th step, we move the marbles at position 1 to position 2. Then, positions 2,6,7,8 are occupied.\nAt the i = 1st step, we move the marbles at position 7 to position 9. Then, positions 2,6,8,9 are occupied.\nAt the i = 2nd step, we move the marbles at position 2 to position 5. Then, positions 5,6,8,9 are occupied.\nAt the end, the final positions containing at least one marbles are [5,6,8,9].\n\n
Example 2:
\n\n\nInput: nums = [1,1,3,3], moveFrom = [1,3], moveTo = [2,2]\nOutput: [2]\nExplanation: Initially, the marbles are at positions [1,1,3,3].\nAt the i = 0th step, we move all the marbles at position 1 to position 2. Then, the marbles are at positions [2,2,3,3].\nAt the i = 1st step, we move all the marbles at position 3 to position 2. Then, the marbles are at positions [2,2,2,2].\nSince 2 is the only occupied position, we return [2].\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= moveFrom.length <= 105
moveFrom.length == moveTo.length
1 <= nums[i], moveFrom[i], moveTo[i] <= 109
moveFrom[i]
at the moment we want to apply the ith
move.Given a binary string s
, partition the string into one or more substrings such that each substring is beautiful.
A string is beautiful if:
\n\n5
.Return the minimum number of substrings in such partition. If it is impossible to partition the string s
into beautiful substrings, return -1
.
A substring is a contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: s = "1011"\nOutput: 2\nExplanation: We can paritition the given string into ["101", "1"].\n- The string "101" does not contain leading zeros and is the binary representation of integer 51 = 5.\n- The string "1" does not contain leading zeros and is the binary representation of integer 50 = 1.\nIt can be shown that 2 is the minimum number of beautiful substrings that s can be partitioned into.\n\n\n
Example 2:
\n\n\nInput: s = "111"\nOutput: 3\nExplanation: We can paritition the given string into ["1", "1", "1"].\n- The string "1" does not contain leading zeros and is the binary representation of integer 50 = 1.\nIt can be shown that 3 is the minimum number of beautiful substrings that s can be partitioned into.\n\n\n
Example 3:
\n\n\nInput: s = "0"\nOutput: -1\nExplanation: We can not partition the given string into beautiful substrings.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 15
s[i]
is either '0'
or '1'
.You are given two integers m
and n
representing the dimensions of a 0-indexed m x n
grid.
You are also given a 0-indexed 2D integer matrix coordinates
, where coordinates[i] = [x, y]
indicates that the cell with coordinates [x, y]
is colored black. All cells in the grid that do not appear in coordinates
are white.
A block is defined as a 2 x 2
submatrix of the grid. More formally, a block with cell [x, y]
as its top-left corner where 0 <= x < m - 1
and 0 <= y < n - 1
contains the coordinates [x, y]
, [x + 1, y]
, [x, y + 1]
, and [x + 1, y + 1]
.
Return a 0-indexed integer array arr
of size 5
such that arr[i]
is the number of blocks that contains exactly i
black cells.
\n
Example 1:
\n\n\nInput: m = 3, n = 3, coordinates = [[0,0]]\nOutput: [3,1,0,0,0]\nExplanation: The grid looks like this:\n\n\n\nThere is only 1 block with one black cell, and it is the block starting with cell [0,0].\nThe other 3 blocks start with cells [0,1], [1,0] and [1,1]. They all have zero black cells. \nThus, we return [3,1,0,0,0]. \n
Example 2:
\n\n\nInput: m = 3, n = 3, coordinates = [[0,0],[1,1],[0,2]]\nOutput: [0,2,2,0,0]\nExplanation: The grid looks like this:\n\n\n\nThere are 2 blocks with two black cells (the ones starting with cell coordinates [0,0] and [0,1]).\nThe other 2 blocks have starting cell coordinates of [1,0] and [1,1]. They both have 1 black cell.\nTherefore, we return [0,2,2,0,0].\n
\n
Constraints:
\n\n2 <= m <= 105
2 <= n <= 105
0 <= coordinates.length <= 104
coordinates[i].length == 2
0 <= coordinates[i][0] < m
0 <= coordinates[i][1] < n
coordinates
contains pairwise distinct coordinates.Given two integers, num
and t
. A number x
is achievable if it can become equal to num
after applying the following operation at most t
times:
x
by 1
, and simultaneously increase or decrease num
by 1
.Return the maximum possible value of x
.
\n
Example 1:
\n\nInput: num = 4, t = 1
\n\nOutput: 6
\n\nExplanation:
\n\nApply the following operation once to make the maximum achievable number equal to num
:
num
by 1.Example 2:
\n\nInput: num = 3, t = 2
\n\nOutput: 7
\n\nExplanation:
\n\nApply the following operation twice to make the maximum achievable number equal to num
:
num
by 1.\n
Constraints:
\n\n1 <= num, t <= 50
You are given a 0-indexed array nums
of n
integers and an integer target
.
You are initially positioned at index 0
. In one step, you can jump from index i
to any index j
such that:
0 <= i < j < n
-target <= nums[j] - nums[i] <= target
Return the maximum number of jumps you can make to reach index n - 1
.
If there is no way to reach index n - 1
, return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,3,6,4,1,2], target = 2\nOutput: 3\nExplanation: To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence:\n- Jump from index 0 to index 1. \n- Jump from index 1 to index 3.\n- Jump from index 3 to index 5.\nIt can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 3 jumps. Hence, the answer is 3.\n\n
Example 2:
\n\n\nInput: nums = [1,3,6,4,1,2], target = 3\nOutput: 5\nExplanation: To go from index 0 to index n - 1 with the maximum number of jumps, you can perform the following jumping sequence:\n- Jump from index 0 to index 1.\n- Jump from index 1 to index 2.\n- Jump from index 2 to index 3.\n- Jump from index 3 to index 4.\n- Jump from index 4 to index 5.\nIt can be proven that there is no other jumping sequence that goes from 0 to n - 1 with more than 5 jumps. Hence, the answer is 5.\n\n
Example 3:
\n\n\nInput: nums = [1,3,6,4,1,2], target = 0\nOutput: -1\nExplanation: It can be proven that there is no jumping sequence that goes from 0 to n - 1. Hence, the answer is -1. \n\n\n
\n
Constraints:
\n\n2 <= nums.length == n <= 1000
-109 <= nums[i] <= 109
0 <= target <= 2 * 109
You are given two 0-indexed integer arrays nums1
and nums2
of length n
.
Let's define another 0-indexed integer array, nums3
, of length n
. For each index i
in the range [0, n - 1]
, you can assign either nums1[i]
or nums2[i]
to nums3[i]
.
Your task is to maximize the length of the longest non-decreasing subarray in nums3
by choosing its values optimally.
Return an integer representing the length of the longest non-decreasing subarray in nums3
.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums1 = [2,3,1], nums2 = [1,2,1]\nOutput: 2\nExplanation: One way to construct nums3 is: \nnums3 = [nums1[0], nums2[1], nums2[2]] => [2,2,1]. \nThe subarray starting from index 0 and ending at index 1, [2,2], forms a non-decreasing subarray of length 2. \nWe can show that 2 is the maximum achievable length.\n\n
Example 2:
\n\n\nInput: nums1 = [1,3,2,1], nums2 = [2,2,3,4]\nOutput: 4\nExplanation: One way to construct nums3 is: \nnums3 = [nums1[0], nums2[1], nums2[2], nums2[3]] => [1,2,3,4]. \nThe entire array forms a non-decreasing subarray of length 4, making it the maximum achievable length.\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,1], nums2 = [2,2]\nOutput: 2\nExplanation: One way to construct nums3 is: \nnums3 = [nums1[0], nums1[1]] => [1,1]. \nThe entire array forms a non-decreasing subarray of length 2, making it the maximum achievable length.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length == nums2.length == n <= 105
1 <= nums1[i], nums2[i] <= 109
You are given a 0-indexed integer array nums
and a positive integer k
.
You can apply the following operation on the array any number of times:
\n\nk
from the array and decrease all its elements by 1
.Return true
if you can make all the array elements equal to 0
, or false
otherwise.
A subarray is a contiguous non-empty part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,2,3,1,1,0], k = 3\nOutput: true\nExplanation: We can do the following operations:\n- Choose the subarray [2,2,3]. The resulting array will be nums = [1,1,2,1,1,0].\n- Choose the subarray [2,1,1]. The resulting array will be nums = [1,1,1,0,0,0].\n- Choose the subarray [1,1,1]. The resulting array will be nums = [0,0,0,0,0,0].\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,1,1], k = 2\nOutput: false\nExplanation: It is not possible to make all the array elements equal to 0.\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
0 <= nums[i] <= 106
You are given a 1-indexed integer array nums
of length n
.
An element nums[i]
of nums
is called special if i
divides n
, i.e. n % i == 0
.
Return the sum of the squares of all special elements of nums
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 21\nExplanation: There are exactly 3 special elements in nums: nums[1] since 1 divides 4, nums[2] since 2 divides 4, and nums[4] since 4 divides 4. \nHence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[4] * nums[4] = 1 * 1 + 2 * 2 + 4 * 4 = 21. \n\n\n
Example 2:
\n\n\nInput: nums = [2,7,1,19,18,3]\nOutput: 63\nExplanation: There are exactly 4 special elements in nums: nums[1] since 1 divides 6, nums[2] since 2 divides 6, nums[3] since 3 divides 6, and nums[6] since 6 divides 6. \nHence, the sum of the squares of all special elements of nums is nums[1] * nums[1] + nums[2] * nums[2] + nums[3] * nums[3] + nums[6] * nums[6] = 2 * 2 + 7 * 7 + 1 * 1 + 3 * 3 = 63. \n\n\n
\n
Constraints:
\n\n1 <= nums.length == n <= 50
1 <= nums[i] <= 50
You are given a 0-indexed array nums
and a non-negative integer k
.
In one operation, you can do the following:
\n\ni
that hasn't been chosen before from the range [0, nums.length - 1]
.nums[i]
with any integer from the range [nums[i] - k, nums[i] + k]
.The beauty of the array is the length of the longest subsequence consisting of equal elements.
\n\nReturn the maximum possible beauty of the array nums
after applying the operation any number of times.
Note that you can apply the operation to each index only once.
\n\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [4,6,1,2], k = 2\nOutput: 3\nExplanation: In this example, we apply the following operations:\n- Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2].\n- Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4].\nAfter the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3).\nIt can be proven that 3 is the maximum possible length we can achieve.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1], k = 10\nOutput: 4\nExplanation: In this example we don't have to apply any operations.\nThe beauty of the array nums is 4 (whole array).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i], k <= 105
An element x
of an integer array arr
of length m
is dominant if freq(x) * 2 > m
, where freq(x)
is the number of occurrences of x
in arr
. Note that this definition implies that arr
can have at most one dominant element.
You are given a 0-indexed integer array nums
of length n
with one dominant element.
You can split nums
at an index i
into two arrays nums[0, ..., i]
and nums[i + 1, ..., n - 1]
, but the split is only valid if:
0 <= i < n - 1
nums[0, ..., i]
, and nums[i + 1, ..., n - 1]
have the same dominant element.Here, nums[i, ..., j]
denotes the subarray of nums
starting at index i
and ending at index j
, both ends being inclusive. Particularly, if j < i
then nums[i, ..., j]
denotes an empty subarray.
Return the minimum index of a valid split. If no valid split exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,2,2,2]\nOutput: 2\nExplanation: We can split the array at index 2 to obtain arrays [1,2,2] and [2]. \nIn array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 > 3. \nIn array [2], element 2 is dominant since it occurs once in the array and 1 * 2 > 1.\nBoth [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. \nIt can be shown that index 2 is the minimum index of a valid split.\n\n
Example 2:
\n\n\nInput: nums = [2,1,3,1,1,1,7,1,2,1]\nOutput: 4\nExplanation: We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1].\nIn array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.\nIn array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.\nBoth [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split.\nIt can be shown that index 4 is the minimum index of a valid split.\n\n
Example 3:
\n\n\nInput: nums = [3,3,3,3,7,2,2]\nOutput: -1\nExplanation: It can be shown that there is no valid split.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
nums
has exactly one dominant element.An element x
of an integer array arr
of length m
is dominant if more than half the elements of arr
have a value of x
.
You are given a 0-indexed integer array nums
of length n
with one dominant element.
You can split nums
at an index i
into two arrays nums[0, ..., i]
and nums[i + 1, ..., n - 1]
, but the split is only valid if:
0 <= i < n - 1
nums[0, ..., i]
, and nums[i + 1, ..., n - 1]
have the same dominant element.Here, nums[i, ..., j]
denotes the subarray of nums
starting at index i
and ending at index j
, both ends being inclusive. Particularly, if j < i
then nums[i, ..., j]
denotes an empty subarray.
Return the minimum index of a valid split. If no valid split exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,2,2,2]\nOutput: 2\nExplanation: We can split the array at index 2 to obtain arrays [1,2,2] and [2]. \nIn array [1,2,2], element 2 is dominant since it occurs twice in the array and 2 * 2 > 3. \nIn array [2], element 2 is dominant since it occurs once in the array and 1 * 2 > 1.\nBoth [1,2,2] and [2] have the same dominant element as nums, so this is a valid split. \nIt can be shown that index 2 is the minimum index of a valid split.\n\n
Example 2:
\n\n\nInput: nums = [2,1,3,1,1,1,7,1,2,1]\nOutput: 4\nExplanation: We can split the array at index 4 to obtain arrays [2,1,3,1,1] and [1,7,1,2,1].\nIn array [2,1,3,1,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.\nIn array [1,7,1,2,1], element 1 is dominant since it occurs thrice in the array and 3 * 2 > 5.\nBoth [2,1,3,1,1] and [1,7,1,2,1] have the same dominant element as nums, so this is a valid split.\nIt can be shown that index 4 is the minimum index of a valid split.\n\n
Example 3:
\n\n\nInput: nums = [3,3,3,3,7,2,2]\nOutput: -1\nExplanation: It can be shown that there is no valid split.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
nums
has exactly one dominant element.You are given a string word
and an array of strings forbidden
.
A string is called valid if none of its substrings are present in forbidden
.
Return the length of the longest valid substring of the string word
.
A substring is a contiguous sequence of characters in a string, possibly empty.
\n\n\n
Example 1:
\n\n\nInput: word = "cbaaaabc", forbidden = ["aaa","cb"]\nOutput: 4\nExplanation: There are 11 valid substrings in word: "c", "b", "a", "ba", "aa", "bc", "baa", "aab", "ab", "abc" and "aabc". The length of the longest valid substring is 4. \nIt can be shown that all other substrings contain either "aaa" or "cb" as a substring.\n\n
Example 2:
\n\n\nInput: word = "leetcode", forbidden = ["de","le","e"]\nOutput: 4\nExplanation: There are 11 valid substrings in word: "l", "t", "c", "o", "d", "tc", "co", "od", "tco", "cod", and "tcod". The length of the longest valid substring is 4.\nIt can be shown that all other substrings contain either "de", "le", or "e" as a substring. \n\n\n
\n
Constraints:
\n\n1 <= word.length <= 105
word
consists only of lowercase English letters.1 <= forbidden.length <= 105
1 <= forbidden[i].length <= 10
forbidden[i]
consists only of lowercase English letters.You are given an integer array nums
. We consider an array good if it is a permutation of an array base[n]
.
base[n] = [1, 2, ..., n - 1, n, n]
(in other words, it is an array of length n + 1
which contains 1
to n - 1
exactly once, plus two occurrences of n
). For example, base[1] = [1, 1]
and base[3] = [1, 2, 3, 3]
.
Return true
if the given array is good, otherwise return false
.
Note: A permutation of integers represents an arrangement of these numbers.
\n\n\n
Example 1:
\n\n\nInput: nums = [2, 1, 3]\nOutput: false\nExplanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. However, base[3] has four elements but array nums has three. Therefore, it can not be a permutation of base[3] = [1, 2, 3, 3]. So the answer is false.\n\n\n
Example 2:
\n\n\nInput: nums = [1, 3, 3, 2]\nOutput: true\nExplanation: Since the maximum element of the array is 3, the only candidate n for which this array could be a permutation of base[n], is n = 3. It can be seen that nums is a permutation of base[3] = [1, 2, 3, 3] (by swapping the second and fourth elements in nums, we reach base[3]). Therefore, the answer is true.\n\n
Example 3:
\n\n\nInput: nums = [1, 1]\nOutput: true\nExplanation: Since the maximum element of the array is 1, the only candidate n for which this array could be a permutation of base[n], is n = 1. It can be seen that nums is a permutation of base[1] = [1, 1]. Therefore, the answer is true.\n\n
Example 4:
\n\n\nInput: nums = [3, 4, 4, 1, 2, 1]\nOutput: false\nExplanation: Since the maximum element of the array is 4, the only candidate n for which this array could be a permutation of base[n], is n = 4. However, base[4] has five elements but array nums has six. Therefore, it can not be a permutation of base[4] = [1, 2, 3, 4, 4]. So the answer is false.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= num[i] <= 200
Given a 0-indexed string s
, permute s
to get a new string t
such that:
i
with 0 <= i < s.length
such that s[i]
is a consonant, then t[i] = s[i]
.i
, j
with 0 <= i < j < s.length
such that s[i]
and s[j]
are vowels, then t[i]
must not have a higher ASCII value than t[j]
.Return the resulting string.
\n\nThe vowels are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
, and they can appear in lowercase or uppercase. Consonants comprise all letters that are not vowels.
\n
Example 1:
\n\n\nInput: s = "lEetcOde"\nOutput: "lEOtcede"\nExplanation: 'E', 'O', and 'e' are the vowels in s; 'l', 't', 'c', and 'd' are all consonants. The vowels are sorted according to their ASCII values, and the consonants remain in the same places.\n\n\n
Example 2:
\n\n\nInput: s = "lYmpH"\nOutput: "lYmpH"\nExplanation: There are no vowels in s (all characters in s are consonants), so we return "lYmpH".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of letters of the English alphabet in uppercase and lowercase.You are given a 0-indexed integer array nums
and a positive integer x
.
You are initially at position 0
in the array and you can visit other positions according to the following rules:
i
, then you can move to any position j
such that i < j
.i
that you visit, you get a score of nums[i]
.i
to a position j
and the parities of nums[i]
and nums[j]
differ, then you lose a score of x
.Return the maximum total score you can get.
\n\nNote that initially you have nums[0]
points.
\n
Example 1:
\n\n\nInput: nums = [2,3,6,1,9,2], x = 5\nOutput: 13\nExplanation: We can visit the following positions in the array: 0 -> 2 -> 3 -> 4.\nThe corresponding values are 2, 6, 1 and 9. Since the integers 6 and 1 have different parities, the move 2 -> 3 will make you lose a score of x = 5.\nThe total score will be: 2 + 6 + 1 + 9 - 5 = 13.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,6,8], x = 3\nOutput: 20\nExplanation: All the integers in the array have the same parities, so we can visit all of them without losing any score.\nThe total score is: 2 + 4 + 6 + 8 = 20.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i], x <= 106
Given two positive integers n
and x
.
Return the number of ways n
can be expressed as the sum of the xth
power of unique positive integers, in other words, the number of sets of unique integers [n1, n2, ..., nk]
where n = n1x + n2x + ... + nkx
.
Since the result can be very large, return it modulo 109 + 7
.
For example, if n = 160
and x = 3
, one way to express n
is n = 23 + 33 + 53
.
\n
Example 1:
\n\n\nInput: n = 10, x = 2\nOutput: 1\nExplanation: We can express n as the following: n = 32 + 12 = 10.\nIt can be shown that it is the only way to express 10 as the sum of the 2nd power of unique integers.\n\n\n
Example 2:
\n\n\nInput: n = 4, x = 1\nOutput: 2\nExplanation: We can express n in the following ways:\n- n = 41 = 4.\n- n = 31 + 11 = 4.\n\n\n
\n
Constraints:
\n\n1 <= n <= 300
1 <= x <= 5
Given an array of strings words
and a character separator
, split each string in words
by separator
.
Return an array of strings containing the new strings formed after the splits, excluding empty strings.
\n\nNotes
\n\nseparator
is used to determine where the split should occur, but it is not included as part of the resulting strings.\n
Example 1:
\n\n\nInput: words = ["one.two.three","four.five","six"], separator = "."\nOutput: ["one","two","three","four","five","six"]\nExplanation: In this example we split as follows:\n\n"one.two.three" splits into "one", "two", "three"\n"four.five" splits into "four", "five"\n"six" splits into "six" \n\nHence, the resulting array is ["one","two","three","four","five","six"].\n\n
Example 2:
\n\n\nInput: words = ["$easy$","$problem$"], separator = "$"\nOutput: ["easy","problem"]\nExplanation: In this example we split as follows: \n\n"$easy$" splits into "easy" (excluding empty strings)\n"$problem$" splits into "problem" (excluding empty strings)\n\nHence, the resulting array is ["easy","problem"].\n\n\n
Example 3:
\n\n\nInput: words = ["|||"], separator = "|"\nOutput: []\nExplanation: In this example the resulting split of "|||" will contain only empty strings, so we return an empty array [].\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 20
words[i]
are either lowercase English letters or characters from the string ".,|$#@"
(excluding the quotes)separator
is a character from the string ".,|$#@"
(excluding the quotes)You are given a 0-indexed array nums
consisting of positive integers.
You can do the following operation on the array any number of times:
\n\ni
such that 0 <= i < nums.length - 1
and nums[i] <= nums[i + 1]
. Replace the element nums[i + 1]
with nums[i] + nums[i + 1]
and delete the element nums[i]
from the array.Return the value of the largest element that you can possibly obtain in the final array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,7,9,3]\nOutput: 21\nExplanation: We can apply the following operations on the array:\n- Choose i = 0. The resulting array will be nums = [5,7,9,3].\n- Choose i = 1. The resulting array will be nums = [5,16,3].\n- Choose i = 0. The resulting array will be nums = [21,3].\nThe largest element in the final array is 21. It can be shown that we cannot obtain a larger element.\n\n\n
Example 2:
\n\n\nInput: nums = [5,3,3]\nOutput: 11\nExplanation: We can do the following operations on the array:\n- Choose i = 1. The resulting array will be nums = [5,6].\n- Choose i = 0. The resulting array will be nums = [11].\nThere is only one element in the final array, which is 11.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
You are given a 0-indexed array usageLimits
of length n
.
Your task is to create groups using numbers from 0
to n - 1
, ensuring that each number, i
, is used no more than usageLimits[i]
times in total across all groups. You must also satisfy the following conditions:
Return an integer denoting the maximum number of groups you can create while satisfying these conditions.
\n\n\n
Example 1:
\n\n\nInput: usageLimits
= [1,2,5]\nOutput: 3\nExplanation: In this example, we can use 0 at most once, 1 at most twice, and 2 at most five times.\nOne way of creating the maximum number of groups while satisfying the conditions is: \nGroup 1 contains the number [2].\nGroup 2 contains the numbers [1,2].\nGroup 3 contains the numbers [0,1,2]. \nIt can be shown that the maximum number of groups is 3. \nSo, the output is 3.
\n\nExample 2:
\n\n\nInput: usageLimits
= [2,1,2]\nOutput: 2\nExplanation: In this example, we can use 0 at most twice, 1 at most once, and 2 at most twice.\nOne way of creating the maximum number of groups while satisfying the conditions is:\nGroup 1 contains the number [0].\nGroup 2 contains the numbers [1,2].\nIt can be shown that the maximum number of groups is 2.\nSo, the output is 2. \n
\n\nExample 3:
\n\n\nInput: usageLimits
= [1,1]\nOutput: 1\nExplanation: In this example, we can use both 0 and 1 at most once.\nOne way of creating the maximum number of groups while satisfying the conditions is:\nGroup 1 contains the number [0].\nIt can be shown that the maximum number of groups is 1.\nSo, the output is 1. \n
\n\n\n
Constraints:
\n\n1 <= usageLimits.length <= 105
1 <= usageLimits[i] <= 109
You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0
consisting of n
nodes numbered from 0
to n - 1
. The tree is represented by a 0-indexed array parent
of size n
, where parent[i]
is the parent of node i
. Since node 0
is the root, parent[0] == -1
.
You are also given a string s
of length n
, where s[i]
is the character assigned to the edge between i
and parent[i]
. s[0]
can be ignored.
Return the number of pairs of nodes (u, v)
such that u < v
and the characters assigned to edges on the path from u
to v
can be rearranged to form a palindrome.
A string is a palindrome when it reads the same backwards as forwards.
\n\n\n
Example 1:
\n\n\nInput: parent = [-1,0,0,1,1,2], s = "acaabc"\nOutput: 8\nExplanation: The valid pairs are:\n- All the pairs (0,1), (0,2), (1,3), (1,4) and (2,5) result in one character which is always a palindrome.\n- The pair (2,3) result in the string "aca" which is a palindrome.\n- The pair (1,5) result in the string "cac" which is a palindrome.\n- The pair (3,5) result in the string "acac" which can be rearranged into the palindrome "acca".\n\n\n
Example 2:
\n\n\nInput: parent = [-1,0,0,0,0], s = "aaaaa"\nOutput: 10\nExplanation: Any pair of nodes (u,v) where u < v is valid.\n\n\n
\n
Constraints:
\n\nn == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1
for all i >= 1
parent[0] == -1
parent
represents a valid tree.s
consists of only lowercase English letters.There are n
employees in a company, numbered from 0
to n - 1
. Each employee i
has worked for hours[i]
hours in the company.
The company requires each employee to work for at least target
hours.
You are given a 0-indexed array of non-negative integers hours
of length n
and a non-negative integer target
.
Return the integer denoting the number of employees who worked at least target
hours.
\n
Example 1:
\n\n\nInput: hours = [0,1,2,3,4], target = 2\nOutput: 3\nExplanation: The company wants each employee to work for at least 2 hours.\n- Employee 0 worked for 0 hours and didn't meet the target.\n- Employee 1 worked for 1 hours and didn't meet the target.\n- Employee 2 worked for 2 hours and met the target.\n- Employee 3 worked for 3 hours and met the target.\n- Employee 4 worked for 4 hours and met the target.\nThere are 3 employees who met the target.\n\n\n
Example 2:
\n\n\nInput: hours = [5,1,4,2,2], target = 6\nOutput: 0\nExplanation: The company wants each employee to work for at least 6 hours.\nThere are 0 employees who met the target.\n\n\n
\n
Constraints:
\n\n1 <= n == hours.length <= 50
0 <= hours[i], target <= 105
You are given an array nums
consisting of positive integers.
We call a subarray of an array complete if the following condition is satisfied:
\n\nReturn the number of complete subarrays.
\n\nA subarray is a contiguous non-empty part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,1,2,2]\nOutput: 4\nExplanation: The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].\n\n\n
Example 2:
\n\n\nInput: nums = [5,5,5,5]\nOutput: 10\nExplanation: The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 2000
a
, b
, and c
, your task is to find a string that has the minimum length and contains all three strings as substrings.\nIf there are multiple such strings, return the lexicographically smallest one.
\n\nReturn a string denoting the answer to the problem.
\n\nNotes
\n\na
is lexicographically smaller than a string b
(of the same length) if in the first position where a
and b
differ, string a
has a letter that appears earlier in the alphabet than the corresponding letter in b
.\n
Example 1:
\n\n\nInput: a = "abc", b = "bca", c = "aaa"\nOutput: "aaabca"\nExplanation: We show that "aaabca" contains all the given strings: a = ans[2...4], b = ans[3..5], c = ans[0..2]. It can be shown that the length of the resulting string would be at least 6 and "aaabca" is the lexicographically smallest one.\n\n
Example 2:
\n\n\nInput: a = "ab", b = "ba", c = "aba"\nOutput: "aba"\nExplanation: We show that the string "aba" contains all the given strings: a = ans[0..1], b = ans[1..2], c = ans[0..2]. Since the length of c is 3, the length of the resulting string would be at least 3. It can be shown that "aba" is the lexicographically smallest one.\n\n\n
\n
Constraints:
\n\n1 <= a.length, b.length, c.length <= 100
a
, b
, c
consist only of lowercase English letters.Given two positive integers low
and high
represented as strings, find the count of stepping numbers in the inclusive range [low, high]
.
A stepping number is an integer such that all of its adjacent digits have an absolute difference of exactly 1
.
Return an integer denoting the count of stepping numbers in the inclusive range [low, high]
.
Since the answer may be very large, return it modulo 109 + 7
.
Note: A stepping number should not have a leading zero.
\n\n\n
Example 1:
\n\n\nInput: low = "1", high = "11"\nOutput: 10\nExplanation: The stepping numbers in the range [1,11] are 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. There are a total of 10 stepping numbers in the range. Hence, the output is 10.\n\n
Example 2:
\n\n\nInput: low = "90", high = "101"\nOutput: 2\nExplanation: The stepping numbers in the range [90,101] are 98 and 101. There are a total of 2 stepping numbers in the range. Hence, the output is 2.\n\n
\n
Constraints:
\n\n1 <= int(low) <= int(high) < 10100
1 <= low.length, high.length <= 100
low
and high
consist of only digits.low
and high
don't have any leading zeros.Initially, you have a bank account balance of 100 dollars.
\n\nYou are given an integer purchaseAmount
representing the amount you will spend on a purchase in dollars, in other words, its price.
When making the purchase, first the purchaseAmount
is rounded to the nearest multiple of 10. Let us call this value roundedAmount
. Then, roundedAmount
dollars are removed from your bank account.
Return an integer denoting your final bank account balance after this purchase.
\n\nNotes:
\n\n\n
Example 1:
\n\nInput: purchaseAmount = 9
\n\nOutput: 90
\n\nExplanation:
\n\nThe nearest multiple of 10 to 9 is 10. So your account balance becomes 100 - 10 = 90.
\nExample 2:
\n\nInput: purchaseAmount = 15
\n\nOutput: 80
\n\nExplanation:
\n\nThe nearest multiple of 10 to 15 is 20. So your account balance becomes 100 - 20 = 80.
\nExample 3:
\n\nInput: purchaseAmount = 10
\n\nOutput: 90
\n\nExplanation:
\n\n10 is a multiple of 10 itself. So your account balance becomes 100 - 10 = 90.
\n\n
Constraints:
\n\n0 <= purchaseAmount <= 100
Given the head of a linked list head
, in which each node contains an integer value.
Between every pair of adjacent nodes, insert a new node with a value equal to the greatest common divisor of them.
\n\nReturn the linked list after insertion.
\n\nThe greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
\n\n\n
Example 1:
\n\nInput: head = [18,6,10,3]\nOutput: [18,6,6,2,10,1,3]\nExplanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes (nodes in blue are the inserted nodes).\n- We insert the greatest common divisor of 18 and 6 = 6 between the 1st and the 2nd nodes.\n- We insert the greatest common divisor of 6 and 10 = 2 between the 2nd and the 3rd nodes.\n- We insert the greatest common divisor of 10 and 3 = 1 between the 3rd and the 4th nodes.\nThere are no more adjacent nodes, so we return the linked list.\n\n\n
Example 2:
\n\nInput: head = [7]\nOutput: [7]\nExplanation: The 1st diagram denotes the initial linked list and the 2nd diagram denotes the linked list after inserting the new nodes.\nThere are no pairs of adjacent nodes, so we return the initial linked list.\n\n\n
\n
Constraints:
\n\n[1, 5000]
.1 <= Node.val <= 1000
You are given a 0-indexed array nums
containing n
integers.
At each second, you perform the following operation on the array:
\n\ni
in the range [0, n - 1]
, replace nums[i]
with either nums[i]
, nums[(i - 1 + n) % n]
, or nums[(i + 1) % n]
.Note that all the elements get replaced simultaneously.
\n\nReturn the minimum number of seconds needed to make all elements in the array nums
equal.
\n
Example 1:
\n\n\nInput: nums = [1,2,1,2]\nOutput: 1\nExplanation: We can equalize the array in 1 second in the following way:\n- At 1st second, replace values at each index with [nums[3],nums[1],nums[3],nums[3]]. After replacement, nums = [2,2,2,2].\nIt can be proven that 1 second is the minimum amount of seconds needed for equalizing the array.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,3,3,2]\nOutput: 2\nExplanation: We can equalize the array in 2 seconds in the following way:\n- At 1st second, replace values at each index with [nums[0],nums[2],nums[2],nums[2],nums[3]]. After replacement, nums = [2,3,3,3,3].\n- At 2nd second, replace values at each index with [nums[1],nums[1],nums[2],nums[3],nums[4]]. After replacement, nums = [3,3,3,3,3].\nIt can be proven that 2 seconds is the minimum amount of seconds needed for equalizing the array.\n\n\n
Example 3:
\n\n\nInput: nums = [5,5,5,5]\nOutput: 0\nExplanation: We don't need to perform any operations as all elements in the initial array are the same.\n\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 105
1 <= nums[i] <= 109
You are given two 0-indexed integer arrays nums1
and nums2
of equal length. Every second, for all indices 0 <= i < nums1.length
, value of nums1[i]
is incremented by nums2[i]
. After this is done, you can do the following operation:
0 <= i < nums1.length
and make nums1[i] = 0
.You are also given an integer x
.
Return the minimum time in which you can make the sum of all elements of nums1
to be less than or equal to x
, or -1
if this is not possible.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,3], nums2 = [1,2,3], x = 4\nOutput: 3\nExplanation: \nFor the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6]. \nFor the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9]. \nFor the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0]. \nNow sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.\n\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2,3], nums2 = [3,3,3], x = 4\nOutput: -1\nExplanation: It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length <= 103
1 <= nums1[i] <= 103
0 <= nums2[i] <= 103
nums1.length == nums2.length
0 <= x <= 106
Your laptop keyboard is faulty, and whenever you type a character 'i'
on it, it reverses the string that you have written. Typing other characters works as expected.
You are given a 0-indexed string s
, and you type each character of s
using your faulty keyboard.
Return the final string that will be present on your laptop screen.
\n\n\n
Example 1:
\n\n\nInput: s = "string"\nOutput: "rtsng"\nExplanation: \nAfter typing first character, the text on the screen is "s".\nAfter the second character, the text is "st". \nAfter the third character, the text is "str".\nSince the fourth character is an 'i', the text gets reversed and becomes "rts".\nAfter the fifth character, the text is "rtsn". \nAfter the sixth character, the text is "rtsng". \nTherefore, we return "rtsng".\n\n\n
Example 2:
\n\n\nInput: s = "poiinter"\nOutput: "ponter"\nExplanation: \nAfter the first character, the text on the screen is "p".\nAfter the second character, the text is "po". \nSince the third character you type is an 'i', the text gets reversed and becomes "op". \nSince the fourth character you type is an 'i', the text gets reversed and becomes "po".\nAfter the fifth character, the text is "pon".\nAfter the sixth character, the text is "pont". \nAfter the seventh character, the text is "ponte". \nAfter the eighth character, the text is "ponter". \nTherefore, we return "ponter".\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters.s[0] != 'i'
You are given an array nums
of length n
and an integer m
. You need to determine if it is possible to split the array into n
arrays of size 1 by performing a series of steps.
An array is called good if:
\n\nm
.In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two arrays, if both resulting arrays are good.
\n\nReturn true if you can split the given array into n
arrays, otherwise return false.
\n
Example 1:
\n\nInput: nums = [2, 2, 1], m = 4
\n\nOutput: true
\n\nExplanation:
\n\n[2, 2, 1]
to [2, 2]
and [1]
. The array [1]
has a length of one, and the array [2, 2]
has the sum of its elements equal to 4 >= m
, so both are good arrays.[2, 2]
to [2]
and [2]
. both arrays have the length of one, so both are good arrays.Example 2:
\n\nInput: nums = [2, 1, 3], m = 5
\n\nOutput: false
\n\nExplanation:
\n\nThe first move has to be either of the following:
\n\n[2, 1, 3]
to [2, 1]
and [3]
. The array [2, 1]
has neither length of one nor sum of elements greater than or equal to m
.[2, 1, 3]
to [2]
and [1, 3]
. The array [1, 3]
has neither length of one nor sum of elements greater than or equal to m
.So as both moves are invalid (they do not divide the array into two good arrays), we are unable to split nums
into n
arrays of size 1.
Example 3:
\n\nInput: nums = [2, 3, 3, 2, 3], m = 6
\n\nOutput: true
\n\nExplanation:
\n\n[2, 3, 3, 2, 3]
to [2]
and [3, 3, 2, 3]
.[3, 3, 2, 3]
to [3, 3, 2]
and [3]
.[3, 3, 2]
to [3, 3]
and [2]
.[3, 3]
to [3]
and [3]
.\n
Constraints:
\n\n1 <= n == nums.length <= 100
1 <= nums[i] <= 100
1 <= m <= 200
You are given a 0-indexed 2D matrix grid
of size n x n
, where (r, c)
represents:
grid[r][c] = 1
grid[r][c] = 0
You are initially positioned at cell (0, 0)
. In one move, you can move to any adjacent cell in the grid, including cells containing thieves.
The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid.
\n\nReturn the maximum safeness factor of all paths leading to cell (n - 1, n - 1)
.
An adjacent cell of cell (r, c)
, is one of the cells (r, c + 1)
, (r, c - 1)
, (r + 1, c)
and (r - 1, c)
if it exists.
The Manhattan distance between two cells (a, b)
and (x, y)
is equal to |a - x| + |b - y|
, where |val|
denotes the absolute value of val.
\n
Example 1:
\n\nInput: grid = [[1,0,0],[0,0,0],[0,0,1]]\nOutput: 0\nExplanation: All paths from (0, 0) to (n - 1, n - 1) go through the thieves in cells (0, 0) and (n - 1, n - 1).\n\n\n
Example 2:
\n\nInput: grid = [[0,0,1],[0,0,0],[0,0,0]]\nOutput: 2\nExplanation: The path depicted in the picture above has a safeness factor of 2 since:\n- The closest cell of the path to the thief at cell (0, 2) is cell (0, 0). The distance between them is | 0 - 0 | + | 0 - 2 | = 2.\nIt can be shown that there are no other paths with a higher safeness factor.\n\n\n
Example 3:
\n\nInput: grid = [[0,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,0]]\nOutput: 2\nExplanation: The path depicted in the picture above has a safeness factor of 2 since:\n- The closest cell of the path to the thief at cell (0, 3) is cell (1, 2). The distance between them is | 0 - 1 | + | 3 - 2 | = 2.\n- The closest cell of the path to the thief at cell (3, 0) is cell (3, 2). The distance between them is | 3 - 3 | + | 0 - 2 | = 2.\nIt can be shown that there are no other paths with a higher safeness factor.\n\n\n
\n
Constraints:
\n\n1 <= grid.length == n <= 400
grid[i].length == n
grid[i][j]
is either 0
or 1
.grid
.You are given a 0-indexed 2D integer array items
of length n
and an integer k
.
items[i] = [profiti, categoryi]
, where profiti
and categoryi
denote the profit and category of the ith
item respectively.
Let's define the elegance of a subsequence of items
as total_profit + distinct_categories2
, where total_profit
is the sum of all profits in the subsequence, and distinct_categories
is the number of distinct categories from all the categories in the selected subsequence.
Your task is to find the maximum elegance from all subsequences of size k
in items
.
Return an integer denoting the maximum elegance of a subsequence of items
with size exactly k
.
Note: A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.
\n\n\n
Example 1:
\n\n\nInput: items = [[3,2],[5,1],[10,1]], k = 2\nOutput: 17\nExplanation: In this example, we have to select a subsequence of size 2.\nWe can select items[0] = [3,2] and items[2] = [10,1].\nThe total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1].\nHence, the elegance is 13 + 22 = 17, and we can show that it is the maximum achievable elegance. \n\n\n
Example 2:
\n\n\nInput: items = [[3,1],[3,1],[2,2],[5,3]], k = 3\nOutput: 19\nExplanation: In this example, we have to select a subsequence of size 3. \nWe can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3]. \nThe total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3]. \nHence, the elegance is 10 + 32 = 19, and we can show that it is the maximum achievable elegance.\n\n
Example 3:
\n\n\nInput: items = [[1,1],[2,1],[3,1]], k = 3\nOutput: 7\nExplanation: In this example, we have to select a subsequence of size 3. \nWe should select all the items. \nThe total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1]. \nHence, the maximum elegance is 6 + 12 = 7.\n\n
\n
Constraints:
\n\n1 <= items.length == n <= 105
items[i].length == 2
items[i][0] == profiti
items[i][1] == categoryi
1 <= profiti <= 109
1 <= categoryi <= n
1 <= k <= n
You are given an integer array nums
. You have to find the maximum sum of a pair of numbers from nums
such that the largest digit in both numbers is equal.
For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.
\n\nReturn the maximum sum or -1 if no such pair exists.
\n\n\n
Example 1:
\n\nInput: nums = [112,131,411]
\n\nOutput: -1
\n\nExplanation:
\n\nEach numbers largest digit in order is [2,3,4].
\nExample 2:
\n\nInput: nums = [2536,1613,3366,162]
\n\nOutput: 5902
\n\nExplanation:
\n\nAll the numbers have 6 as their largest digit, so the answer is 2536 + 3366 = 5902.
\nExample 3:
\n\nInput: nums = [51,71,17,24,42]
\n\nOutput: 88
\n\nExplanation:
\n\nEach number's largest digit in order is [5,7,7,4,4].
\n\nSo we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.
\n\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 104
You are given the head
of a non-empty linked list representing a non-negative integer without leading zeroes.
Return the head
of the linked list after doubling it.
\n
Example 1:
\n\nInput: head = [1,8,9]\nOutput: [3,7,8]\nExplanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.\n\n\n
Example 2:
\n\nInput: head = [9,9,9]\nOutput: [1,9,9,8]\nExplanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list reprersents the number 999 * 2 = 1998. \n\n\n
\n
Constraints:
\n\n[1, 104]
0 <= Node.val <= 9
0
itself.You are given a 0-indexed integer array nums
and an integer x
.
Find the minimum absolute difference between two elements in the array that are at least x
indices apart.
In other words, find two indices i
and j
such that abs(i - j) >= x
and abs(nums[i] - nums[j])
is minimized.
Return an integer denoting the minimum absolute difference between two elements that are at least x
indices apart.
\n
Example 1:
\n\n\nInput: nums = [4,3,2,4], x = 2\nOutput: 0\nExplanation: We can select nums[0] = 4 and nums[3] = 4. \nThey are at least 2 indices apart, and their absolute difference is the minimum, 0. \nIt can be shown that 0 is the optimal answer.\n\n\n
Example 2:
\n\n\nInput: nums = [5,3,2,10,15], x = 1\nOutput: 1\nExplanation: We can select nums[1] = 3 and nums[2] = 2.\nThey are at least 1 index apart, and their absolute difference is the minimum, 1.\nIt can be shown that 1 is the optimal answer.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3,4], x = 3\nOutput: 3\nExplanation: We can select nums[0] = 1 and nums[3] = 4.\nThey are at least 3 indices apart, and their absolute difference is the minimum, 3.\nIt can be shown that 3 is the optimal answer.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= x < nums.length
You are given an array nums
of n
positive integers and an integer k
.
Initially, you start with a score of 1
. You have to maximize your score by applying the following operation at most k
times:
nums[l, ..., r]
that you haven't chosen previously.x
of nums[l, ..., r]
with the highest prime score. If multiple such elements exist, choose the one with the smallest index.x
.Here, nums[l, ..., r]
denotes the subarray of nums
starting at index l
and ending at the index r
, both ends being inclusive.
The prime score of an integer x
is equal to the number of distinct prime factors of x
. For example, the prime score of 300
is 3
since 300 = 2 * 2 * 3 * 5 * 5
.
Return the maximum possible score after applying at most k
operations.
Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [8,3,9,3,8], k = 2\nOutput: 81\nExplanation: To get a score of 81, we can apply the following operations:\n- Choose subarray nums[2, ..., 2]. nums[2] is the only element in this subarray. Hence, we multiply the score by nums[2]. The score becomes 1 * 9 = 9.\n- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 1, but nums[2] has the smaller index. Hence, we multiply the score by nums[2]. The score becomes 9 * 9 = 81.\nIt can be proven that 81 is the highest score one can obtain.\n\n
Example 2:
\n\n\nInput: nums = [19,12,14,6,10,18], k = 3\nOutput: 4788\nExplanation: To get a score of 4788, we can apply the following operations: \n- Choose subarray nums[0, ..., 0]. nums[0] is the only element in this subarray. Hence, we multiply the score by nums[0]. The score becomes 1 * 19 = 19.\n- Choose subarray nums[5, ..., 5]. nums[5] is the only element in this subarray. Hence, we multiply the score by nums[5]. The score becomes 19 * 18 = 342.\n- Choose subarray nums[2, ..., 3]. Both nums[2] and nums[3] have a prime score of 2, but nums[2] has the smaller index. Hence, we multipy the score by nums[2]. The score becomes 342 * 14 = 4788.\nIt can be proven that 4788 is the highest score one can obtain.\n\n\n
\n
Constraints:
\n\n1 <= nums.length == n <= 105
1 <= nums[i] <= 105
1 <= k <= min(n * (n + 1) / 2, 109)
nums
of length n
and an integer target
, return the number of pairs (i, j)
where 0 <= i < j < n
and nums[i] + nums[j] < target
.\n\n
Example 1:
\n\n\nInput: nums = [-1,1,2,3,1], target = 2\nOutput: 3\nExplanation: There are 3 pairs of indices that satisfy the conditions in the statement:\n- (0, 1) since 0 < 1 and nums[0] + nums[1] = 0 < target\n- (0, 2) since 0 < 2 and nums[0] + nums[2] = 1 < target \n- (0, 4) since 0 < 4 and nums[0] + nums[4] = 0 < target\nNote that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.\n\n\n
Example 2:
\n\n\nInput: nums = [-6,2,5,-2,-7,-1,3], target = -2\nOutput: 10\nExplanation: There are 10 pairs of indices that satisfy the conditions in the statement:\n- (0, 1) since 0 < 1 and nums[0] + nums[1] = -4 < target\n- (0, 3) since 0 < 3 and nums[0] + nums[3] = -8 < target\n- (0, 4) since 0 < 4 and nums[0] + nums[4] = -13 < target\n- (0, 5) since 0 < 5 and nums[0] + nums[5] = -7 < target\n- (0, 6) since 0 < 6 and nums[0] + nums[6] = -3 < target\n- (1, 4) since 1 < 4 and nums[1] + nums[4] = -5 < target\n- (3, 4) since 3 < 4 and nums[3] + nums[4] = -9 < target\n- (3, 5) since 3 < 5 and nums[3] + nums[5] = -3 < target\n- (4, 5) since 4 < 5 and nums[4] + nums[5] = -8 < target\n- (4, 6) since 4 < 6 and nums[4] + nums[6] = -4 < target\n\n\n
\n
Constraints:
\n\n1 <= nums.length == n <= 50
-50 <= nums[i], target <= 50
You are given two 0-indexed strings str1
and str2
.
In an operation, you select a set of indices in str1
, and for each index i
in the set, increment str1[i]
to the next character cyclically. That is 'a'
becomes 'b'
, 'b'
becomes 'c'
, and so on, and 'z'
becomes 'a'
.
Return true
if it is possible to make str2
a subsequence of str1
by performing the operation at most once, and false
otherwise.
Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.
\n\n\n
Example 1:
\n\n\nInput: str1 = "abc", str2 = "ad"\nOutput: true\nExplanation: Select index 2 in str1.\nIncrement str1[2] to become 'd'. \nHence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.\n\n
Example 2:
\n\n\nInput: str1 = "zc", str2 = "ad"\nOutput: true\nExplanation: Select indices 0 and 1 in str1. \nIncrement str1[0] to become 'a'. \nIncrement str1[1] to become 'd'. \nHence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.\n\n
Example 3:
\n\n\nInput: str1 = "ab", str2 = "d"\nOutput: false\nExplanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. \nTherefore, false is returned.\n\n
\n
Constraints:
\n\n1 <= str1.length <= 105
1 <= str2.length <= 105
str1
and str2
consist of only lowercase English letters.You are given an integer array nums
. Each element in nums
is 1, 2 or 3. In each operation, you can remove an element from nums
. Return the minimum number of operations to make nums
non-decreasing.
\n
Example 1:
\n\nInput: nums = [2,1,3,2,1]
\n\nOutput: 3
\n\nExplanation:
\n\nOne of the optimal solutions is to remove nums[0]
, nums[2]
and nums[3]
.
Example 2:
\n\nInput: nums = [1,3,2,1,3,3]
\n\nOutput: 2
\n\nExplanation:
\n\nOne of the optimal solutions is to remove nums[1]
and nums[2]
.
Example 3:
\n\nInput: nums = [2,2,2,2,3,3]
\n\nOutput: 0
\n\nExplanation:
\n\nnums
is already non-decreasing.
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 3
\nFollow-up: Can you come up with an algorithm that runs in
O(n)
time complexity?",
- "likes": 505,
+ "likes": 512,
"dislikes": 91,
- "stats": "{\"totalAccepted\": \"22K\", \"totalSubmission\": \"52.5K\", \"totalAcceptedRaw\": 21967, \"totalSubmissionRaw\": 52453, \"acRate\": \"41.9%\"}",
+ "stats": "{\"totalAccepted\": \"23.3K\", \"totalSubmission\": \"55.6K\", \"totalAcceptedRaw\": 23271, \"totalSubmissionRaw\": 55592, \"acRate\": \"41.9%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [
@@ -106529,10 +106786,10 @@
"questionFrontendId": "2827",
"title": "Number of Beautiful Integers in the Range",
"content": "You are given positive integers low
, high
, and k
.
A number is beautiful if it meets both of the following conditions:
\n\nk
.Return the number of beautiful integers in the range [low, high]
.
\n
Example 1:
\n\n\nInput: low = 10, high = 20, k = 3\nOutput: 2\nExplanation: There are 2 beautiful integers in the given range: [12,18]. \n- 12 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.\n- 18 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 3.\nAdditionally we can see that:\n- 16 is not beautiful because it is not divisible by k = 3.\n- 15 is not beautiful because it does not contain equal counts even and odd digits.\nIt can be shown that there are only 2 beautiful integers in the given range.\n\n\n
Example 2:
\n\n\nInput: low = 1, high = 10, k = 1\nOutput: 1\nExplanation: There is 1 beautiful integer in the given range: [10].\n- 10 is beautiful because it contains 1 odd digit and 1 even digit, and is divisible by k = 1.\nIt can be shown that there is only 1 beautiful integer in the given range.\n\n\n
Example 3:
\n\n\nInput: low = 5, high = 5, k = 2\nOutput: 0\nExplanation: There are 0 beautiful integers in the given range.\n- 5 is not beautiful because it is not divisible by k = 2 and it does not contain equal even and odd digits.\n\n\n
\n
Constraints:
\n\n0 < low <= high <= 109
0 < k <= 20
Given an array of strings words
and a string s
, determine if s
is an acronym of words.
The string s
is considered an acronym of words
if it can be formed by concatenating the first character of each string in words
in order. For example, "ab"
can be formed from ["apple", "banana"]
, but it can't be formed from ["bear", "aardvark"]
.
Return true
if s
is an acronym of words
, and false
otherwise.
\n
Example 1:
\n\n\nInput: words = ["alice","bob","charlie"], s = "abc"\nOutput: true\nExplanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym. \n\n\n
Example 2:
\n\n\nInput: words = ["an","apple"], s = "a"\nOutput: false\nExplanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively. \nThe acronym formed by concatenating these characters is "aa". \nHence, s = "a" is not the acronym.\n\n\n
Example 3:
\n\n\nInput: words = ["never","gonna","give","up","on","you"], s = "ngguoy"\nOutput: true\nExplanation: By concatenating the first character of the words in the array, we get the string "ngguoy". \nHence, s = "ngguoy" is the acronym.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 10
1 <= s.length <= 100
words[i]
and s
consist of lowercase English letters.You are given two integers, n
and k
.
An array of distinct positive integers is called a k-avoiding array if there does not exist any pair of distinct elements that sum to k
.
Return the minimum possible sum of a k-avoiding array of length n
.
\n
Example 1:
\n\n\nInput: n = 5, k = 4\nOutput: 18\nExplanation: Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.\nIt can be proven that there is no k-avoiding array with a sum less than 18.\n\n\n
Example 2:
\n\n\nInput: n = 2, k = 6\nOutput: 3\nExplanation: We can construct the array [1,2], which has a sum of 3.\nIt can be proven that there is no k-avoiding array with a sum less than 3.\n\n\n
\n
Constraints:
\n\n1 <= n, k <= 50
You are given an integer n
representing the number of houses on a number line, numbered from 0
to n - 1
.
Additionally, you are given a 2D integer array offers
where offers[i] = [starti, endi, goldi]
, indicating that ith
buyer wants to buy all the houses from starti
to endi
for goldi
amount of gold.
As a salesman, your goal is to maximize your earnings by strategically selecting and selling houses to buyers.
\n\nReturn the maximum amount of gold you can earn.
\n\nNote that different buyers can't buy the same house, and some houses may remain unsold.
\n\n\n
Example 1:
\n\n\nInput: n = 5, offers = [[0,0,1],[0,2,2],[1,3,2]]\nOutput: 3\nExplanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers.\nWe sell houses in the range [0,0] to 1st buyer for 1 gold and houses in the range [1,3] to 3rd buyer for 2 golds.\nIt can be proven that 3 is the maximum amount of gold we can achieve.\n\n\n
Example 2:
\n\n\nInput: n = 5, offers = [[0,0,1],[0,2,10],[1,3,2]]\nOutput: 10\nExplanation: There are 5 houses numbered from 0 to 4 and there are 3 purchase offers.\nWe sell houses in the range [0,2] to 2nd buyer for 10 golds.\nIt can be proven that 10 is the maximum amount of gold we can achieve.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= offers.length <= 105
offers[i].length == 3
0 <= starti <= endi <= n - 1
1 <= goldi <= 103
You are given a 0-indexed integer array nums
and an integer k
.
A subarray is called equal if all of its elements are equal. Note that the empty subarray is an equal subarray.
\n\nReturn the length of the longest possible equal subarray after deleting at most k
elements from nums
.
A subarray is a contiguous, possibly empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,2,3,1,3], k = 3\nOutput: 3\nExplanation: It's optimal to delete the elements at index 2 and index 4.\nAfter deleting them, nums becomes equal to [1, 3, 3, 3].\nThe longest equal subarray starts at i = 1 and ends at j = 3 with length equal to 3.\nIt can be proven that no longer equal subarrays can be created.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,2,2,1,1], k = 2\nOutput: 4\nExplanation: It's optimal to delete the elements at index 2 and index 3.\nAfter deleting them, nums becomes equal to [1, 1, 1, 1].\nThe array itself is an equal subarray, so the answer is 4.\nIt can be proven that no longer equal subarrays can be created.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= nums.length
0 <= k <= nums.length
You are given a string moves
of length n
consisting only of characters 'L'
, 'R'
, and '_'
. The string represents your movement on a number line starting from the origin 0
.
In the ith
move, you can choose one of the following directions:
moves[i] = 'L'
or moves[i] = '_'
moves[i] = 'R'
or moves[i] = '_'
Return the distance from the origin of the furthest point you can get to after n
moves.
\n
Example 1:
\n\n\nInput: moves = "L_RL__R"\nOutput: 3\nExplanation: The furthest point we can reach from the origin 0 is point -3 through the following sequence of moves "LLRLLLR".\n\n\n
Example 2:
\n\n\nInput: moves = "_R__LL_"\nOutput: 5\nExplanation: The furthest point we can reach from the origin 0 is point -5 through the following sequence of moves "LRLLLLL".\n\n\n
Example 3:
\n\n\nInput: moves = "_______"\nOutput: 7\nExplanation: The furthest point we can reach from the origin 0 is point 7 through the following sequence of moves "RRRRRRR".\n\n\n
\n
Constraints:
\n\n1 <= moves.length == n <= 50
moves
consists only of characters 'L'
, 'R'
and '_'
.You are given positive integers n
and target
.
An array nums
is beautiful if it meets the following conditions:
nums.length == n
.nums
consists of pairwise distinct positive integers.i
and j
, in the range [0, n - 1]
, such that nums[i] + nums[j] == target
.Return the minimum possible sum that a beautiful array could have modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: n = 2, target = 3\nOutput: 4\nExplanation: We can see that nums = [1,3] is beautiful.\n- The array nums has length n = 2.\n- The array nums consists of pairwise distinct positive integers.\n- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3.\nIt can be proven that 4 is the minimum possible sum that a beautiful array could have.\n\n\n
Example 2:
\n\n\nInput: n = 3, target = 3\nOutput: 8\nExplanation: We can see that nums = [1,3,4] is beautiful.\n- The array nums has length n = 3.\n- The array nums consists of pairwise distinct positive integers.\n- There doesn't exist two distinct indices, i and j, with nums[i] + nums[j] == 3.\nIt can be proven that 8 is the minimum possible sum that a beautiful array could have.\n\n\n
Example 3:
\n\n\nInput: n = 1, target = 1\nOutput: 1\nExplanation: We can see, that nums = [1] is beautiful.\n\n\n
\n
Constraints:
\n\n1 <= n <= 109
1 <= target <= 109
You are given a 0-indexed array nums
consisting of non-negative powers of 2
, and an integer target
.
In one operation, you must apply the following changes to the array:
\n\nnums[i]
such that nums[i] > 1
.nums[i]
from the array.nums[i] / 2
to the end of nums
.Return the minimum number of operations you need to perform so that nums
contains a subsequence whose elements sum to target
. If it is impossible to obtain such a subsequence, return -1
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,8], target = 7\nOutput: 1\nExplanation: In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4].\nAt this stage, nums contains the subsequence [1,2,4] which sums up to 7.\nIt can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7.\n\n\n
Example 2:
\n\n\nInput: nums = [1,32,1,2], target = 12\nOutput: 2\nExplanation: In the first operation, we choose element nums[1]. The array becomes equal to nums = [1,1,2,16,16].\nIn the second operation, we choose element nums[3]. The array becomes equal to nums = [1,1,2,16,8,8]\nAt this stage, nums contains the subsequence [1,1,2,8] which sums up to 12.\nIt can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.\n\n
Example 3:
\n\n\nInput: nums = [1,32,1], target = 35\nOutput: -1\nExplanation: It can be shown that no sequence of operations results in a subsequence that sums up to 35.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 230
nums
consists only of non-negative powers of two.1 <= target < 231
You are given an integer array receiver
of length n
and an integer k
. n
players are playing a ball-passing game.
You choose the starting player, i
. The game proceeds as follows: player i
passes the ball to player receiver[i]
, who then passes it to receiver[receiver[i]]
, and so on, for k
passes in total. The game's score is the sum of the indices of the players who touched the ball, including repetitions, i.e. i + receiver[i] + receiver[receiver[i]] + ... + receiver(k)[i]
.
Return the maximum possible score.
\n\nNotes:
\n\nreceiver
may contain duplicates.receiver[i]
may be equal to i
.\n
Example 1:
\n\nInput: receiver = [2,0,1], k = 4
\n\nOutput: 6
\n\nExplanation:
\n\nStarting with player i = 2
the initial score is 2:
Pass | \n\t\t\tSender Index | \n\t\t\tReceiver Index | \n\t\t\tScore | \n\t\t
---|---|---|---|
1 | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\t3 | \n\t\t
2 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t3 | \n\t\t
3 | \n\t\t\t0 | \n\t\t\t2 | \n\t\t\t5 | \n\t\t
4 | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\t6 | \n\t\t
Example 2:
\n\nInput: receiver = [1,1,1,2,3], k = 3
\n\nOutput: 10
\n\nExplanation:
\n\nStarting with player i = 4
the initial score is 4:
Pass | \n\t\t\tSender Index | \n\t\t\tReceiver Index | \n\t\t\tScore | \n\t\t
---|---|---|---|
1 | \n\t\t\t4 | \n\t\t\t3 | \n\t\t\t7 | \n\t\t
2 | \n\t\t\t3 | \n\t\t\t2 | \n\t\t\t9 | \n\t\t
3 | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\t10 | \n\t\t
\n
Constraints:
\n\n1 <= receiver.length == n <= 105
0 <= receiver[i] <= n - 1
1 <= k <= 1010
You are given two strings s1
and s2
, both of length 4
, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
\n\ni
and j
such that j - i = 2
, then swap the two characters at those indices in the string.Return true
if you can make the strings s1
and s2
equal, and false
otherwise.
\n
Example 1:
\n\n\nInput: s1 = "abcd", s2 = "cdab"\nOutput: true\nExplanation: We can do the following operations on s1:\n- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad".\n- Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2.\n\n\n
Example 2:
\n\n\nInput: s1 = "abcd", s2 = "dacb"\nOutput: false\nExplanation: It is not possible to make the two strings equal.\n\n\n
\n
Constraints:
\n\ns1.length == s2.length == 4
s1
and s2
consist only of lowercase English letters.You are given two strings s1
and s2
, both of length n
, consisting of lowercase English letters.
You can apply the following operation on any of the two strings any number of times:
\n\ni
and j
such that i < j
and the difference j - i
is even, then swap the two characters at those indices in the string.Return true
if you can make the strings s1
and s2
equal, and false
otherwise.
\n
Example 1:
\n\n\nInput: s1 = "abcdba", s2 = "cabdab"\nOutput: true\nExplanation: We can apply the following operations on s1:\n- Choose the indices i = 0, j = 2. The resulting string is s1 = "cbadba".\n- Choose the indices i = 2, j = 4. The resulting string is s1 = "cbbdaa".\n- Choose the indices i = 1, j = 5. The resulting string is s1 = "cabdab" = s2.\n\n\n
Example 2:
\n\n\nInput: s1 = "abe", s2 = "bea"\nOutput: false\nExplanation: It is not possible to make the two strings equal.\n\n\n
\n
Constraints:
\n\nn == s1.length == s2.length
1 <= n <= 105
s1
and s2
consist only of lowercase English letters.You are given an integer array nums
and two positive integers m
and k
.
Return the maximum sum out of all almost unique subarrays of length k
of nums
. If no such subarray exists, return 0
.
A subarray of nums
is almost unique if it contains at least m
distinct elements.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,6,7,3,1,7], m = 3, k = 4\nOutput: 18\nExplanation: There are 3 almost unique subarrays of size k = 4
. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18.\n
\n\nExample 2:
\n\n\nInput: nums = [5,9,9,2,4,5,4], m = 1, k = 3\nOutput: 23\nExplanation: There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,1,2,1,2,1], m = 3, k = 3\nOutput: 0\nExplanation: There are no subarrays of size\n\nk = 3
that contain at leastm = 3
distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0.\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
1 <= m <= k <= nums.length
1 <= nums[i] <= 109
You are given a string s
and an integer k
.
A k-subsequence is a subsequence of s
, having length k
, and all its characters are unique, i.e., every character occurs once.
Let f(c)
denote the number of times the character c
occurs in s
.
The beauty of a k-subsequence is the sum of f(c)
for every character c
in the k-subsequence.
For example, consider s = "abbbdd"
and k = 2
:
f('a') = 1
, f('b') = 3
, f('d') = 2
s
are:\n\t"abbbdd"
-> "ab"
having a beauty of f('a') + f('b') = 4
"abbbdd"
-> "ad"
having a beauty of f('a') + f('d') = 3
"abbbdd"
-> "bd"
having a beauty of f('b') + f('d') = 5
Return an integer denoting the number of k-subsequences whose beauty is the maximum among all k-subsequences. Since the answer may be too large, return it modulo 109 + 7
.
A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.
\n\nNotes
\n\nf(c)
is the number of times a character c
occurs in s
, not a k-subsequence.\n
Example 1:
\n\n\nInput: s = "bcca", k = 2\nOutput: 4\nExplanation: From s we have f('a') = 1, f('b') = 1, and f('c') = 2.\nThe k-subsequences of s are: \nbcca having a beauty of f('b') + f('c') = 3 \nbcca having a beauty of f('b') + f('c') = 3 \nbcca having a beauty of f('b') + f('a') = 2 \nbcca having a beauty of f('c') + f('a') = 3\nbcca having a beauty of f('c') + f('a') = 3 \nThere are 4 k-subsequences that have the maximum beauty, 3. \nHence, the answer is 4. \n
\n\nExample 2:
\n\n\nInput: s = "abbcd", k = 4\nOutput: 2\nExplanation: From s we have f('a') = 1, f('b') = 2, f('c') = 1, and f('d') = 1. \nThe k-subsequences of s are: \nabbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5\nabbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5 \nThere are 2 k-subsequences that have the maximum beauty, 5. \nHence, the answer is 2. \n\n\n
\n
Constraints:
\n\n1 <= s.length <= 2 * 105
1 <= k <= s.length
s
consists only of lowercase English letters.You are given two positive integers low
and high
.
An integer x
consisting of 2 * n
digits is symmetric if the sum of the first n
digits of x
is equal to the sum of the last n
digits of x
. Numbers with an odd number of digits are never symmetric.
Return the number of symmetric integers in the range [low, high]
.
\n
Example 1:
\n\n\nInput: low = 1, high = 100\nOutput: 9\nExplanation: There are 9 symmetric integers between 1 and 100: 11, 22, 33, 44, 55, 66, 77, 88, and 99.\n\n\n
Example 2:
\n\n\nInput: low = 1200, high = 1230\nOutput: 4\nExplanation: There are 4 symmetric integers between 1200 and 1230: 1203, 1212, 1221, and 1230.\n\n\n
\n
Constraints:
\n\n1 <= low <= high <= 104
You are given a 0-indexed string num
representing a non-negative integer.
In one operation, you can pick any digit of num
and delete it. Note that if you delete all the digits of num
, num
becomes 0
.
Return the minimum number of operations required to make num
special.
An integer x
is considered special if it is divisible by 25
.
\n
Example 1:
\n\n\nInput: num = "2245047"\nOutput: 2\nExplanation: Delete digits num[5] and num[6]. The resulting number is "22450" which is special since it is divisible by 25.\nIt can be shown that 2 is the minimum number of operations required to get a special number.\n\n
Example 2:
\n\n\nInput: num = "2908305"\nOutput: 3\nExplanation: Delete digits num[3], num[4], and num[6]. The resulting number is "2900" which is special since it is divisible by 25.\nIt can be shown that 3 is the minimum number of operations required to get a special number.\n\n
Example 3:
\n\n\nInput: num = "10"\nOutput: 1\nExplanation: Delete digit num[0]. The resulting number is "0" which is special since it is divisible by 25.\nIt can be shown that 1 is the minimum number of operations required to get a special number.\n\n\n\n
\n
Constraints:
\n\n1 <= num.length <= 100
num
only consists of digits '0'
through '9'
.num
does not contain any leading zeros.You are given a 0-indexed integer array nums
, an integer modulo
, and an integer k
.
Your task is to find the count of subarrays that are interesting.
\n\nA subarray nums[l..r]
is interesting if the following condition holds:
cnt
be the number of indices i
in the range [l, r]
such that nums[i] % modulo == k
. Then, cnt % modulo == k
.Return an integer denoting the count of interesting subarrays.
\n\nNote: A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,2,4], modulo = 2, k = 1\nOutput: 3\nExplanation: In this example the interesting subarrays are: \nThe subarray nums[0..0] which is [3]. \n- There is only one index, i = 0, in the range [0, 0] that satisfies nums[i] % modulo == k. \n- Hence, cnt = 1 and cnt % modulo == k. \nThe subarray nums[0..1] which is [3,2].\n- There is only one index, i = 0, in the range [0, 1] that satisfies nums[i] % modulo == k. \n- Hence, cnt = 1 and cnt % modulo == k.\nThe subarray nums[0..2] which is [3,2,4]. \n- There is only one index, i = 0, in the range [0, 2] that satisfies nums[i] % modulo == k. \n- Hence, cnt = 1 and cnt % modulo == k. \nIt can be shown that there are no other interesting subarrays. So, the answer is 3.\n\n
Example 2:
\n\n\nInput: nums = [3,1,9,6], modulo = 3, k = 0\nOutput: 2\nExplanation: In this example the interesting subarrays are: \nThe subarray nums[0..3] which is [3,1,9,6]. \n- There are three indices, i = 0, 2, 3, in the range [0, 3] that satisfy nums[i] % modulo == k. \n- Hence, cnt = 3 and cnt % modulo == k. \nThe subarray nums[1..1] which is [1]. \n- There is no index, i, in the range [1, 1] that satisfies nums[i] % modulo == k. \n- Hence, cnt = 0 and cnt % modulo == k. \nIt can be shown that there are no other interesting subarrays. So, the answer is 2.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= modulo <= 109
0 <= k < modulo
There is an undirected tree with n
nodes labeled from 0
to n - 1
. You are given the integer n
and a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi, wi]
indicates that there is an edge between nodes ui
and vi
with weight wi
in the tree.
You are also given a 2D integer array queries
of length m
, where queries[i] = [ai, bi]
. For each query, find the minimum number of operations required to make the weight of every edge on the path from ai
to bi
equal. In one operation, you can choose any edge of the tree and change its weight to any value.
Note that:
\n\nai
to bi
is a sequence of distinct nodes starting with node ai
and ending with node bi
such that every two adjacent nodes in the sequence share an edge in the tree.Return an array answer
of length m
where answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: n = 7, edges = [[0,1,1],[1,2,1],[2,3,1],[3,4,2],[4,5,2],[5,6,2]], queries = [[0,3],[3,6],[2,6],[0,6]]\nOutput: [0,0,1,3]\nExplanation: In the first query, all the edges in the path from 0 to 3 have a weight of 1. Hence, the answer is 0.\nIn the second query, all the edges in the path from 3 to 6 have a weight of 2. Hence, the answer is 0.\nIn the third query, we change the weight of edge [2,3] to 2. After this operation, all the edges in the path from 2 to 6 have a weight of 2. Hence, the answer is 1.\nIn the fourth query, we change the weights of edges [0,1], [1,2] and [2,3] to 2. After these operations, all the edges in the path from 0 to 6 have a weight of 2. Hence, the answer is 3.\nFor each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi.\n\n\n
Example 2:
\n\nInput: n = 8, edges = [[1,2,6],[1,3,4],[2,4,6],[2,5,3],[3,6,6],[3,0,8],[7,0,2]], queries = [[4,6],[0,4],[6,5],[7,4]]\nOutput: [1,2,2,3]\nExplanation: In the first query, we change the weight of edge [1,3] to 6. After this operation, all the edges in the path from 4 to 6 have a weight of 6. Hence, the answer is 1.\nIn the second query, we change the weight of edges [0,3] and [3,1] to 6. After these operations, all the edges in the path from 0 to 4 have a weight of 6. Hence, the answer is 2.\nIn the third query, we change the weight of edges [1,3] and [5,2] to 6. After these operations, all the edges in the path from 6 to 5 have a weight of 6. Hence, the answer is 2.\nIn the fourth query, we change the weights of edges [0,7], [0,3] and [1,3] to 6. After these operations, all the edges in the path from 7 to 4 have a weight of 6. Hence, the answer is 3.\nFor each queries[i], it can be shown that answer[i] is the minimum number of operations needed to equalize all the edge weights in the path from ai to bi.\n\n\n
\n
Constraints:
\n\n1 <= n <= 104
edges.length == n - 1
edges[i].length == 3
0 <= ui, vi < n
1 <= wi <= 26
edges
represents a valid tree.1 <= queries.length == m <= 2 * 104
queries[i].length == 2
0 <= ai, bi < n
You are given a 0-indexed 2D integer array nums
representing the coordinates of the cars parking on a number line. For any index i
, nums[i] = [starti, endi]
where starti
is the starting point of the ith
car and endi
is the ending point of the ith
car.
Return the number of integer points on the line that are covered with any part of a car.
\n\n\n
Example 1:
\n\n\nInput: nums = [[3,6],[1,5],[4,7]]\nOutput: 7\nExplanation: All the points from 1 to 7 intersect at least one car, therefore the answer would be 7.\n\n\n
Example 2:
\n\n\nInput: nums = [[1,3],[5,8]]\nOutput: 7\nExplanation: Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
nums[i].length == 2
1 <= starti <= endi <= 100
You are given four integers sx
, sy
, fx
, fy
, and a non-negative integer t
.
In an infinite 2D grid, you start at the cell (sx, sy)
. Each second, you must move to any of its adjacent cells.
Return true
if you can reach cell (fx, fy)
after exactly t
seconds, or false
otherwise.
A cell's adjacent cells are the 8 cells around it that share at least one corner with it. You can visit the same cell several times.
\n\n\n
Example 1:
\n\nInput: sx = 2, sy = 4, fx = 7, fy = 7, t = 6\nOutput: true\nExplanation: Starting at cell (2, 4), we can reach cell (7, 7) in exactly 6 seconds by going through the cells depicted in the picture above. \n\n\n
Example 2:
\n\nInput: sx = 3, sy = 1, fx = 7, fy = 3, t = 3\nOutput: false\nExplanation: Starting at cell (3, 1), it takes at least 4 seconds to reach cell (7, 3) by going through the cells depicted in the picture above. Hence, we cannot reach cell (7, 3) at the third second.\n\n\n
\n
Constraints:
\n\n1 <= sx, sy, fx, fy <= 109
0 <= t <= 109
You are given a 0-indexed 2D integer matrix grid
of size 3 * 3
, representing the number of stones in each cell. The grid contains exactly 9
stones, and there can be multiple stones in a single cell.
In one move, you can move a single stone from its current cell to any other cell if the two cells share a side.
\n\nReturn the minimum number of moves required to place one stone in each cell.
\n\n\n
Example 1:
\n\nInput: grid = [[1,1,0],[1,1,1],[1,2,1]]\nOutput: 3\nExplanation: One possible sequence of moves to place one stone in each cell is: \n1- Move one stone from cell (2,1) to cell (2,2).\n2- Move one stone from cell (2,2) to cell (1,2).\n3- Move one stone from cell (1,2) to cell (0,2).\nIn total, it takes 3 moves to place one stone in each cell of the grid.\nIt can be shown that 3 is the minimum number of moves required to place one stone in each cell.\n\n\n
Example 2:
\n\nInput: grid = [[1,3,0],[1,0,0],[1,0,3]]\nOutput: 4\nExplanation: One possible sequence of moves to place one stone in each cell is:\n1- Move one stone from cell (0,1) to cell (0,2).\n2- Move one stone from cell (0,1) to cell (1,1).\n3- Move one stone from cell (2,2) to cell (1,2).\n4- Move one stone from cell (2,2) to cell (2,1).\nIn total, it takes 4 moves to place one stone in each cell of the grid.\nIt can be shown that 4 is the minimum number of moves required to place one stone in each cell.\n\n\n
\n
Constraints:
\n\ngrid.length == grid[i].length == 3
0 <= grid[i][j] <= 9
grid
is equal to 9
.You are given two strings s
and t
of equal length n
. You can perform the following operation on the string s
:
s
of length l
where 0 < l < n
and append it at the start of s
.s = 'abcd'
then in one operation you can remove the suffix 'cd'
and append it in front of s
making s = 'cdab'
.You are also given an integer k
. Return the number of ways in which s
can be transformed into t
in exactly k
operations.
Since the answer can be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: s = "abcd", t = "cdab", k = 2\nOutput: 2\nExplanation: \nFirst way:\nIn first operation, choose suffix from index = 3, so resulting s = "dabc".\nIn second operation, choose suffix from index = 3, so resulting s = "cdab".\n\nSecond way:\nIn first operation, choose suffix from index = 1, so resulting s = "bcda".\nIn second operation, choose suffix from index = 1, so resulting s = "cdab".\n\n\n
Example 2:
\n\n\nInput: s = "ababab", t = "ababab", k = 1\nOutput: 2\nExplanation: \nFirst way:\nChoose suffix from index = 2, so resulting s = "ababab".\n\nSecond way:\nChoose suffix from index = 4, so resulting s = "ababab".\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 5 * 105
1 <= k <= 1015
s.length == t.length
s
and t
consist of only lowercase English alphabets.You are given a 0-indexed array nums
of length n
containing distinct positive integers. Return the minimum number of right shifts required to sort nums
and -1
if this is not possible.
A right shift is defined as shifting the element at index i
to index (i + 1) % n
, for all indices.
\n
Example 1:
\n\n\nInput: nums = [3,4,5,1,2]\nOutput: 2\nExplanation: \nAfter the first right shift, nums = [2,3,4,5,1].\nAfter the second right shift, nums = [1,2,3,4,5].\nNow nums is sorted; therefore the answer is 2.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,5]\nOutput: 0\nExplanation: nums is already sorted therefore, the answer is 0.\n\n
Example 3:
\n\n\nInput: nums = [2,1,4]\nOutput: -1\nExplanation: It's impossible to sort the array using right shifts.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
nums
contains distinct integers.Given an integer array num
sorted in non-decreasing order.
You can perform the following operation any number of times:
\n\ni
and j
, where nums[i] < nums[j]
.i
and j
from nums
. The remaining elements retain their original order, and the array is re-indexed.Return the minimum length of nums
after applying the operation zero or more times.
\n
Example 1:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 0
\n\nExplanation:
\n\nExample 2:
\n\nInput: nums = [1,1,2,2,3,3]
\n\nOutput: 0
\n\nExplanation:
\n\nExample 3:
\n\nInput: nums = [1000000000,1000000000]
\n\nOutput: 2
\n\nExplanation:
\n\nSince both numbers are equal, they cannot be removed.
\nExample 4:
\n\nInput: nums = [2,3,4,4,4]
\n\nOutput: 1
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
nums
is sorted in non-decreasing order.You are given a 2D integer array coordinates
and an integer k
, where coordinates[i] = [xi, yi]
are the coordinates of the ith
point in a 2D plane.
We define the distance between two points (x1, y1)
and (x2, y2)
as (x1 XOR x2) + (y1 XOR y2)
where XOR
is the bitwise XOR
operation.
Return the number of pairs (i, j)
such that i < j
and the distance between points i
and j
is equal to k
.
\n
Example 1:
\n\n\nInput: coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5\nOutput: 2\nExplanation: We can choose the following pairs:\n- (0,1): Because we have (1 XOR 4) + (2 XOR 2) = 5.\n- (2,3): Because we have (1 XOR 5) + (3 XOR 2) = 5.\n\n\n
Example 2:
\n\n\nInput: coordinates = [[1,3],[1,3],[1,3],[1,3],[1,3]], k = 0\nOutput: 10\nExplanation: Any two chosen pairs will have a distance of 0. There are 10 ways to choose two pairs.\n\n\n
\n
Constraints:
\n\n2 <= coordinates.length <= 50000
0 <= xi, yi <= 106
0 <= k <= 100
There is a simple directed graph with n
nodes labeled from 0
to n - 1
. The graph would form a tree if its edges were bi-directional.
You are given an integer n
and a 2D integer array edges
, where edges[i] = [ui, vi]
represents a directed edge going from node ui
to node vi
.
An edge reversal changes the direction of an edge, i.e., a directed edge going from node ui
to node vi
becomes a directed edge going from node vi
to node ui
.
For every node i
in the range [0, n - 1]
, your task is to independently calculate the minimum number of edge reversals required so it is possible to reach any other node starting from node i
through a sequence of directed edges.
Return an integer array answer
, where answer[i]
is the minimum number of edge reversals required so it is possible to reach any other node starting from node i
through a sequence of directed edges.
\n
Example 1:
\n\n\nInput: n = 4, edges = [[2,0],[2,1],[1,3]]\nOutput: [1,1,0,2]\nExplanation: The image above shows the graph formed by the edges.\nFor node 0: after reversing the edge [2,0], it is possible to reach any other node starting from node 0.\nSo, answer[0] = 1.\nFor node 1: after reversing the edge [2,1], it is possible to reach any other node starting from node 1.\nSo, answer[1] = 1.\nFor node 2: it is already possible to reach any other node starting from node 2.\nSo, answer[2] = 0.\nFor node 3: after reversing the edges [1,3] and [2,1], it is possible to reach any other node starting from node 3.\nSo, answer[3] = 2.\n\n\n
Example 2:
\n\n\nInput: n = 3, edges = [[1,2],[2,0]]\nOutput: [2,0,1]\nExplanation: The image above shows the graph formed by the edges.\nFor node 0: after reversing the edges [2,0] and [1,2], it is possible to reach any other node starting from node 0.\nSo, answer[0] = 2.\nFor node 1: it is already possible to reach any other node starting from node 1.\nSo, answer[1] = 0.\nFor node 2: after reversing the edge [1, 2], it is possible to reach any other node starting from node 2.\nSo, answer[2] = 1.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ui == edges[i][0] < n
0 <= vi == edges[i][1] < n
ui != vi
You are given a 0-indexed integer array nums
and an integer k
.
Return an integer that denotes the sum of elements in nums
whose corresponding indices have exactly k
set bits in their binary representation.
The set bits in an integer are the 1
's present when it is written in binary.
21
is 10101
, which has 3
set bits.\n
Example 1:
\n\n\nInput: nums = [5,10,1,5,2], k = 1\nOutput: 13\nExplanation: The binary representation of the indices are: \n0 = 0002\n1 = 0012\n2 = 0102\n3 = 0112\n4 = 1002 \nIndices 1, 2, and 4 have k = 1 set bits in their binary representation.\nHence, the answer is nums[1] + nums[2] + nums[4] = 13.\n\n
Example 2:
\n\n\nInput: nums = [4,3,2,1], k = 2\nOutput: 1\nExplanation: The binary representation of the indices are:\n0 = 002\n1 = 012\n2 = 102\n3 = 112\nOnly index 3 has k = 2 set bits in its binary representation.\nHence, the answer is nums[3] = 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 105
0 <= k <= 10
You are given a 0-indexed integer array nums
of length n
where n
is the total number of students in the class. The class teacher tries to select a group of students so that all the students remain happy.
The ith
student will become happy if one of these two conditions is met:
nums[i]
.nums[i]
.Return the number of ways to select a group of students so that everyone remains happy.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,1]\nOutput: 2\nExplanation: \nThe two possible ways are:\nThe class teacher selects no student.\nThe class teacher selects both students to form the group. \nIf the class teacher selects just one student to form a group then the both students will not be happy. Therefore, there are only two possible ways.\n\n\n
Example 2:
\n\n\nInput: nums = [6,0,3,3,6,7,2,7]\nOutput: 3\nExplanation: \nThe three possible ways are:\nThe class teacher selects the student with index = 1 to form the group.\nThe class teacher selects the students with index = 1, 2, 3, 6 to form the group.\nThe class teacher selects all the students to form the group.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] < nums.length
You are the owner of a company that creates alloys using various types of metals. There are n
different types of metals available, and you have access to k
machines that can be used to create alloys. Each machine requires a specific amount of each metal type to create an alloy.
For the ith
machine to create an alloy, it needs composition[i][j]
units of metal of type j
. Initially, you have stock[i]
units of metal type i
, and purchasing one unit of metal type i
costs cost[i]
coins.
Given integers n
, k
, budget
, a 1-indexed 2D array composition
, and 1-indexed arrays stock
and cost
, your goal is to maximize the number of alloys the company can create while staying within the budget of budget
coins.
All alloys must be created with the same machine.
\n\nReturn the maximum number of alloys that the company can create.
\n\n\n
Example 1:
\n\n\nInput: n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,0], cost = [1,2,3]\nOutput: 2\nExplanation: It is optimal to use the 1st machine to create alloys.\nTo create 2 alloys we need to buy the:\n- 2 units of metal of the 1st type.\n- 2 units of metal of the 2nd type.\n- 2 units of metal of the 3rd type.\nIn total, we need 2 * 1 + 2 * 2 + 2 * 3 = 12 coins, which is smaller than or equal to budget = 15.\nNotice that we have 0 units of metal of each type and we have to buy all the required units of metal.\nIt can be proven that we can create at most 2 alloys.\n\n\n
Example 2:
\n\n\nInput: n = 3, k = 2, budget = 15, composition = [[1,1,1],[1,1,10]], stock = [0,0,100], cost = [1,2,3]\nOutput: 5\nExplanation: It is optimal to use the 2nd machine to create alloys.\nTo create 5 alloys we need to buy:\n- 5 units of metal of the 1st type.\n- 5 units of metal of the 2nd type.\n- 0 units of metal of the 3rd type.\nIn total, we need 5 * 1 + 5 * 2 + 0 * 3 = 15 coins, which is smaller than or equal to budget = 15.\nIt can be proven that we can create at most 5 alloys.\n\n\n
Example 3:
\n\n\nInput: n = 2, k = 3, budget = 10, composition = [[2,1],[1,2],[1,1]], stock = [1,1], cost = [5,5]\nOutput: 2\nExplanation: It is optimal to use the 3rd machine to create alloys.\nTo create 2 alloys we need to buy the:\n- 1 unit of metal of the 1st type.\n- 1 unit of metal of the 2nd type.\nIn total, we need 1 * 5 + 1 * 5 = 10 coins, which is smaller than or equal to budget = 10.\nIt can be proven that we can create at most 2 alloys.\n\n\n
\n
Constraints:
\n\n1 <= n, k <= 100
0 <= budget <= 108
composition.length == k
composition[i].length == n
1 <= composition[i][j] <= 100
stock.length == cost.length == n
0 <= stock[i] <= 108
1 <= cost[i] <= 100
You are given a 1-indexed array nums
. Your task is to select a complete subset from nums
where every pair of selected indices multiplied is a perfect square,. i. e. if you select ai
and aj
, i * j
must be a perfect square.
Return the sum of the complete subset with the maximum sum.
\n\n\n
Example 1:
\n\nInput: nums = [8,7,3,5,7,2,4,9]
\n\nOutput: 16
\n\nExplanation:
\n\nWe select elements at indices 2 and 8 and 2 * 8
is a perfect square.
Example 2:
\n\nInput: nums = [8,10,3,8,1,13,7,9,4]
\n\nOutput: 20
\n\nExplanation:
\n\nWe select elements at indices 1, 4, and 9. 1 * 4
, 1 * 9
, 4 * 9
are perfect squares.
\n
Constraints:
\n\n1 <= n == nums.length <= 104
1 <= nums[i] <= 109
You are given a binary string s
that contains at least one '1'
.
You have to rearrange the bits in such a way that the resulting binary number is the maximum odd binary number that can be created from this combination.
\n\nReturn a string representing the maximum odd binary number that can be created from the given combination.
\n\nNote that the resulting string can have leading zeros.
\n\n\n
Example 1:
\n\n\nInput: s = "010"\nOutput: "001"\nExplanation: Because there is just one '1', it must be in the last position. So the answer is "001".\n\n\n
Example 2:
\n\n\nInput: s = "0101"\nOutput: "1001"\nExplanation: One of the '1's must be in the last position. The maximum number that can be made with the remaining digits is "100". So the answer is "1001".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of '0'
and '1'
.s
contains at least one '1'
.You are given an array heights
of n
integers representing the number of bricks in n
consecutive towers. Your task is to remove some bricks to form a mountain-shaped tower arrangement. In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers and then non-increasing.
Return the maximum possible sum of heights of a mountain-shaped tower arrangement.
\n\n\n
Example 1:
\n\nInput: heights = [5,3,4,1,1]
\n\nOutput: 13
\n\nExplanation:
\n\nWe remove some bricks to make heights = [5,3,3,1,1]
, the peak is at index 0.
Example 2:
\n\nInput: heights = [6,5,3,9,2,7]
\n\nOutput: 22
\n\nExplanation:
\n\nWe remove some bricks to make heights = [3,3,3,9,2,2]
, the peak is at index 3.
Example 3:
\n\nInput: heights = [3,2,5,5,2,3]
\n\nOutput: 18
\n\nExplanation:
\n\nWe remove some bricks to make heights = [2,2,5,5,2,2]
, the peak is at index 2 or 3.
\n
Constraints:
\n\n1 <= n == heights.length <= 103
1 <= heights[i] <= 109
You are given a 0-indexed array maxHeights
of n
integers.
You are tasked with building n
towers in the coordinate line. The ith
tower is built at coordinate i
and has a height of heights[i]
.
A configuration of towers is beautiful if the following conditions hold:
\n\n1 <= heights[i] <= maxHeights[i]
heights
is a mountain array.Array heights
is a mountain if there exists an index i
such that:
0 < j <= i
, heights[j - 1] <= heights[j]
i <= k < n - 1
, heights[k + 1] <= heights[k]
Return the maximum possible sum of heights of a beautiful configuration of towers.
\n\n\n
Example 1:
\n\n\nInput: maxHeights = [5,3,4,1,1]\nOutput: 13\nExplanation: One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since:\n- 1 <= heights[i] <= maxHeights[i] \n- heights is a mountain of peak i = 0.\nIt can be shown that there exists no other beautiful configuration with a sum of heights greater than 13.\n\n
Example 2:
\n\n\nInput: maxHeights = [6,5,3,9,2,7]\nOutput: 22\nExplanation: One beautiful configuration with a maximum sum is heights = [3,3,3,9,2,2]. This configuration is beautiful since:\n- 1 <= heights[i] <= maxHeights[i]\n- heights is a mountain of peak i = 3.\nIt can be shown that there exists no other beautiful configuration with a sum of heights greater than 22.\n\n
Example 3:
\n\n\nInput: maxHeights = [3,2,5,5,2,3]\nOutput: 18\nExplanation: One beautiful configuration with a maximum sum is heights = [2,2,5,5,2,2]. This configuration is beautiful since:\n- 1 <= heights[i] <= maxHeights[i]\n- heights is a mountain of peak i = 2. \nNote that, for this configuration, i = 3 can also be considered a peak.\nIt can be shown that there exists no other beautiful configuration with a sum of heights greater than 18.\n\n\n
\n
Constraints:
\n\n1 <= n == maxHeights.length <= 105
1 <= maxHeights[i] <= 109
There is an undirected tree with n
nodes labeled from 1
to n
. You are given the integer n
and a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the tree.
Return the number of valid paths in the tree.
\n\nA path (a, b)
is valid if there exists exactly one prime number among the node labels in the path from a
to b
.
Note that:
\n\n(a, b)
is a sequence of distinct nodes starting with node a
and ending with node b
such that every two adjacent nodes in the sequence share an edge in the tree.(a, b)
and path (b, a)
are considered the same and counted only once.\n
Example 1:
\n\nInput: n = 5, edges = [[1,2],[1,3],[2,4],[2,5]]\nOutput: 4\nExplanation: The pairs with exactly one prime number on the path between them are: \n- (1, 2) since the path from 1 to 2 contains prime number 2. \n- (1, 3) since the path from 1 to 3 contains prime number 3.\n- (1, 4) since the path from 1 to 4 contains prime number 2.\n- (2, 4) since the path from 2 to 4 contains prime number 2.\nIt can be shown that there are only 4 valid paths.\n\n\n
Example 2:
\n\nInput: n = 6, edges = [[1,2],[1,3],[2,4],[3,5],[3,6]]\nOutput: 6\nExplanation: The pairs with exactly one prime number on the path between them are: \n- (1, 2) since the path from 1 to 2 contains prime number 2.\n- (1, 3) since the path from 1 to 3 contains prime number 3.\n- (1, 4) since the path from 1 to 4 contains prime number 2.\n- (1, 6) since the path from 1 to 6 contains prime number 3.\n- (2, 4) since the path from 2 to 4 contains prime number 2.\n- (3, 6) since the path from 3 to 6 contains prime number 3.\nIt can be shown that there are only 6 valid paths.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
edges
represent a valid tree.You are given an array nums
of positive integers and an integer k
.
In one operation, you can remove the last element of the array and add it to your collection.
\n\nReturn the minimum number of operations needed to collect elements 1, 2, ..., k
.
\n
Example 1:
\n\n\nInput: nums = [3,1,5,4,2], k = 2\nOutput: 4\nExplanation: After 4 operations, we collect elements 2, 4, 5, and 1, in this order. Our collection contains elements 1 and 2. Hence, the answer is 4.\n\n\n
Example 2:
\n\n\nInput: nums = [3,1,5,4,2], k = 5\nOutput: 5\nExplanation: After 5 operations, we collect elements 2, 4, 5, 1, and 3, in this order. Our collection contains elements 1 through 5. Hence, the answer is 5.\n\n\n
Example 3:
\n\n\nInput: nums = [3,2,5,3,1], k = 3\nOutput: 4\nExplanation: After 4 operations, we collect elements 1, 3, 5, and 2, in this order. Our collection contains elements 1 through 3. Hence, the answer is 4.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= nums.length
1 <= k <= nums.length
1, 2, ..., k
.You are given a 0-indexed array nums
consisting of positive integers.
There are two types of operations that you can apply on the array any number of times:
\n\nReturn the minimum number of operations required to make the array empty, or -1
if it is not possible.
\n
Example 1:
\n\n\nInput: nums = [2,3,3,2,2,4,2,3,4]\nOutput: 4\nExplanation: We can apply the following operations to make the array empty:\n- Apply the first operation on the elements at indices 0 and 3. The resulting array is nums = [3,3,2,4,2,3,4].\n- Apply the first operation on the elements at indices 2 and 4. The resulting array is nums = [3,3,4,3,4].\n- Apply the second operation on the elements at indices 0, 1, and 3. The resulting array is nums = [4,4].\n- Apply the first operation on the elements at indices 0 and 1. The resulting array is nums = [].\nIt can be shown that we cannot make the array empty in less than 4 operations.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,2,2,3,3]\nOutput: -1\nExplanation: It is impossible to empty the array.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 106
\n
Note: This question is the same as 2244: Minimum Rounds to Complete All Tasks.
\n", - "likes": 1401, + "likes": 1414, "dislikes": 68, - "stats": "{\"totalAccepted\": \"187K\", \"totalSubmission\": \"302.1K\", \"totalAcceptedRaw\": 187049, \"totalSubmissionRaw\": 302075, \"acRate\": \"61.9%\"}", + "stats": "{\"totalAccepted\": \"191.4K\", \"totalSubmission\": \"309.4K\", \"totalAcceptedRaw\": 191351, \"totalSubmissionRaw\": 309407, \"acRate\": \"61.8%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [], @@ -108235,9 +108498,9 @@ "questionFrontendId": "2871", "title": "Split Array Into Maximum Number of Subarrays", "content": "You are given an array nums
consisting of non-negative integers.
We define the score of subarray nums[l..r]
such that l <= r
as nums[l] AND nums[l + 1] AND ... AND nums[r]
where AND is the bitwise AND
operation.
Consider splitting the array into one or more subarrays such that the following conditions are satisfied:
\n\nReturn the maximum number of subarrays in a split that satisfies the conditions above.
\n\nA subarray is a contiguous part of an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,0,2,0,1,2]\nOutput: 3\nExplanation: We can split the array into the following subarrays:\n- [1,0]. The score of this subarray is 1 AND 0 = 0.\n- [2,0]. The score of this subarray is 2 AND 0 = 0.\n- [1,2]. The score of this subarray is 1 AND 2 = 0.\nThe sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain.\nIt can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3.\n\n\n
Example 2:
\n\n\nInput: nums = [5,7,1,3]\nOutput: 1\nExplanation: We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain.\nIt can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 106
There is an undirected tree with n
nodes labeled from 0
to n - 1
. You are given the integer n
and a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
You are also given a 0-indexed integer array values
of length n
, where values[i]
is the value associated with the ith
node, and an integer k
.
A valid split of the tree is obtained by removing any set of edges, possibly empty, from the tree such that the resulting components all have values that are divisible by k
, where the value of a connected component is the sum of the values of its nodes.
Return the maximum number of components in any valid split.
\n\n\n
Example 1:
\n\nInput: n = 5, edges = [[0,2],[1,2],[1,3],[2,4]], values = [1,8,1,4,4], k = 6\nOutput: 2\nExplanation: We remove the edge connecting node 1 with 2. The resulting split is valid because:\n- The value of the component containing nodes 1 and 3 is values[1] + values[3] = 12.\n- The value of the component containing nodes 0, 2, and 4 is values[0] + values[2] + values[4] = 6.\nIt can be shown that no other valid split has more than 2 connected components.\n\n
Example 2:
\n\nInput: n = 7, edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [3,0,6,1,5,2,1], k = 3\nOutput: 3\nExplanation: We remove the edge connecting node 0 with 2, and the edge connecting node 0 with 1. The resulting split is valid because:\n- The value of the component containing node 0 is values[0] = 3.\n- The value of the component containing nodes 2, 5, and 6 is values[2] + values[5] + values[6] = 9.\n- The value of the component containing nodes 1, 3, and 4 is values[1] + values[3] + values[4] = 6.\nIt can be shown that no other valid split has more than 3 connected components.\n\n\n
\n
Constraints:
\n\n1 <= n <= 3 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
values.length == n
0 <= values[i] <= 109
1 <= k <= 109
values
is divisible by k
.edges
represents a valid tree.You are given a 0-indexed integer array nums
.
Return the maximum value over all triplets of indices (i, j, k)
such that i < j < k
. If all such triplets have a negative value, return 0
.
The value of a triplet of indices (i, j, k)
is equal to (nums[i] - nums[j]) * nums[k]
.
\n
Example 1:
\n\n\nInput: nums = [12,6,1,2,7]\nOutput: 77\nExplanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.\nIt can be shown that there are no ordered triplets of indices with a value greater than 77. \n\n\n
Example 2:
\n\n\nInput: nums = [1,10,3,4,19]\nOutput: 133\nExplanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.\nIt can be shown that there are no ordered triplets of indices with a value greater than 133.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 100
1 <= nums[i] <= 106
You are given a 0-indexed integer array nums
.
Return the maximum value over all triplets of indices (i, j, k)
such that i < j < k
. If all such triplets have a negative value, return 0
.
The value of a triplet of indices (i, j, k)
is equal to (nums[i] - nums[j]) * nums[k]
.
\n
Example 1:
\n\n\nInput: nums = [12,6,1,2,7]\nOutput: 77\nExplanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.\nIt can be shown that there are no ordered triplets of indices with a value greater than 77. \n\n\n
Example 2:
\n\n\nInput: nums = [1,10,3,4,19]\nOutput: 133\nExplanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.\nIt can be shown that there are no ordered triplets of indices with a value greater than 133.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
1 <= nums[i] <= 106
prefix_max[i] = max(nums[0], nums[1], \u2026, nums[i])
and the suffix maximum array, suffix_max[i] = max(nums[i], nums[i + 1], \u2026, nums[i - 1])
.",
+ "Preprocess the prefix maximum array, prefix_max[i] = max(nums[0], nums[1], \u2026, nums[i])
and the suffix maximum array, suffix_max[i] = max(nums[i], nums[i + 1], \u2026, nums[n - 1])
.",
"For each index j
, find two indices i
and k
such that i < j < k
and (nums[i] - nums[j]) * nums[k]
is the maximum, using the prefix and suffix maximum arrays.",
"For index j
, the maximum triplet value is (prefix_max[j - 1] - nums[j]) * suffix_max[j + 1]
."
],
@@ -108360,8 +108626,11 @@
"companyTags": null,
"difficulty": "Medium",
"isPaidOnly": false,
- "solution": null,
- "hasSolution": false,
+ "solution": {
+ "canSeeDetail": true,
+ "content": "[TOC]\n\n## Solution\n\n--- \n\n### Approach 1: Greedy + Prefix Suffix Array\n\n#### Intuition\n\nLet the length of the array $\\textit{nums}$ be $n$. According to the value formula $(\\textit{nums}[i] - \\textit{nums}[j]) \\times \\textit{nums}[k]$, it can be known that when $j$ is fixed, the maximum value of the triplet is achieved when $\\textit{nums}[i]$ and $\\textit{nums}[k]$ respectively take the maximum values from $[0, j)$ and $[j + 1, n)$. We use $\\textit{leftMax}[j]$ and $\\textit{rightMax}[j]$ to maintain the maximum value of the prefix $[0, j)$ and the maximum value of the suffix $[j + 1, n)$, respectively, and enumerate $j$ in order, calculate the value $(\\textit{leftMax}[j] - \\textit{nums}[j]) \\times \\textit{rightMax}[j]$, and return the maximum value (if all values are negative, return $0$).\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the length of the array $\\textit{nums}$.\n\n- Time complexity: $O(n)$.\n\nDuring the traversal of the array, the prefix and suffix arrays can be maintained, thus achieving a single traversal.\n\n- Space complexity: $O(n)$.\n\nTwo arrays are needed to maintain the maximum and minimum values of the prefixes and suffixes.\n\n### Approach 2: Greedy\n\n#### Intuition\n\nSimilar to approach 1, if we fix $k$, then the value of the triplet is maximized when $\\textit{nums}[i] - \\textit{nums}[j]$ takes the maximum value. We can use $\\textit{imax}$ to maintain the maximum value of $\\textit{nums}[i]$, and $\\textit{dmax}$ to maintain the maximum value of $\\textit{nums}[i] - \\textit{nums}[j]$. During the enumeration of $k$, update $\\textit{dmax}$ and $\\textit{imax}$.\n\n#### Implementation\n\n\n\n#### Complexity Analysis\n\nLet $n$ be the length of the array $\\textit{nums}$.\n\n- Time complexity: $O(n)$.\n\nSimilar to approach 1, in the process of a single traversal, the maximum and minimum values can be maintained.\n\n- Space complexity: $O(1)$.\n\nWe only need two variables to maintain the maximum and minimum values.\n\n---"
+ },
+ "hasSolution": true,
"hasVideoSolution": false,
"url": "https://leetcode.com/problems/maximum-value-of-an-ordered-triplet-ii/"
}
@@ -108374,9 +108643,9 @@
"questionFrontendId": "2875",
"title": "Minimum Size Subarray in Infinite Array",
"content": "You are given a 0-indexed array nums
and an integer target
.
A 0-indexed array infinite_nums
is generated by infinitely appending the elements of nums
to itself.
Return the length of the shortest subarray of the array infinite_nums
with a sum equal to target
. If there is no such subarray return -1
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3], target = 5\nOutput: 2\nExplanation: In this example infinite_nums = [1,2,3,1,2,3,1,2,...].\nThe subarray in the range [1,2], has the sum equal to target = 5 and length = 2.\nIt can be proven that 2 is the shortest length of a subarray with sum equal to target = 5.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,2,3], target = 4\nOutput: 2\nExplanation: In this example infinite_nums = [1,1,1,2,3,1,1,1,2,3,1,1,...].\nThe subarray in the range [4,5], has the sum equal to target = 4 and length = 2.\nIt can be proven that 2 is the shortest length of a subarray with sum equal to target = 4.\n\n\n
Example 3:
\n\n\nInput: nums = [2,4,6,8], target = 3\nOutput: -1\nExplanation: In this example infinite_nums = [2,4,6,8,2,4,6,8,...].\nIt can be proven that there is no subarray with sum equal to target = 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= target <= 109
There is a directed graph consisting of n
nodes numbered from 0
to n - 1
and n
directed edges.
You are given a 0-indexed array edges
where edges[i]
indicates that there is an edge from node i
to node edges[i]
.
Consider the following process on the graph:
\n\nx
and keep visiting other nodes through edges until you reach a node that you have already visited before on this same process.Return an array answer
where answer[i]
is the number of different nodes that you will visit if you perform the process starting from node i
.
\n
Example 1:
\n\nInput: edges = [1,2,0,0]\nOutput: [3,3,3,4]\nExplanation: We perform the process starting from each node in the following way:\n- Starting from node 0, we visit the nodes 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 3.\n- Starting from node 1, we visit the nodes 1 -> 2 -> 0 -> 1. The number of different nodes we visit is 3.\n- Starting from node 2, we visit the nodes 2 -> 0 -> 1 -> 2. The number of different nodes we visit is 3.\n- Starting from node 3, we visit the nodes 3 -> 0 -> 1 -> 2 -> 0. The number of different nodes we visit is 4.\n\n\n
Example 2:
\n\nInput: edges = [1,2,3,4,0]\nOutput: [5,5,5,5,5]\nExplanation: Starting from any node we can visit every node in the graph in the process.\n\n\n
\n
Constraints:
\n\nn == edges.length
2 <= n <= 105
0 <= edges[i] <= n - 1
edges[i] != i
Write a solution to create a DataFrame from a 2D list called student_data
. This 2D list contains the IDs and ages of some students.
The DataFrame should have two columns, student_id
and age
, and be in the same order as the original 2D list.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\nstudent_data:\n\n", - "likes": 228, - "dislikes": 10, - "stats": "{\"totalAccepted\": \"178.1K\", \"totalSubmission\": \"218.8K\", \"totalAcceptedRaw\": 178069, \"totalSubmissionRaw\": 218769, \"acRate\": \"81.4%\"}", + "likes": 261, + "dislikes": 11, + "stats": "{\"totalAccepted\": \"214.3K\", \"totalSubmission\": \"263K\", \"totalAcceptedRaw\": 214282, \"totalSubmissionRaw\": 262991, \"acRate\": \"81.5%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108481,9 +108750,9 @@ "questionFrontendId": "2878", "title": "Get the Size of a DataFrame", "content": "[\n [1, 15],\n [2, 11],\n [3, 11],\n [4, 20]\n]
\nOutput:\n+------------+-----+\n| student_id | age |\n+------------+-----+\n| 1 | 15 |\n| 2 | 11 |\n| 3 | 11 |\n| 4 | 20 |\n+------------+-----+\nExplanation:\nA DataFrame was created on top of student_data, with two columns namedstudent_id
andage
.\n
\nDataFrame players:
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| player_id | int |\n| name | object |\n| age | int |\n| position | object |\n| ... | ... |\n+-------------+--------+\n
\n\nWrite a solution to calculate and display the number of rows and columns of players
.
Return the result as an array:
\n\n[number of rows, number of columns]
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\n+-----------+----------+-----+-------------+--------------------+\n| player_id | name | age | position | team |\n+-----------+----------+-----+-------------+--------------------+\n| 846 | Mason | 21 | Forward | RealMadrid |\n| 749 | Riley | 30 | Winger | Barcelona |\n| 155 | Bob | 28 | Striker | ManchesterUnited |\n| 583 | Isabella | 32 | Goalkeeper | Liverpool |\n| 388 | Zachary | 24 | Midfielder | BayernMunich |\n| 883 | Ava | 23 | Defender | Chelsea |\n| 355 | Violet | 18 | Striker | Juventus |\n| 247 | Thomas | 27 | Striker | ParisSaint-Germain |\n| 761 | Jack | 33 | Midfielder | ManchesterCity |\n| 642 | Charlie | 36 | Center-back | Arsenal |\n+-----------+----------+-----+-------------+--------------------+\nOutput:\n[10, 5]\nExplanation:\nThis DataFrame contains 10 rows and 5 columns.\n\n", - "likes": 118, - "dislikes": 10, - "stats": "{\"totalAccepted\": \"139.2K\", \"totalSubmission\": \"163.6K\", \"totalAcceptedRaw\": 139177, \"totalSubmissionRaw\": 163553, \"acRate\": \"85.1%\"}", + "likes": 140, + "dislikes": 11, + "stats": "{\"totalAccepted\": \"166.6K\", \"totalSubmission\": \"195.6K\", \"totalAcceptedRaw\": 166638, \"totalSubmissionRaw\": 195611, \"acRate\": \"85.2%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108510,9 +108779,9 @@ "questionFrontendId": "2879", "title": "Display the First Three Rows", "content": "
\nDataFrame: employees
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| employee_id | int |\n| name | object |\n| department | object |\n| salary | int |\n+-------------+--------+\n
\n\nWrite a solution to display the first 3
rows of this DataFrame.
\n
Example 1:
\n\n\nInput:\nDataFrame employees\n+-------------+-----------+-----------------------+--------+\n| employee_id | name | department | salary |\n+-------------+-----------+-----------------------+--------+\n| 3 | Bob | Operations | 48675 |\n| 90 | Alice | Sales | 11096 |\n| 9 | Tatiana | Engineering | 33805 |\n| 60 | Annabelle | InformationTechnology | 37678 |\n| 49 | Jonathan | HumanResources | 23793 |\n| 43 | Khaled | Administration | 40454 |\n+-------------+-----------+-----------------------+--------+\nOutput:\n+-------------+---------+-------------+--------+\n| employee_id | name | department | salary |\n+-------------+---------+-------------+--------+\n| 3 | Bob | Operations | 48675 |\n| 90 | Alice | Sales | 11096 |\n| 9 | Tatiana | Engineering | 33805 |\n+-------------+---------+-------------+--------+\nExplanation: \nOnly the first 3 rows are displayed.\n", - "likes": 99, + "likes": 108, "dislikes": 22, - "stats": "{\"totalAccepted\": \"145.5K\", \"totalSubmission\": \"156.4K\", \"totalAcceptedRaw\": 145455, \"totalSubmissionRaw\": 156408, \"acRate\": \"93.0%\"}", + "stats": "{\"totalAccepted\": \"174.4K\", \"totalSubmission\": \"187.3K\", \"totalAcceptedRaw\": 174407, \"totalSubmissionRaw\": 187333, \"acRate\": \"93.1%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108539,9 +108808,9 @@ "questionFrontendId": "2880", "title": "Select Data", "content": "
\nDataFrame students\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| student_id | int |\n| name | object |\n| age | int |\n+-------------+--------+\n\n\n\n
Write a solution to select the name and age of the student with student_id = 101
.
The result format is in the following example.
\n\n\n
\nExample 1:\nInput:\n+------------+---------+-----+\n| student_id | name | age |\n+------------+---------+-----+\n| 101 | Ulysses | 13 |\n| 53 | William | 10 |\n| 128 | Henry | 6 |\n| 3 | Henry | 11 |\n+------------+---------+-----+\nOutput:\n+---------+-----+\n| name | age | \n+---------+-----+\n| Ulysses | 13 |\n+---------+-----+\nExplanation:\nStudent Ulysses has student_id = 101, we select the name and age.\n", - "likes": 105, + "likes": 120, "dislikes": 8, - "stats": "{\"totalAccepted\": \"115.8K\", \"totalSubmission\": \"146K\", \"totalAcceptedRaw\": 115764, \"totalSubmissionRaw\": 146039, \"acRate\": \"79.3%\"}", + "stats": "{\"totalAccepted\": \"139.4K\", \"totalSubmission\": \"175.9K\", \"totalAcceptedRaw\": 139400, \"totalSubmissionRaw\": 175902, \"acRate\": \"79.2%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108568,9 +108837,9 @@ "questionFrontendId": "2881", "title": "Create a New Column", "content": "
\nDataFrame employees
\n+-------------+--------+\n| Column Name | Type. |\n+-------------+--------+\n| name | object |\n| salary | int. |\n+-------------+--------+\n
\n\nA company plans to provide its employees with a bonus.
\n\nWrite a solution to create a new column name bonus
that contains the doubled values of the salary
column.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\nDataFrame employees\n+---------+--------+\n| name | salary |\n+---------+--------+\n| Piper | 4548 |\n| Grace | 28150 |\n| Georgia | 1103 |\n| Willow | 6593 |\n| Finn | 74576 |\n| Thomas | 24433 |\n+---------+--------+\nOutput:\n+---------+--------+--------+\n| name | salary | bonus |\n+---------+--------+--------+\n| Piper | 4548 | 9096 |\n| Grace | 28150 | 56300 |\n| Georgia | 1103 | 2206 |\n| Willow | 6593 | 13186 |\n| Finn | 74576 | 149152 |\n| Thomas | 24433 | 48866 |\n+---------+--------+--------+\nExplanation: \nA new column bonus is created by doubling the value in the column salary.\n", - "likes": 90, + "likes": 99, "dislikes": 6, - "stats": "{\"totalAccepted\": \"108.2K\", \"totalSubmission\": \"120K\", \"totalAcceptedRaw\": 108228, \"totalSubmissionRaw\": 119950, \"acRate\": \"90.2%\"}", + "stats": "{\"totalAccepted\": \"130.3K\", \"totalSubmission\": \"144.2K\", \"totalAcceptedRaw\": 130253, \"totalSubmissionRaw\": 144228, \"acRate\": \"90.3%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108597,9 +108866,9 @@ "questionFrontendId": "2882", "title": "Drop Duplicate Rows", "content": "
\nDataFrame customers\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| customer_id | int |\n| name | object |\n| email | object |\n+-------------+--------+\n\n\n
There are some duplicate rows in the DataFrame based on the email
column.
Write a solution to remove these duplicate rows and keep only the first occurrence.
\n\nThe result format is in the following example.
\n\n\n
\nExample 1:\nInput:\n+-------------+---------+---------------------+\n| customer_id | name | email |\n+-------------+---------+---------------------+\n| 1 | Ella | emily@example.com |\n| 2 | David | michael@example.com |\n| 3 | Zachary | sarah@example.com |\n| 4 | Alice | john@example.com |\n| 5 | Finn | john@example.com |\n| 6 | Violet | alice@example.com |\n+-------------+---------+---------------------+\nOutput: \n+-------------+---------+---------------------+\n| customer_id | name | email |\n+-------------+---------+---------------------+\n| 1 | Ella | emily@example.com |\n| 2 | David | michael@example.com |\n| 3 | Zachary | sarah@example.com |\n| 4 | Alice | john@example.com |\n| 6 | Violet | alice@example.com |\n+-------------+---------+---------------------+\nExplanation:\nAlic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained.\n\n", - "likes": 110, + "likes": 122, "dislikes": 6, - "stats": "{\"totalAccepted\": \"97.5K\", \"totalSubmission\": \"113.8K\", \"totalAcceptedRaw\": 97492, \"totalSubmissionRaw\": 113777, \"acRate\": \"85.7%\"}", + "stats": "{\"totalAccepted\": \"117.7K\", \"totalSubmission\": \"137.6K\", \"totalAcceptedRaw\": 117742, \"totalSubmissionRaw\": 137647, \"acRate\": \"85.5%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108626,9 +108895,9 @@ "questionFrontendId": "2883", "title": "Drop Missing Data", "content": "
\nDataFrame students\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| student_id | int |\n| name | object |\n| age | int |\n+-------------+--------+\n\n\n
There are some rows having missing values in the name
column.
Write a solution to remove the rows with missing values.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\n+------------+---------+-----+\n| student_id | name | age |\n+------------+---------+-----+\n| 32 | Piper | 5 |\n| 217 | None | 19 |\n| 779 | Georgia | 20 |\n| 849 | Willow | 14 |\n+------------+---------+-----+\nOutput:\n+------------+---------+-----+\n| student_id | name | age |\n+------------+---------+-----+\n| 32 | Piper | 5 |\n| 779 | Georgia | 20 | \n| 849 | Willow | 14 | \n+------------+---------+-----+\nExplanation: \nStudent with id 217 havs empty value in the name column, so it will be removed.\n", - "likes": 78, - "dislikes": 5, - "stats": "{\"totalAccepted\": \"90.7K\", \"totalSubmission\": \"141.2K\", \"totalAcceptedRaw\": 90698, \"totalSubmissionRaw\": 141167, \"acRate\": \"64.2%\"}", + "likes": 90, + "dislikes": 7, + "stats": "{\"totalAccepted\": \"109.6K\", \"totalSubmission\": \"170.1K\", \"totalAcceptedRaw\": 109591, \"totalSubmissionRaw\": 170123, \"acRate\": \"64.4%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108655,9 +108924,9 @@ "questionFrontendId": "2884", "title": "Modify Columns", "content": "
\nDataFrame employees
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| name | object |\n| salary | int |\n+-------------+--------+\n
\n\nA company intends to give its employees a pay rise.
\n\nWrite a solution to modify the salary
column by multiplying each salary by 2.
The result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\nDataFrame employees\n+---------+--------+\n| name | salary |\n+---------+--------+\n| Jack | 19666 |\n| Piper | 74754 |\n| Mia | 62509 |\n| Ulysses | 54866 |\n+---------+--------+\nOutput:\n+---------+--------+\n| name | salary |\n+---------+--------+\n| Jack | 39332 |\n| Piper | 149508 |\n| Mia | 125018 |\n| Ulysses | 109732 |\n+---------+--------+\nExplanation:\nEvery salary has been doubled.\n", - "likes": 75, + "likes": 85, "dislikes": 6, - "stats": "{\"totalAccepted\": \"98.9K\", \"totalSubmission\": \"107.1K\", \"totalAcceptedRaw\": 98912, \"totalSubmissionRaw\": 107076, \"acRate\": \"92.4%\"}", + "stats": "{\"totalAccepted\": \"119.4K\", \"totalSubmission\": \"129K\", \"totalAcceptedRaw\": 119383, \"totalSubmissionRaw\": 129000, \"acRate\": \"92.5%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108684,9 +108953,9 @@ "questionFrontendId": "2885", "title": "Rename Columns", "content": "
\nDataFrame students
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| id | int |\n| first | object |\n| last | object |\n| age | int |\n+-------------+--------+\n
\n\nWrite a solution to rename the columns as follows:
\n\nid
to student_id
first
to first_name
last
to last_name
age
to age_in_years
The result format is in the following example.
\n\n\n
\nExample 1:\nInput:\n+----+---------+----------+-----+\n| id | first | last | age |\n+----+---------+----------+-----+\n| 1 | Mason | King | 6 |\n| 2 | Ava | Wright | 7 |\n| 3 | Taylor | Hall | 16 |\n| 4 | Georgia | Thompson | 18 |\n| 5 | Thomas | Moore | 10 |\n+----+---------+----------+-----+\nOutput:\n+------------+------------+-----------+--------------+\n| student_id | first_name | last_name | age_in_years |\n+------------+------------+-----------+--------------+\n| 1 | Mason | King | 6 |\n| 2 | Ava | Wright | 7 |\n| 3 | Taylor | Hall | 16 |\n| 4 | Georgia | Thompson | 18 |\n| 5 | Thomas | Moore | 10 |\n+------------+------------+-----------+--------------+\nExplanation: \nThe column names are changed accordingly.\n", - "likes": 66, + "likes": 73, "dislikes": 3, - "stats": "{\"totalAccepted\": \"85.7K\", \"totalSubmission\": \"100.2K\", \"totalAcceptedRaw\": 85735, \"totalSubmissionRaw\": 100192, \"acRate\": \"85.6%\"}", + "stats": "{\"totalAccepted\": \"103.8K\", \"totalSubmission\": \"121.2K\", \"totalAcceptedRaw\": 103751, \"totalSubmissionRaw\": 121163, \"acRate\": \"85.6%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108713,9 +108982,9 @@ "questionFrontendId": "2886", "title": "Change Data Type", "content": "
\nDataFrame students
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| student_id | int |\n| name | object |\n| age | int |\n| grade | float |\n+-------------+--------+\n
\n\nWrite a solution to correct the errors:
\n\nThe grade
column is stored as floats, convert it to integers.
The result format is in the following example.
\n\n\n
\nExample 1:\nInput:\nDataFrame students:\n+------------+------+-----+-------+\n| student_id | name | age | grade |\n+------------+------+-----+-------+\n| 1 | Ava | 6 | 73.0 |\n| 2 | Kate | 15 | 87.0 |\n+------------+------+-----+-------+\nOutput:\n+------------+------+-----+-------+\n| student_id | name | age | grade |\n+------------+------+-----+-------+\n| 1 | Ava | 6 | 73 |\n| 2 | Kate | 15 | 87 |\n+------------+------+-----+-------+\nExplanation: \nThe data types of the column grade is converted to int.\n", - "likes": 73, + "likes": 82, "dislikes": 8, - "stats": "{\"totalAccepted\": \"83.6K\", \"totalSubmission\": \"95.6K\", \"totalAcceptedRaw\": 83605, \"totalSubmissionRaw\": 95614, \"acRate\": \"87.4%\"}", + "stats": "{\"totalAccepted\": \"101.4K\", \"totalSubmission\": \"115.8K\", \"totalAcceptedRaw\": 101383, \"totalSubmissionRaw\": 115837, \"acRate\": \"87.5%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108742,9 +109011,9 @@ "questionFrontendId": "2887", "title": "Fill Missing Data", "content": "
\nDataFrame products
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| name | object |\n| quantity | int |\n| price | int |\n+-------------+--------+\n
\n\nWrite a solution to fill in the missing value as 0
in the quantity
column.
The result format is in the following example.
\n\n\n
\nExample 1:\nInput:+-----------------+----------+-------+\n| name | quantity | price |\n+-----------------+----------+-------+\n| Wristwatch | None | 135 |\n| WirelessEarbuds | None | 821 |\n| GolfClubs | 779 | 9319 |\n| Printer | 849 | 3051 |\n+-----------------+----------+-------+\nOutput:\n+-----------------+----------+-------+\n| name | quantity | price |\n+-----------------+----------+-------+\n| Wristwatch | 0 | 135 |\n| WirelessEarbuds | 0 | 821 |\n| GolfClubs | 779 | 9319 |\n| Printer | 849 | 3051 |\n+-----------------+----------+-------+\nExplanation: \nThe quantity for Wristwatch and WirelessEarbuds are filled by 0.\n", - "likes": 76, + "likes": 85, "dislikes": 3, - "stats": "{\"totalAccepted\": \"80.2K\", \"totalSubmission\": \"111.2K\", \"totalAcceptedRaw\": 80174, \"totalSubmissionRaw\": 111161, \"acRate\": \"72.1%\"}", + "stats": "{\"totalAccepted\": \"97.1K\", \"totalSubmission\": \"134.4K\", \"totalAcceptedRaw\": 97147, \"totalSubmissionRaw\": 134356, \"acRate\": \"72.3%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108771,9 +109040,9 @@ "questionFrontendId": "2888", "title": "Reshape Data: Concatenate", "content": "
\nDataFrame\n\ndf1
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| student_id | int |\n| name | object |\n| age | int |\n+-------------+--------+\n\nDataFramedf2
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| student_id | int |\n| name | object |\n| age | int |\n+-------------+--------+\n\n
Write a solution to concatenate these two DataFrames vertically into one DataFrame.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\ndf1\n+------------+---------+-----+\n| student_id | name | age |\n+------------+---------+-----+\n| 1 | Mason | 8 |\n| 2 | Ava | 6 |\n| 3 | Taylor | 15 |\n| 4 | Georgia | 17 |\n+------------+---------+-----+\ndf2\n+------------+------+-----+\n| student_id | name | age |\n+------------+------+-----+\n| 5 | Leo | 7 |\n| 6 | Alex | 7 |\n+------------+------+-----+\nOutput:\n+------------+---------+-----+\n| student_id | name | age |\n+------------+---------+-----+\n| 1 | Mason | 8 |\n| 2 | Ava | 6 |\n| 3 | Taylor | 15 |\n| 4 | Georgia | 17 |\n| 5 | Leo | 7 |\n| 6 | Alex | 7 |\n+------------+---------+-----+\nExplanation:\nThe two DataFramess are stacked vertically, and their rows are combined.\n", - "likes": 74, + "likes": 84, "dislikes": 7, - "stats": "{\"totalAccepted\": \"84.1K\", \"totalSubmission\": \"92.7K\", \"totalAcceptedRaw\": 84117, \"totalSubmissionRaw\": 92716, \"acRate\": \"90.7%\"}", + "stats": "{\"totalAccepted\": \"101.6K\", \"totalSubmission\": \"112K\", \"totalAcceptedRaw\": 101631, \"totalSubmissionRaw\": 111976, \"acRate\": \"90.8%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108800,9 +109069,9 @@ "questionFrontendId": "2889", "title": "Reshape Data: Pivot", "content": "
\nDataFrame weather
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| city | object |\n| month | object |\n| temperature | int |\n+-------------+--------+\n
\n\nWrite a solution to pivot the data so that each row represents temperatures for a specific month, and each city is a separate column.
\n\nThe result format is in the following example.
\n\n\n
\nExample 1:\nInput:\n+--------------+----------+-------------+\n| city | month | temperature |\n+--------------+----------+-------------+\n| Jacksonville | January | 13 |\n| Jacksonville | February | 23 |\n| Jacksonville | March | 38 |\n| Jacksonville | April | 5 |\n| Jacksonville | May | 34 |\n| ElPaso | January | 20 |\n| ElPaso | February | 6 |\n| ElPaso | March | 26 |\n| ElPaso | April | 2 |\n| ElPaso | May | 43 |\n+--------------+----------+-------------+\nOutput:\n+----------+--------+--------------+\n| month | ElPaso | Jacksonville |\n+----------+--------+--------------+\n| April | 2 | 5 |\n| February | 6 | 23 |\n| January | 20 | 13 |\n| March | 26 | 38 |\n| May | 43 | 34 |\n+----------+--------+--------------+
\nExplanation:\nThe table is pivoted, each column represents a city, and each row represents a specific month.
\n",
- "likes": 112,
+ "likes": 126,
"dislikes": 14,
- "stats": "{\"totalAccepted\": \"71K\", \"totalSubmission\": \"85K\", \"totalAcceptedRaw\": 70995, \"totalSubmissionRaw\": 85026, \"acRate\": \"83.5%\"}",
+ "stats": "{\"totalAccepted\": \"86.1K\", \"totalSubmission\": \"103.1K\", \"totalAcceptedRaw\": 86132, \"totalSubmissionRaw\": 103078, \"acRate\": \"83.6%\"}",
"similarQuestions": "[]",
"categoryTitle": "pandas",
"hints": [
@@ -108829,9 +109098,9 @@
"questionFrontendId": "2890",
"title": "Reshape Data: Melt",
"content": "\nDataFrame report
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| product | object |\n| quarter_1 | int |\n| quarter_2 | int |\n| quarter_3 | int |\n| quarter_4 | int |\n+-------------+--------+\n
\n\nWrite a solution to reshape the data so that each row represents sales data for a product in a specific quarter.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput:\n+-------------+-----------+-----------+-----------+-----------+\n| product | quarter_1 | quarter_2 | quarter_3 | quarter_4 |\n+-------------+-----------+-----------+-----------+-----------+\n| Umbrella | 417 | 224 | 379 | 611 |\n| SleepingBag | 800 | 936 | 93 | 875 |\n+-------------+-----------+-----------+-----------+-----------+\nOutput:\n+-------------+-----------+-------+\n| product | quarter | sales |\n+-------------+-----------+-------+\n| Umbrella | quarter_1 | 417 |\n| SleepingBag | quarter_1 | 800 |\n| Umbrella | quarter_2 | 224 |\n| SleepingBag | quarter_2 | 936 |\n| Umbrella | quarter_3 | 379 |\n| SleepingBag | quarter_3 | 93 |\n| Umbrella | quarter_4 | 611 |\n| SleepingBag | quarter_4 | 875 |\n+-------------+-----------+-------+\nExplanation:\nThe DataFrame is reshaped from wide to long format. Each row represents the sales of a product in a quarter.\n\n", - "likes": 93, + "likes": 105, "dislikes": 3, - "stats": "{\"totalAccepted\": \"67K\", \"totalSubmission\": \"77.8K\", \"totalAcceptedRaw\": 67020, \"totalSubmissionRaw\": 77751, \"acRate\": \"86.2%\"}", + "stats": "{\"totalAccepted\": \"81.2K\", \"totalSubmission\": \"94.2K\", \"totalAcceptedRaw\": 81228, \"totalSubmissionRaw\": 94193, \"acRate\": \"86.2%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [ @@ -108858,9 +109127,9 @@ "questionFrontendId": "2891", "title": "Method Chaining", "content": "
\nDataFrame animals
\n+-------------+--------+\n| Column Name | Type |\n+-------------+--------+\n| name | object |\n| species | object |\n| age | int |\n| weight | int |\n+-------------+--------+\n
\n\nWrite a solution to list the names of animals that weigh strictly more than 100
kilograms.
Return the animals sorted by weight in descending order.
\n\nThe result format is in the following example.
\n\n\n
Example 1:
\n\n\nInput: \nDataFrame animals:\n+----------+---------+-----+--------+\n| name | species | age | weight |\n+----------+---------+-----+--------+\n| Tatiana | Snake | 98 | 464 |\n| Khaled | Giraffe | 50 | 41 |\n| Alex | Leopard | 6 | 328 |\n| Jonathan | Monkey | 45 | 463 |\n| Stefan | Bear | 100 | 50 |\n| Tommy | Panda | 26 | 349 |\n+----------+---------+-----+--------+\nOutput: \n+----------+\n| name |\n+----------+\n| Tatiana |\n| Jonathan |\n| Tommy |\n| Alex |\n+----------+\nExplanation: \nAll animals weighing more than 100 should be included in the results table.\nTatiana's weight is 464, Jonathan's weight is 463, Tommy's weight is 349, and Alex's weight is 328.\nThe results should be sorted in descending order of weight.\n\n
\n
In Pandas, method chaining enables us to perform operations on a DataFrame without breaking up each operation into a separate line or creating multiple temporary variables.
\n\nCan you complete this task in just one line of code using method chaining?
\n", - "likes": 85, + "likes": 98, "dislikes": 6, - "stats": "{\"totalAccepted\": \"69.5K\", \"totalSubmission\": \"90.6K\", \"totalAcceptedRaw\": 69464, \"totalSubmissionRaw\": 90647, \"acRate\": \"76.6%\"}", + "stats": "{\"totalAccepted\": \"84.1K\", \"totalSubmission\": \"109.8K\", \"totalAcceptedRaw\": 84117, \"totalSubmissionRaw\": 109798, \"acRate\": \"76.6%\"}", "similarQuestions": "[]", "categoryTitle": "pandas", "hints": [], @@ -108887,7 +109156,7 @@ "content": null, "likes": 27, "dislikes": 1, - "stats": "{\"totalAccepted\": \"1.3K\", \"totalSubmission\": \"3.3K\", \"totalAcceptedRaw\": 1318, \"totalSubmissionRaw\": 3327, \"acRate\": \"39.6%\"}", + "stats": "{\"totalAccepted\": \"1.5K\", \"totalSubmission\": \"3.6K\", \"totalAcceptedRaw\": 1456, \"totalSubmissionRaw\": 3643, \"acRate\": \"40.0%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -108929,7 +109198,7 @@ "content": null, "likes": 21, "dislikes": 3, - "stats": "{\"totalAccepted\": \"2.8K\", \"totalSubmission\": \"4.2K\", \"totalAcceptedRaw\": 2846, \"totalSubmissionRaw\": 4230, \"acRate\": \"67.3%\"}", + "stats": "{\"totalAccepted\": \"3.3K\", \"totalSubmission\": \"4.9K\", \"totalAcceptedRaw\": 3347, \"totalSubmissionRaw\": 4932, \"acRate\": \"67.9%\"}", "similarQuestions": "[]", "categoryTitle": "Database", "hints": [], @@ -108955,9 +109224,9 @@ "questionFrontendId": "2894", "title": "Divisible and Non-divisible Sums Difference", "content": "You are given positive integers n
and m
.
Define two integers as follows:
\n\nnum1
: The sum of all integers in the range [1, n]
(both inclusive) that are not divisible by m
.num2
: The sum of all integers in the range [1, n]
(both inclusive) that are divisible by m
.Return the integer num1 - num2
.
\n
Example 1:
\n\n\nInput: n = 10, m = 3\nOutput: 19\nExplanation: In the given example:\n- Integers in the range [1, 10] that are not divisible by 3 are [1,2,4,5,7,8,10], num1 is the sum of those integers = 37.\n- Integers in the range [1, 10] that are divisible by 3 are [3,6,9], num2 is the sum of those integers = 18.\nWe return 37 - 18 = 19 as the answer.\n\n\n
Example 2:
\n\n\nInput: n = 5, m = 6\nOutput: 15\nExplanation: In the given example:\n- Integers in the range [1, 5] that are not divisible by 6 are [1,2,3,4,5], num1 is the sum of those integers = 15.\n- Integers in the range [1, 5] that are divisible by 6 are [], num2 is the sum of those integers = 0.\nWe return 15 - 0 = 15 as the answer.\n\n\n
Example 3:
\n\n\nInput: n = 5, m = 1\nOutput: -15\nExplanation: In the given example:\n- Integers in the range [1, 5] that are not divisible by 1 are [], num1 is the sum of those integers = 0.\n- Integers in the range [1, 5] that are divisible by 1 are [1,2,3,4,5], num2 is the sum of those integers = 15.\nWe return 0 - 15 = -15 as the answer.\n\n\n
\n
Constraints:
\n\n1 <= n, m <= 1000
You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.
\n\nYou are given an array processorTime
representing the time each processor becomes available and an array tasks
representing how long each task takes to complete. Return the minimum time needed to complete all tasks.
\n
Example 1:
\n\nInput: processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]
\n\nOutput: 16
\n\nExplanation:
\n\nAssign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at time = 8
, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at time = 10
.
The time taken by the first processor to finish the execution of all tasks is max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16
.
The time taken by the second processor to finish the execution of all tasks is max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13
.
Example 2:
\n\nInput: processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]
\n\nOutput: 23
\n\nExplanation:
\n\nAssign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.
\n\nThe time taken by the first processor to finish the execution of all tasks is max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18
.
The time taken by the second processor to finish the execution of all tasks is max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23
.
\n
Constraints:
\n\n1 <= n == processorTime.length <= 25000
1 <= tasks.length <= 105
0 <= processorTime[i] <= 109
1 <= tasks[i] <= 109
tasks.length == 4 * n
You are given two 0-indexed binary strings s1
and s2
, both of length n
, and a positive integer x
.
You can perform any of the following operations on the string s1
any number of times:
i
and j
, and flip both s1[i]
and s1[j]
. The cost of this operation is x
.i
such that i < n - 1
and flip both s1[i]
and s1[i + 1]
. The cost of this operation is 1
.Return the minimum cost needed to make the strings s1
and s2
equal, or return -1
if it is impossible.
Note that flipping a character means changing it from 0
to 1
or vice-versa.
\n
Example 1:
\n\n\nInput: s1 = "1100011000", s2 = "0101001010", x = 2\nOutput: 4\nExplanation: We can do the following operations:\n- Choose i = 3 and apply the second operation. The resulting string is s1 = "1101111000".\n- Choose i = 4 and apply the second operation. The resulting string is s1 = "1101001000".\n- Choose i = 0 and j = 8 and apply the first operation. The resulting string is s1 = "0101001010" = s2.\nThe total cost is 1 + 1 + 2 = 4. It can be shown that it is the minimum cost possible.\n\n\n
Example 2:
\n\n\nInput: s1 = "10110", s2 = "00011", x = 4\nOutput: -1\nExplanation: It is not possible to make the two strings equal.\n\n\n
\n
Constraints:
\n\nn == s1.length == s2.length
1 <= n, x <= 500
s1
and s2
consist only of the characters '0'
and '1'
.You are given a 0-indexed integer array nums
and a positive integer k
.
You can do the following operation on the array any number of times:
\n\ni
and j
and simultaneously update the values of nums[i]
to (nums[i] AND nums[j])
and nums[j]
to (nums[i] OR nums[j])
. Here, OR
denotes the bitwise OR
operation, and AND
denotes the bitwise AND
operation.You have to choose k
elements from the final array and calculate the sum of their squares.
Return the maximum sum of squares you can achieve.
\n\nSince the answer can be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [2,6,5,8], k = 2\nOutput: 261\nExplanation: We can do the following operations on the array:\n- Choose i = 0 and j = 3, then change nums[0] to (2 AND 8) = 0 and nums[3] to (2 OR 8) = 10. The resulting array is nums = [0,6,5,10].\n- Choose i = 2 and j = 3, then change nums[2] to (5 AND 10) = 0 and nums[3] to (5 OR 10) = 15. The resulting array is nums = [0,6,0,15].\nWe can choose the elements 15 and 6 from the final array. The sum of squares is 152 + 62 = 261.\nIt can be shown that this is the maximum value we can get.\n\n\n
Example 2:
\n\n\nInput: nums = [4,5,4,7], k = 3\nOutput: 90\nExplanation: We do not need to apply any operations.\nWe can choose the elements 7, 5, and 4 with a sum of squares: 72 + 52 + 42 = 90.\nIt can be shown that this is the maximum value we can get.\n\n\n
\n
Constraints:
\n\n1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
Given an integer array nums
where nums[i]
is either a positive integer or -1
. We need to find for each -1
the respective positive integer, which we call the last visited integer.
To achieve this goal, let's define two empty arrays: seen
and ans
.
Start iterating from the beginning of the array nums
.
seen
.-1
is encountered, let k
be the number of consecutive -1
s seen so far (including the current -1
),\n\tk
is less than or equal to the length of seen
, append the k
-th element of seen
to ans
.k
is strictly greater than the length of seen
, append -1
to ans
.Return the array ans
.
\n
Example 1:
\n\nInput: nums = [1,2,-1,-1,-1]
\n\nOutput: [2,1,-1]
\n\nExplanation:
\n\nStart with seen = []
and ans = []
.
nums[0]
: The first element in nums is 1
. We prepend it to the front of seen
. Now, seen == [1]
.nums[1]
: The next element is 2
. We prepend it to the front of seen
. Now, seen == [2, 1]
.nums[2]
: The next element is -1
. This is the first occurrence of -1
, so k == 1
. We look for the first element in seen. We append 2
to ans
. Now, ans == [2]
.nums[3]
: Another -1
. This is the second consecutive -1
, so k == 2
. The second element in seen
is 1
, so we append 1
to ans
. Now, ans == [2, 1]
.nums[4]
: Another -1
, the third in a row, making k = 3
. However, seen
only has two elements ([2, 1]
). Since k
is greater than the number of elements in seen
, we append -1
to ans
. Finally, ans == [2, 1, -1]
.Example 2:
\n\nInput: nums = [1,-1,2,-1,-1]
\n\nOutput: [1,2,1]
\n\nExplanation:
\n\nStart with seen = []
and ans = []
.
nums[0]
: The first element in nums is 1
. We prepend it to the front of seen
. Now, seen == [1]
.nums[1]
: The next element is -1
. This is the first occurrence of -1
, so k == 1
. We look for the first element in seen
, which is 1
. Append 1
to ans
. Now, ans == [1]
.nums[2]
: The next element is 2
. Prepend this to the front of seen
. Now, seen == [2, 1]
.nums[3]
: The next element is -1
. This -1
is not consecutive to the first -1
since 2
was in between. Thus, k
resets to 1
. The first element in seen
is 2
, so append 2
to ans
. Now, ans == [1, 2]
.nums[4]
: Another -1
. This is consecutive to the previous -1
, so k == 2
. The second element in seen
is 1
, append 1
to ans
. Finally, ans == [1, 2, 1]
.\n
Constraints:
\n\n1 <= nums.length <= 100
nums[i] == -1
or 1 <= nums[i] <= 100
You are given a string array words
and a binary array groups
both of length n
, where words[i]
is associated with groups[i]
.
Your task is to select the longest alternating subsequence from words
. A subsequence of words
is alternating if for any two consecutive strings in the sequence, their corresponding elements in the binary array groups
differ. Essentially, you are to choose strings such that adjacent elements have non-matching corresponding bits in the groups
array.
Formally, you need to find the longest subsequence of an array of indices [0, 1, ..., n - 1]
denoted as [i0, i1, ..., ik-1]
, such that groups[ij] != groups[ij+1]
for each 0 <= j < k - 1
and then find the words corresponding to these indices.
Return the selected subsequence. If there are multiple answers, return any of them.
\n\nNote: The elements in words
are distinct.
\n
Example 1:
\n\nInput: words = ["e","a","b"], groups = [0,0,1]
\n\nOutput: ["e","b"]
\n\nExplanation: A subsequence that can be selected is ["e","b"]
because groups[0] != groups[2]
. Another subsequence that can be selected is ["a","b"]
because groups[1] != groups[2]
. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is 2
.
Example 2:
\n\nInput: words = ["a","b","c","d"], groups = [1,0,1,1]
\n\nOutput: ["a","b","c"]
\n\nExplanation: A subsequence that can be selected is ["a","b","c"]
because groups[0] != groups[1]
and groups[1] != groups[2]
. Another subsequence that can be selected is ["a","b","d"]
because groups[0] != groups[1]
and groups[1] != groups[3]
. It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3
.
\n
Constraints:
\n\n1 <= n == words.length == groups.length <= 100
1 <= words[i].length <= 10
groups[i]
is either 0
or 1.
words
consists of distinct strings.words[i]
consists of lowercase English letters.You are given a string array words
and a binary array groups
both of length n
.
A subsequence of words
is alternating if for any two consecutive strings in the sequence, their corresponding elements at the same indices in groups
are different (that is, there cannot be consecutive 0 or 1).
Your task is to select the longest alternating subsequence from words
.
Return the selected subsequence. If there are multiple answers, return any of them.
\n\nNote: The elements in words
are distinct.
\n
Example 1:
\n\nInput: words = ["e","a","b"], groups = [0,0,1]
\n\nOutput: ["e","b"]
\n\nExplanation: A subsequence that can be selected is ["e","b"]
because groups[0] != groups[2]
. Another subsequence that can be selected is ["a","b"]
because groups[1] != groups[2]
. It can be demonstrated that the length of the longest subsequence of indices that satisfies the condition is 2
.
Example 2:
\n\nInput: words = ["a","b","c","d"], groups = [1,0,1,1]
\n\nOutput: ["a","b","c"]
\n\nExplanation: A subsequence that can be selected is ["a","b","c"]
because groups[0] != groups[1]
and groups[1] != groups[2]
. Another subsequence that can be selected is ["a","b","d"]
because groups[0] != groups[1]
and groups[1] != groups[3]
. It can be shown that the length of the longest subsequence of indices that satisfies the condition is 3
.
\n
Constraints:
\n\n1 <= n == words.length == groups.length <= 100
1 <= words[i].length <= 10
groups[i]
is either 0
or 1.
words
consists of distinct strings.words[i]
consists of lowercase English letters.You are given a string array words
, and an array groups
, both arrays having length n
.
The hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different.
\n\nYou need to select the longest subsequence from an array of indices [0, 1, ..., n - 1]
, such that for the subsequence denoted as [i0, i1, ..., ik-1]
having length k
, the following holds:
groups[ij] != groups[ij+1]
, for each j
where 0 < j + 1 < k
.words[ij]
and words[ij+1]
are equal in length, and the hamming distance between them is 1
, where 0 < j + 1 < k
, for all indices in the subsequence.Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them.
\n\nNote: strings in words
may be unequal in length.
\n
Example 1:
\n\nInput: words = ["bab","dab","cab"], groups = [1,2,2]
\n\nOutput: ["bab","cab"]
\n\nExplanation: A subsequence that can be selected is [0,2]
.
groups[0] != groups[2]
words[0].length == words[2].length
, and the hamming distance between them is 1.So, a valid answer is [words[0],words[2]] = ["bab","cab"]
.
Another subsequence that can be selected is [0,1]
.
groups[0] != groups[1]
words[0].length == words[1].length
, and the hamming distance between them is 1
.So, another valid answer is [words[0],words[1]] = ["bab","dab"]
.
It can be shown that the length of the longest subsequence of indices that satisfies the conditions is 2
.
Example 2:
\n\nInput: words = ["a","b","c","d"], groups = [1,2,3,4]
\n\nOutput: ["a","b","c","d"]
\n\nExplanation: We can select the subsequence [0,1,2,3]
.
It satisfies both conditions.
\n\nHence, the answer is [words[0],words[1],words[2],words[3]] = ["a","b","c","d"]
.
It has the longest length among all subsequences of indices that satisfy the conditions.
\n\nHence, it is the only answer.
\n\n
Constraints:
\n\n1 <= n == words.length == groups.length <= 1000
1 <= words[i].length <= 10
1 <= groups[i] <= n
words
consists of distinct strings.words[i]
consists of lowercase English letters.You are given a 0-indexed array nums
of non-negative integers, and two integers l
and r
.
Return the count of sub-multisets within nums
where the sum of elements in each subset falls within the inclusive range of [l, r]
.
Since the answer may be large, return it modulo 109 + 7
.
A sub-multiset is an unordered collection of elements of the array in which a given value x
can occur 0, 1, ..., occ[x]
times, where occ[x]
is the number of occurrences of x
in the array.
Note that:
\n\n0
.\n
Example 1:
\n\n\nInput: nums = [1,2,2,3], l = 6, r = 6\nOutput: 1\nExplanation: The only subset of nums that has a sum of 6 is {1, 2, 3}.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1,4,2,7], l = 1, r = 5\nOutput: 7\nExplanation: The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,1,3,5,2], l = 3, r = 5\nOutput: 9\nExplanation: The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 2 * 104
0 <= nums[i] <= 2 * 104
nums
does not exceed 2 * 104
.0 <= l <= r <= 2 * 104
You are given a 0-indexed integer array nums
having length n
, an integer indexDifference
, and an integer valueDifference
.
Your task is to find two indices i
and j
, both in the range [0, n - 1]
, that satisfy the following conditions:
abs(i - j) >= indexDifference
, andabs(nums[i] - nums[j]) >= valueDifference
Return an integer array answer
, where answer = [i, j]
if there are two such indices, and answer = [-1, -1]
otherwise. If there are multiple choices for the two indices, return any of them.
Note: i
and j
may be equal.
\n
Example 1:
\n\n\nInput: nums = [5,1,4,1], indexDifference = 2, valueDifference = 4\nOutput: [0,3]\nExplanation: In this example, i = 0 and j = 3 can be selected.\nabs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.\nHence, a valid answer is [0,3].\n[3,0] is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1], indexDifference = 0, valueDifference = 0\nOutput: [0,0]\nExplanation: In this example, i = 0 and j = 0 can be selected.\nabs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.\nHence, a valid answer is [0,0].\nOther valid answers are [0,1], [1,0], and [1,1].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3], indexDifference = 2, valueDifference = 4\nOutput: [-1,-1]\nExplanation: In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.\nHence, [-1,-1] is returned.\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 100
0 <= nums[i] <= 50
0 <= indexDifference <= 100
0 <= valueDifference <= 50
You are given a binary string s
and a positive integer k
.
A substring of s
is beautiful if the number of 1
's in it is exactly k
.
Let len
be the length of the shortest beautiful substring.
Return the lexicographically smallest beautiful substring of string s
with length equal to len
. If s
doesn't contain a beautiful substring, return an empty string.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
.
"abcd"
is lexicographically larger than "abcc"
because the first position they differ is at the fourth character, and d
is greater than c
.\n
Example 1:
\n\n\nInput: s = "100011001", k = 3\nOutput: "11001"\nExplanation: There are 7 beautiful substrings in this example:\n1. The substring "100011001".\n2. The substring "100011001".\n3. The substring "100011001".\n4. The substring "100011001".\n5. The substring "100011001".\n6. The substring "100011001".\n7. The substring "100011001".\nThe length of the shortest beautiful substring is 5.\nThe lexicographically smallest beautiful substring with length 5 is the substring "11001".\n\n\n
Example 2:
\n\n\nInput: s = "1011", k = 2\nOutput: "11"\nExplanation: There are 3 beautiful substrings in this example:\n1. The substring "1011".\n2. The substring "1011".\n3. The substring "1011".\nThe length of the shortest beautiful substring is 2.\nThe lexicographically smallest beautiful substring with length 2 is the substring "11".\n\n\n
Example 3:
\n\n\nInput: s = "000", k = 1\nOutput: ""\nExplanation: There are no beautiful substrings in this example.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
1 <= k <= s.length
You are given a 0-indexed integer array nums
having length n
, an integer indexDifference
, and an integer valueDifference
.
Your task is to find two indices i
and j
, both in the range [0, n - 1]
, that satisfy the following conditions:
abs(i - j) >= indexDifference
, andabs(nums[i] - nums[j]) >= valueDifference
Return an integer array answer
, where answer = [i, j]
if there are two such indices, and answer = [-1, -1]
otherwise. If there are multiple choices for the two indices, return any of them.
Note: i
and j
may be equal.
\n
Example 1:
\n\n\nInput: nums = [5,1,4,1], indexDifference = 2, valueDifference = 4\nOutput: [0,3]\nExplanation: In this example, i = 0 and j = 3 can be selected.\nabs(0 - 3) >= 2 and abs(nums[0] - nums[3]) >= 4.\nHence, a valid answer is [0,3].\n[3,0] is also a valid answer.\n\n\n
Example 2:
\n\n\nInput: nums = [2,1], indexDifference = 0, valueDifference = 0\nOutput: [0,0]\nExplanation: In this example, i = 0 and j = 0 can be selected.\nabs(0 - 0) >= 0 and abs(nums[0] - nums[0]) >= 0.\nHence, a valid answer is [0,0].\nOther valid answers are [0,1], [1,0], and [1,1].\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3], indexDifference = 2, valueDifference = 4\nOutput: [-1,-1]\nExplanation: In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.\nHence, [-1,-1] is returned.\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 105
0 <= nums[i] <= 109
0 <= indexDifference <= 105
0 <= valueDifference <= 109
Given a 0-indexed 2D integer matrix grid
of size n * m
, we define a 0-indexed 2D matrix p
of size n * m
as the product matrix of grid
if the following condition is met:
p[i][j]
is calculated as the product of all elements in grid
except for the element grid[i][j]
. This product is then taken modulo 12345
.Return the product matrix of grid
.
\n
Example 1:
\n\n\nInput: grid = [[1,2],[3,4]]\nOutput: [[24,12],[8,6]]\nExplanation: p[0][0] = grid[0][1] * grid[1][0] * grid[1][1] = 2 * 3 * 4 = 24\np[0][1] = grid[0][0] * grid[1][0] * grid[1][1] = 1 * 3 * 4 = 12\np[1][0] = grid[0][0] * grid[0][1] * grid[1][1] = 1 * 2 * 4 = 8\np[1][1] = grid[0][0] * grid[0][1] * grid[1][0] = 1 * 2 * 3 = 6\nSo the answer is [[24,12],[8,6]].\n\n
Example 2:
\n\n\nInput: grid = [[12345],[2],[1]]\nOutput: [[2],[0],[0]]\nExplanation: p[0][0] = grid[0][1] * grid[0][2] = 2 * 1 = 2.\np[0][1] = grid[0][0] * grid[0][2] = 12345 * 1 = 12345. 12345 % 12345 = 0. So p[0][1] = 0.\np[0][2] = grid[0][0] * grid[0][1] = 12345 * 2 = 24690. 24690 % 12345 = 0. So p[0][2] = 0.\nSo the answer is [[2],[0],[0]].\n\n
\n
Constraints:
\n\n1 <= n == grid.length <= 105
1 <= m == grid[i].length <= 105
2 <= n * m <= 105
1 <= grid[i][j] <= 109
You are given a 0-indexed array nums
of integers.
A triplet of indices (i, j, k)
is a mountain if:
i < j < k
nums[i] < nums[j]
and nums[k] < nums[j]
Return the minimum possible sum of a mountain triplet of nums
. If no such triplet exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [8,6,1,5,3]\nOutput: 9\nExplanation: Triplet (2, 3, 4) is a mountain triplet of sum 9 since: \n- 2 < 3 < 4\n- nums[2] < nums[3] and nums[4] < nums[3]\nAnd the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.\n\n\n
Example 2:
\n\n\nInput: nums = [5,4,8,7,10,2]\nOutput: 13\nExplanation: Triplet (1, 3, 5) is a mountain triplet of sum 13 since: \n- 1 < 3 < 5\n- nums[1] < nums[3] and nums[5] < nums[3]\nAnd the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.\n\n\n
Example 3:
\n\n\nInput: nums = [6,5,4,3,4,5]\nOutput: -1\nExplanation: It can be shown that there are no mountain triplets in nums.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 50
1 <= nums[i] <= 50
You are given a 0-indexed array nums
of integers.
A triplet of indices (i, j, k)
is a mountain if:
i < j < k
nums[i] < nums[j]
and nums[k] < nums[j]
Return the minimum possible sum of a mountain triplet of nums
. If no such triplet exists, return -1
.
\n
Example 1:
\n\n\nInput: nums = [8,6,1,5,3]\nOutput: 9\nExplanation: Triplet (2, 3, 4) is a mountain triplet of sum 9 since: \n- 2 < 3 < 4\n- nums[2] < nums[3] and nums[4] < nums[3]\nAnd the sum of this triplet is nums[2] + nums[3] + nums[4] = 9. It can be shown that there are no mountain triplets with a sum of less than 9.\n\n\n
Example 2:
\n\n\nInput: nums = [5,4,8,7,10,2]\nOutput: 13\nExplanation: Triplet (1, 3, 5) is a mountain triplet of sum 13 since: \n- 1 < 3 < 5\n- nums[1] < nums[3] and nums[5] < nums[3]\nAnd the sum of this triplet is nums[1] + nums[3] + nums[5] = 13. It can be shown that there are no mountain triplets with a sum of less than 13.\n\n\n
Example 3:
\n\n\nInput: nums = [6,5,4,3,4,5]\nOutput: -1\nExplanation: It can be shown that there are no mountain triplets in nums.\n\n\n
\n
Constraints:
\n\n3 <= nums.length <= 105
1 <= nums[i] <= 108
You are given a collection of numbered balls
and instructed to sort them into boxes for a nearly balanced distribution. There are two rules you must follow:
\u200bReturn the fewest number of boxes to sort these balls following these rules.
\n\n\n
Example 1:
\n\nInput: balls = [3,2,3,2,3]
\n\nOutput: 2
\n\nExplanation:
\n\nWe can sort balls
into boxes as follows:
[3,3,3]
[2,2]
The size difference between the two boxes doesn't exceed one.
\nExample 2:
\n\nInput: balls = [10,10,10,3,1,1]
\n\nOutput: 4
\n\nExplanation:
\n\nWe can sort balls
into boxes as follows:
[10]
[10,10]
[3]
[1,1]
You can't use fewer than four boxes while still following the rules. For example, putting all three balls numbered 10 in one box would break the rule about the maximum size difference between boxes.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
Given a string s
and an integer k
, partition s
into k
substrings such that the letter changes needed to make each substring a semi-palindrome are minimized.
Return the minimum number of letter changes required.
\n\nA semi-palindrome is a special type of string that can be divided into palindromes based on a repeating pattern. To check if a string is a semi-palindrome:\u200b
\n\nd
of the string's length. d
can range from 1
up to, but not including, the string's length. For a string of length 1
, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed.d
, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length d
. Specifically, the first group consists of characters at positions 1
, 1 + d
, 1 + 2d
, and so on; the second group includes characters at positions 2
, 2 + d
, 2 + 2d
, etc.Consider the string "abcabc"
:
"abcabc"
is 6
. Valid divisors are 1
, 2
, and 3
.d = 1
: The entire string "abcabc"
forms one group. Not a palindrome.d = 2
:\n\t1, 3, 5
): "acb"
2, 4, 6
): "bac"
d = 3
:\n\t1, 4
): "aa"
2, 5
): "bb"
3, 6
): "cc"
"abcabc"
is a semi-palindrome.\n
Example 1:
\n\nInput: s = "abcac", k = 2
\n\nOutput: 1
\n\nExplanation: Divide s
into "ab"
and "cac"
. "cac"
is already semi-palindrome. Change "ab"
to "aa"
, it becomes semi-palindrome with d = 1
.
Example 2:
\n\nInput: s = "abcdef", k = 2
\n\nOutput: 2
\n\nExplanation: Divide s
into substrings "abc"
and "def"
. Each needs one change to become semi-palindrome.
Example 3:
\n\nInput: s = "aabbaa", k = 3
\n\nOutput: 0
\n\nExplanation: Divide s
into substrings "aa"
, "bb"
and "aa"
. All are already semi-palindromes.
\n
Constraints:
\n\n2 <= s.length <= 200
1 <= k <= s.length / 2
s
contains only lowercase English letters.You are given a 0-indexed integer array nums
.
The distinct count of a subarray of nums
is defined as:
nums[i..j]
be a subarray of nums
consisting of all the indices from i
to j
such that 0 <= i <= j < nums.length
. Then the number of distinct values in nums[i..j]
is called the distinct count of nums[i..j]
.Return the sum of the squares of distinct counts of all subarrays of nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1]\nOutput: 15\nExplanation: Six possible subarrays are:\n[1]: 1 distinct value\n[2]: 1 distinct value\n[1]: 1 distinct value\n[1,2]: 2 distinct values\n[2,1]: 2 distinct values\n[1,2,1]: 2 distinct values\nThe sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1]\nOutput: 3\nExplanation: Three possible subarrays are:\n[1]: 1 distinct value\n[1]: 1 distinct value\n[1,1]: 1 distinct value\nThe sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given a 0-indexed binary string s
having an even length.
A string is beautiful if it's possible to partition it into one or more substrings such that:
\n\n1
's or only 0
's.You can change any character in s
to 0
or 1
.
Return the minimum number of changes required to make the string s
beautiful.
\n
Example 1:
\n\n\nInput: s = "1001"\nOutput: 2\nExplanation: We change s[1] to 1 and s[3] to 0 to get string "1100".\nIt can be seen that the string "1100" is beautiful because we can partition it into "11|00".\nIt can be proven that 2 is the minimum number of changes needed to make the string beautiful.\n\n\n
Example 2:
\n\n\nInput: s = "10"\nOutput: 1\nExplanation: We change s[1] to 1 to get string "11".\nIt can be seen that the string "11" is beautiful because we can partition it into "11".\nIt can be proven that 1 is the minimum number of changes needed to make the string beautiful.\n\n\n
Example 3:
\n\n\nInput: s = "0000"\nOutput: 0\nExplanation: We don't need to make any changes as the string "0000" is beautiful already.\n\n\n
\n
Constraints:
\n\n2 <= s.length <= 105
s
has an even length.s[i]
is either '0'
or '1'
.You are given a 0-indexed array of integers nums
, and an integer target
.
Return the length of the longest subsequence of nums
that sums up to target
. If no such subsequence exists, return -1
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5], target = 9\nOutput: 3\nExplanation: There are 3 subsequences with a sum equal to 9: [4,5], [1,3,5], and [2,3,4]. The longest subsequences are [1,3,5], and [2,3,4]. Hence, the answer is 3.\n\n\n
Example 2:
\n\n\nInput: nums = [4,1,3,2,1,5], target = 7\nOutput: 4\nExplanation: There are 5 subsequences with a sum equal to 7: [4,3], [4,1,2], [4,2,1], [1,1,5], and [1,3,2,1]. The longest subsequence is [1,3,2,1]. Hence, the answer is 4.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,5,4,5], target = 3\nOutput: -1\nExplanation: It can be shown that nums has no subsequence that sums up to 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
1 <= target <= 1000
You are given a 0-indexed integer array nums
.
The distinct count of a subarray of nums
is defined as:
nums[i..j]
be a subarray of nums
consisting of all the indices from i
to j
such that 0 <= i <= j < nums.length
. Then the number of distinct values in nums[i..j]
is called the distinct count of nums[i..j]
.Return the sum of the squares of distinct counts of all subarrays of nums
.
Since the answer may be very large, return it modulo 109 + 7
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,1]\nOutput: 15\nExplanation: Six possible subarrays are:\n[1]: 1 distinct value\n[2]: 1 distinct value\n[1]: 1 distinct value\n[1,2]: 2 distinct values\n[2,1]: 2 distinct values\n[1,2,1]: 2 distinct values\nThe sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 + 22 + 22 + 22 = 15.\n\n\n
Example 2:
\n\n\nInput: nums = [2,2]\nOutput: 3\nExplanation: Three possible subarrays are:\n[2]: 1 distinct value\n[2]: 1 distinct value\n[2,2]: 1 distinct value\nThe sum of the squares of the distinct counts in all subarrays is equal to 12 + 12 + 12 = 3.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
You are given an integer array nums
, and an integer k
. Let's introduce K-or operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to 1
if at least k
numbers in nums
have a 1
in that position.
Return the K-or of nums
.
\n
Example 1:
\n\nInput: nums = [7,12,9,8,9,15], k = 4
\n\nOutput: 9
\n\nExplanation:
\n\nRepresent numbers in binary:
\n\nNumber | \n\t\t\tBit 3 | \n\t\t\tBit 2 | \n\t\t\tBit 1 | \n\t\t\tBit 0 | \n\t\t
---|---|---|---|---|
7 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
12 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
9 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
8 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
9 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
15 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
Result = 9 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15.
\nOnly bits 0 and 3 qualify. The result is (1001)2 = 9
.
Example 2:
\n\nInput: nums = [2,12,1,11,4,5], k = 6
\n\nOutput: 0
\n\nExplanation: No bit appears as 1 in all six array numbers, as required for K-or with k = 6
. Thus, the result is 0.
Example 3:
\n\nInput: nums = [10,8,5,9,11,6,8], k = 1
\n\nOutput: 15
\n\nExplanation: Since k == 1
, the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is 10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15
.
\n
Constraints:
\n\n1 <= nums.length <= 50
0 <= nums[i] < 231
1 <= k <= nums.length
You are given two arrays nums1
and nums2
consisting of positive integers.
You have to replace all the 0
's in both arrays with strictly positive integers such that the sum of elements of both arrays becomes equal.
Return the minimum equal sum you can obtain, or -1
if it is impossible.
\n
Example 1:
\n\n\nInput: nums1 = [3,2,0,1,0], nums2 = [6,5,0]\nOutput: 12\nExplanation: We can replace 0's in the following way:\n- Replace the two 0's in nums1 with the values 2 and 4. The resulting array is nums1 = [3,2,2,1,4].\n- Replace the 0 in nums2 with the value 1. The resulting array is nums2 = [6,5,1].\nBoth arrays have an equal sum of 12. It can be shown that it is the minimum sum we can obtain.\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,0,2,0], nums2 = [1,4]\nOutput: -1\nExplanation: It is impossible to make the sum of both arrays equal.\n\n\n
\n
Constraints:
\n\n1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[i] <= 106
You are given a 0-indexed integer array nums
having length n
, and an integer k
.
You can perform the following increment operation any number of times (including zero):
\n\ni
in the range [0, n - 1]
, and increase nums[i]
by 1
.An array is considered beautiful if, for any subarray with a size of 3
or more, its maximum element is greater than or equal to k
.
Return an integer denoting the minimum number of increment operations needed to make nums
beautiful.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,3,0,0,2], k = 4\nOutput: 3\nExplanation: We can perform the following increment operations to make nums beautiful:\nChoose index i = 1 and increase nums[1] by 1 -> [2,4,0,0,2].\nChoose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,3].\nChoose index i = 4 and increase nums[4] by 1 -> [2,4,0,0,4].\nThe subarrays with a size of 3 or more are: [2,4,0], [4,0,0], [0,0,4], [2,4,0,0], [4,0,0,4], [2,4,0,0,4].\nIn all the subarrays, the maximum element is equal to k = 4, so nums is now beautiful.\nIt can be shown that nums cannot be made beautiful with fewer than 3 increment operations.\nHence, the answer is 3.\n\n\n
Example 2:
\n\n\nInput: nums = [0,1,3,3], k = 5\nOutput: 2\nExplanation: We can perform the following increment operations to make nums beautiful:\nChoose index i = 2 and increase nums[2] by 1 -> [0,1,4,3].\nChoose index i = 2 and increase nums[2] by 1 -> [0,1,5,3].\nThe subarrays with a size of 3 or more are: [0,1,5], [1,5,3], [0,1,5,3].\nIn all the subarrays, the maximum element is equal to k = 5, so nums is now beautiful.\nIt can be shown that nums cannot be made beautiful with fewer than 2 increment operations.\nHence, the answer is 2.\n\n\n
Example 3:
\n\n\nInput: nums = [1,1,2], k = 1\nOutput: 0\nExplanation: The only subarray with a size of 3 or more in this example is [1,1,2].\nThe maximum element, 2, is already greater than k = 1, so we don't need any increment operation.\nHence, the answer is 0.\n\n\n
\n
Constraints:
\n\n3 <= n == nums.length <= 105
0 <= nums[i] <= 109
0 <= k <= 109
There exists an undirected tree rooted at node 0
with n
nodes labeled from 0
to n - 1
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree. You are also given a 0-indexed array coins
of size n
where coins[i]
indicates the number of coins in the vertex i
, and an integer k
.
Starting from the root, you have to collect all the coins such that the coins at a node can only be collected if the coins of its ancestors have been already collected.
\n\nCoins at nodei
can be collected in one of the following ways:
coins[i] - k
points. If coins[i] - k
is negative then you will lose abs(coins[i] - k)
points.floor(coins[i] / 2)
points. If this way is used, then for all the nodej
present in the subtree of nodei
, coins[j]
will get reduced to floor(coins[j] / 2)
.Return the maximum points you can get after collecting the coins from all the tree nodes.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1],[1,2],[2,3]], coins = [10,10,3,3], k = 5\nOutput: 11 \nExplanation: \nCollect all the coins from node 0 using the first way. Total points = 10 - 5 = 5.\nCollect all the coins from node 1 using the first way. Total points = 5 + (10 - 5) = 10.\nCollect all the coins from node 2 using the second way so coins left at node 3 will be floor(3 / 2) = 1. Total points = 10 + floor(3 / 2) = 11.\nCollect all the coins from node 3 using the second way. Total points = 11 + floor(1 / 2) = 11.\nIt can be shown that the maximum points we can get after collecting coins from all the nodes is 11. \n\n\n
Example 2:
\n\nInput: edges = [[0,1],[0,2]], coins = [8,4,4], k = 0\nOutput: 16\nExplanation: \nCoins will be collected from all the nodes using the first way. Therefore, total points = (8 - 0) + (4 - 0) + (4 - 0) = 16.\n\n\n
\n
Constraints:
\n\nn == coins.length
2 <= n <= 105
0 <= coins[i] <= 104
edges.length == n - 1
0 <= edges[i][0], edges[i][1] < n
0 <= k <= 104
There are n
teams numbered from 0
to n - 1
in a tournament.
Given a 0-indexed 2D boolean matrix grid
of size n * n
. For all i, j
that 0 <= i, j <= n - 1
and i != j
team i
is stronger than team j
if grid[i][j] == 1
, otherwise, team j
is stronger than team i
.
Team a
will be the champion of the tournament if there is no team b
that is stronger than team a
.
Return the team that will be the champion of the tournament.
\n\n\n
Example 1:
\n\n\nInput: grid = [[0,1],[0,0]]\nOutput: 0\nExplanation: There are two teams in this tournament.\ngrid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion.\n\n\n
Example 2:
\n\n\nInput: grid = [[0,0,1],[1,0,1],[0,0,0]]\nOutput: 1\nExplanation: There are three teams in this tournament.\ngrid[1][0] == 1 means that team 1 is stronger than team 0.\ngrid[1][2] == 1 means that team 1 is stronger than team 2.\nSo team 1 will be the champion.\n\n\n
\n
Constraints:
\n\nn == grid.length
n == grid[i].length
2 <= n <= 100
grid[i][j]
is either 0
or 1
.i grid[i][i]
is 0.
i, j
that i != j
, grid[i][j] != grid[j][i]
.a
is stronger than team b
and team b
is stronger than team c
, then team a
is stronger than team c
.There are n
teams numbered from 0
to n - 1
in a tournament; each team is also a node in a DAG.
You are given the integer n
and a 0-indexed 2D integer array edges
of length m
representing the DAG, where edges[i] = [ui, vi]
indicates that there is a directed edge from team ui
to team vi
in the graph.
A directed edge from a
to b
in the graph means that team a
is stronger than team b
and team b
is weaker than team a
.
Team a
will be the champion of the tournament if there is no team b
that is stronger than team a
.
Return the team that will be the champion of the tournament if there is a unique champion, otherwise, return -1
.
Notes
\n\na1, a2, ..., an, an+1
such that node a1
is the same node as node an+1
, the nodes a1, a2, ..., an
are distinct, and there is a directed edge from the node ai
to node ai+1
for every i
in the range [1, n]
.\n
Example 1:
\n\n\nInput: n = 3, edges = [[0,1],[1,2]]\nOutput: 0\nExplanation: Team 1 is weaker than team 0. Team 2 is weaker than team 1. So the champion is team 0.\n\n\n
Example 2:
\n\n\nInput: n = 4, edges = [[0,2],[1,3],[1,2]]\nOutput: -1\nExplanation: Team 2 is weaker than team 0 and team 1. Team 3 is weaker than team 1. But team 1 and team 0 are not weaker than any other teams. So the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= n <= 100
m == edges.length
0 <= m <= n * (n - 1) / 2
edges[i].length == 2
0 <= edge[i][j] <= n - 1
edges[i][0] != edges[i][1]
a
is stronger than team b
, team b
is not stronger than team a
.a
is stronger than team b
and team b
is stronger than team c
, then team a
is stronger than team c
.There is an undirected tree with n
nodes labeled from 0
to n - 1
, and rooted at node 0
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
You are also given a 0-indexed integer array values
of length n
, where values[i]
is the value associated with the ith
node.
You start with a score of 0
. In one operation, you can:
i
.values[i]
to your score.values[i]
to 0
.A tree is healthy if the sum of values on the path from the root to any leaf node is different than zero.
\n\nReturn the maximum score you can obtain after performing these operations on the tree any number of times so that it remains healthy.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]\nOutput: 11\nExplanation: We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11.\nIt can be shown that 11 is the maximum score obtainable after any number of operations on the tree.\n\n\n
Example 2:
\n\nInput: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]\nOutput: 40\nExplanation: We can choose nodes 0, 2, 3, and 4.\n- The sum of values on the path from 0 to 4 is equal to 10.\n- The sum of values on the path from 0 to 3 is equal to 10.\n- The sum of values on the path from 0 to 5 is equal to 3.\n- The sum of values on the path from 0 to 6 is equal to 5.\nTherefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.\nIt can be shown that 40 is the maximum score obtainable after any number of operations on the tree.\n\n\n
\n
Constraints:
\n\n2 <= n <= 2 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
values.length == n
1 <= values[i] <= 109
edges
represents a valid tree.You are given a 0-indexed integer array nums
.
A subsequence of nums
having length k
and consisting of indices i0 < i1 < ... < ik-1
is balanced if the following holds:
nums[ij] - nums[ij-1] >= ij - ij-1
, for every j
in the range [1, k - 1]
.A subsequence of nums
having length 1
is considered balanced.
Return an integer denoting the maximum possible sum of elements in a balanced subsequence of nums
.
A subsequence of an array is a new non-empty array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,3,5,6]\nOutput: 14\nExplanation: In this example, the subsequence [3,5,6] consisting of indices 0, 2, and 3 can be selected.\nnums[2] - nums[0] >= 2 - 0.\nnums[3] - nums[2] >= 3 - 2.\nHence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.\nThe subsequence consisting of indices 1, 2, and 3 is also valid.\nIt can be shown that it is not possible to get a balanced subsequence with a sum greater than 14.\n\n
Example 2:
\n\n\nInput: nums = [5,-1,-3,8]\nOutput: 13\nExplanation: In this example, the subsequence [5,8] consisting of indices 0 and 3 can be selected.\nnums[3] - nums[0] >= 3 - 0.\nHence, it is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.\nIt can be shown that it is not possible to get a balanced subsequence with a sum greater than 13.\n\n\n
Example 3:
\n\n\nInput: nums = [-2,-1]\nOutput: -1\nExplanation: In this example, the subsequence [-1] can be selected.\nIt is a balanced subsequence, and its sum is the maximum among the balanced subsequences of nums.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
You are given two positive integers n
and limit
.
Return the total number of ways to distribute n
candies among 3
children such that no child gets more than limit
candies.
\n
Example 1:
\n\n\nInput: n = 5, limit = 2\nOutput: 3\nExplanation: There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).\n\n\n
Example 2:
\n\n\nInput: n = 3, limit = 3\nOutput: 10\nExplanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).\n\n\n
\n
Constraints:
\n\n1 <= n <= 50
1 <= limit <= 50
You are given two positive integers n
and limit
.
Return the total number of ways to distribute n
candies among 3
children such that no child gets more than limit
candies.
\n
Example 1:
\n\n\nInput: n = 5, limit = 2\nOutput: 3\nExplanation: There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).\n\n\n
Example 2:
\n\n\nInput: n = 3, limit = 3\nOutput: 10\nExplanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).\n\n\n
\n
Constraints:
\n\n1 <= n <= 106
1 <= limit <= 106
You are given an integer n
.
A string s
is called good if it contains only lowercase English characters and it is possible to rearrange the characters of s
such that the new string contains "leet"
as a substring.
For example:
\n\n"lteer"
is good because we can rearrange it to form "leetr"
."letl"
is not good because we cannot rearrange it to contain "leet"
as a substring.Return the total number of good strings of length n
.
Since the answer may be large, return it modulo 109 + 7
.
A substring is a contiguous sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: n = 4\nOutput: 12\nExplanation: The 12 strings which can be rearranged to have "leet" as a substring are: "eelt", "eetl", "elet", "elte", "etel", "etle", "leet", "lete", "ltee", "teel", "tele", and "tlee".\n\n\n
Example 2:
\n\n\nInput: n = 10\nOutput: 83943898\nExplanation: The number of strings with length 10 which can be rearranged to have "leet" as a substring is 526083947580. Hence the answer is 526083947580 % (109 + 7) = 83943898.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
You are given a 0-indexed m * n
integer matrix values
, representing the values of m * n
different items in m
different shops. Each shop has n
items where the jth
item in the ith
shop has a value of values[i][j]
. Additionally, the items in the ith
shop are sorted in non-increasing order of value. That is, values[i][j] >= values[i][j + 1]
for all 0 <= j < n - 1
.
On each day, you would like to buy a single item from one of the shops. Specifically, On the dth
day you can:
i
.j
for the price of values[i][j] * d
. That is, find the greatest index j
such that item j
was never bought before, and buy it for the price of values[i][j] * d
.Note that all items are pairwise different. For example, if you have bought item 0
from shop 1
, you can still buy item 0
from any other shop.
Return the maximum amount of money that can be spent on buying all m * n
products.
\n
Example 1:
\n\n\nInput: values = [[8,5,2],[6,4,1],[9,7,3]]\nOutput: 285\nExplanation: On the first day, we buy product 2 from shop 1 for a price of values[1][2] * 1 = 1.\nOn the second day, we buy product 2 from shop 0 for a price of values[0][2] * 2 = 4.\nOn the third day, we buy product 2 from shop 2 for a price of values[2][2] * 3 = 9.\nOn the fourth day, we buy product 1 from shop 1 for a price of values[1][1] * 4 = 16.\nOn the fifth day, we buy product 1 from shop 0 for a price of values[0][1] * 5 = 25.\nOn the sixth day, we buy product 0 from shop 1 for a price of values[1][0] * 6 = 36.\nOn the seventh day, we buy product 1 from shop 2 for a price of values[2][1] * 7 = 49.\nOn the eighth day, we buy product 0 from shop 0 for a price of values[0][0] * 8 = 64.\nOn the ninth day, we buy product 0 from shop 2 for a price of values[2][0] * 9 = 81.\nHence, our total spending is equal to 285.\nIt can be shown that 285 is the maximum amount of money that can be spent buying all m * n products. \n\n\n
Example 2:
\n\n\nInput: values = [[10,8,6,4,2],[9,7,5,3,2]]\nOutput: 386\nExplanation: On the first day, we buy product 4 from shop 0 for a price of values[0][4] * 1 = 2.\nOn the second day, we buy product 4 from shop 1 for a price of values[1][4] * 2 = 4.\nOn the third day, we buy product 3 from shop 1 for a price of values[1][3] * 3 = 9.\nOn the fourth day, we buy product 3 from shop 0 for a price of values[0][3] * 4 = 16.\nOn the fifth day, we buy product 2 from shop 1 for a price of values[1][2] * 5 = 25.\nOn the sixth day, we buy product 2 from shop 0 for a price of values[0][2] * 6 = 36.\nOn the seventh day, we buy product 1 from shop 1 for a price of values[1][1] * 7 = 49.\nOn the eighth day, we buy product 1 from shop 0 for a price of values[0][1] * 8 = 64\nOn the ninth day, we buy product 0 from shop 1 for a price of values[1][0] * 9 = 81.\nOn the tenth day, we buy product 0 from shop 0 for a price of values[0][0] * 10 = 100.\nHence, our total spending is equal to 386.\nIt can be shown that 386 is the maximum amount of money that can be spent buying all m * n products.\n\n\n
\n
Constraints:
\n\n1 <= m == values.length <= 10
1 <= n == values[i].length <= 104
1 <= values[i][j] <= 106
values[i]
are sorted in non-increasing order.You are given a 0-indexed integer array nums
. A pair of integers x
and y
is called a strong pair if it satisfies the condition:
|x - y| <= min(x, y)
You need to select two integers from nums
such that they form a strong pair and their bitwise XOR
is the maximum among all strong pairs in the array.
Return the maximum XOR
value out of all possible strong pairs in the array nums
.
Note that you can pick the same integer twice to form a pair.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 7\nExplanation: There are 11 strong pairs in the array nums
: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).\nThe maximum XOR possible from these pairs is 3 XOR 4 = 7.\n
\n\nExample 2:
\n\n\nInput: nums = [10,100]\nOutput: 0\nExplanation: There are 2 strong pairs in the array nums
: (10, 10) and (100, 100).\nThe maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.\n
\n\nExample 3:
\n\n\nInput: nums = [5,6,25,30]\nOutput: 7\nExplanation: There are 6 strong pairs in the array nums
: (5, 5), (5, 6), (6, 6), (25, 25), (25, 30) and (30, 30).\nThe maximum XOR possible from these pairs is 25 XOR 30 = 7 since the only other non-zero XOR value is 5 XOR 6 = 3.\n
\n\n\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 100
You are given a 2D 0-indexed array of strings, access_times
, with size n
. For each i
where 0 <= i <= n - 1
, access_times[i][0]
represents the name of an employee, and access_times[i][1]
represents the access time of that employee. All entries in access_times
are within the same day.
The access time is represented as four digits using a 24-hour time format, for example, "0800"
or "2250"
.
An employee is said to be high-access if he has accessed the system three or more times within a one-hour period.
\n\nTimes with exactly one hour of difference are not considered part of the same one-hour period. For example, "0815"
and "0915"
are not part of the same one-hour period.
Access times at the start and end of the day are not counted within the same one-hour period. For example, "0005"
and "2350"
are not part of the same one-hour period.
Return a list that contains the names of high-access employees with any order you want.
\n\n\n
Example 1:
\n\n\nInput: access_times = [["a","0549"],["b","0457"],["a","0532"],["a","0621"],["b","0540"]]\nOutput: ["a"]\nExplanation: "a" has three access times in the one-hour period of [05:32, 06:31] which are 05:32, 05:49, and 06:21.\nBut "b" does not have more than two access times at all.\nSo the answer is ["a"].\n\n
Example 2:
\n\n\nInput: access_times = [["d","0002"],["c","0808"],["c","0829"],["e","0215"],["d","1508"],["d","1444"],["d","1410"],["c","0809"]]\nOutput: ["c","d"]\nExplanation: "c" has three access times in the one-hour period of [08:08, 09:07] which are 08:08, 08:09, and 08:29.\n"d" has also three access times in the one-hour period of [14:10, 15:09] which are 14:10, 14:44, and 15:08.\nHowever, "e" has just one access time, so it can not be in the answer and the final answer is ["c","d"].\n\n
Example 3:
\n\n\nInput: access_times = [["cd","1025"],["ab","1025"],["cd","1046"],["cd","1055"],["ab","1124"],["ab","1120"]]\nOutput: ["ab","cd"]\nExplanation: "ab" has three access times in the one-hour period of [10:25, 11:24] which are 10:25, 11:20, and 11:24.\n"cd" has also three access times in the one-hour period of [10:25, 11:24] which are 10:25, 10:46, and 10:55.\nSo the answer is ["ab","cd"].\n\n
\n
Constraints:
\n\n1 <= access_times.length <= 100
access_times[i].length == 2
1 <= access_times[i][0].length <= 10
access_times[i][0]
consists only of English small letters.access_times[i][1].length == 4
access_times[i][1]
is in 24-hour time format.access_times[i][1]
consists only of '0'
to '9'
.You are given two 0-indexed integer arrays, nums1
and nums2
, both having length n
.
You are allowed to perform a series of operations (possibly none).
\n\nIn an operation, you select an index i
in the range [0, n - 1]
and swap the values of nums1[i]
and nums2[i]
.
Your task is to find the minimum number of operations required to satisfy the following conditions:
\n\nnums1[n - 1]
is equal to the maximum value among all elements of nums1
, i.e., nums1[n - 1] = max(nums1[0], nums1[1], ..., nums1[n - 1])
.nums2[n - 1]
is equal to the maximum value among all elements of nums2
, i.e., nums2[n - 1] = max(nums2[0], nums2[1], ..., nums2[n - 1])
.Return an integer denoting the minimum number of operations needed to meet both conditions, or -1
if it is impossible to satisfy both conditions.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,7], nums2 = [4,5,3]\nOutput: 1\nExplanation: In this example, an operation can be performed using index i = 2.\nWhen nums1[2] and nums2[2] are swapped, nums1 becomes [1,2,3] and nums2 becomes [4,5,7].\nBoth conditions are now satisfied.\nIt can be shown that the minimum number of operations needed to be performed is 1.\nSo, the answer is 1.\n\n\n
Example 2:
\n\n\nInput: nums1 = [2,3,4,5,9], nums2 = [8,8,4,4,4]\nOutput: 2\nExplanation: In this example, the following operations can be performed:\nFirst operation using index i = 4.\nWhen nums1[4] and nums2[4] are swapped, nums1 becomes [2,3,4,5,4], and nums2 becomes [8,8,4,4,9].\nAnother operation using index i = 3.\nWhen nums1[3] and nums2[3] are swapped, nums1 becomes [2,3,4,4,4], and nums2 becomes [8,8,4,5,9].\nBoth conditions are now satisfied.\nIt can be shown that the minimum number of operations needed to be performed is 2.\nSo, the answer is 2. \n\n\n
Example 3:
\n\n\nInput: nums1 = [1,5,4], nums2 = [2,5,3]\nOutput: -1\nExplanation: In this example, it is not possible to satisfy both conditions. \nSo, the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= n == nums1.length == nums2.length <= 1000
1 <= nums1[i] <= 109
1 <= nums2[i] <= 109
You are given a 0-indexed integer array nums
. A pair of integers x
and y
is called a strong pair if it satisfies the condition:
|x - y| <= min(x, y)
You need to select two integers from nums
such that they form a strong pair and their bitwise XOR
is the maximum among all strong pairs in the array.
Return the maximum XOR
value out of all possible strong pairs in the array nums
.
Note that you can pick the same integer twice to form a pair.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 7\nExplanation: There are 11 strong pairs in the array nums
: (1, 1), (1, 2), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (3, 5), (4, 4), (4, 5) and (5, 5).\nThe maximum XOR possible from these pairs is 3 XOR 4 = 7.\n
\n\nExample 2:
\n\n\nInput: nums = [10,100]\nOutput: 0\nExplanation: There are 2 strong pairs in the array nums: (10, 10) and (100, 100).\nThe maximum XOR possible from these pairs is 10 XOR 10 = 0 since the pair (100, 100) also gives 100 XOR 100 = 0.\n\n\n
Example 3:
\n\n\nInput: nums = [500,520,2500,3000]\nOutput: 1020\nExplanation: There are 6 strong pairs in the array nums: (500, 500), (500, 520), (520, 520), (2500, 2500), (2500, 3000) and (3000, 3000).\nThe maximum XOR possible from these pairs is 500 XOR 520 = 1020 since the only other non-zero XOR value is 2500 XOR 3000 = 636.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
1 <= nums[i] <= 220 - 1
You are given three strings: s1
, s2
, and s3
. In one operation you can choose one of these strings and delete its rightmost character. Note that you cannot completely empty a string.
Return the minimum number of operations required to make the strings equal. If it is impossible to make them equal, return -1
.
\n
Example 1:
\n\nInput: s1 = "abc", s2 = "abb", s3 = "ab"
\n\nOutput: 2
\n\nExplanation: Deleting the rightmost character from both s1
and s2
will result in three equal strings.
Example 2:
\n\nInput: s1 = "dac", s2 = "bac", s3 = "cac"
\n\nOutput: -1
\n\nExplanation: Since the first letters of s1
and s2
differ, they cannot be made equal.
\n
Constraints:
\n\n1 <= s1.length, s2.length, s3.length <= 100
s1
, s2
and s3
consist only of lowercase English letters.There are n
balls on a table, each ball has a color black or white.
You are given a 0-indexed binary string s
of length n
, where 1
and 0
represent black and white balls, respectively.
In each step, you can choose two adjacent balls and swap them.
\n\nReturn the minimum number of steps to group all the black balls to the right and all the white balls to the left.
\n\n\n
Example 1:
\n\n\nInput: s = "101"\nOutput: 1\nExplanation: We can group all the black balls to the right in the following way:\n- Swap s[0] and s[1], s = "011".\nInitially, 1s are not grouped together, requiring at least 1 step to group them to the right.\n\n
Example 2:
\n\n\nInput: s = "100"\nOutput: 2\nExplanation: We can group all the black balls to the right in the following way:\n- Swap s[0] and s[1], s = "010".\n- Swap s[1] and s[2], s = "001".\nIt can be proven that the minimum number of steps needed is 2.\n\n\n
Example 3:
\n\n\nInput: s = "0111"\nOutput: 0\nExplanation: All the black balls are already grouped to the right.\n\n\n
\n
Constraints:
\n\n1 <= n == s.length <= 105
s[i]
is either '0'
or '1'
.Given three integers a
, b
, and n
, return the maximum value of (a XOR x) * (b XOR x)
where 0 <= x < 2n
.
Since the answer may be too large, return it modulo 109 + 7
.
Note that XOR
is the bitwise XOR operation.
\n
Example 1:
\n\n\nInput: a = 12, b = 5, n = 4\nOutput: 98\nExplanation: For x = 2, (a XOR x) = 14 and (b XOR x) = 7. Hence, (a XOR x) * (b XOR x) = 98. \nIt can be shown that 98 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.\n
\n\nExample 2:
\n\n\nInput: a = 6, b = 7 , n = 5\nOutput: 930\nExplanation: For x = 25, (a XOR x) = 31 and (b XOR x) = 30. Hence, (a XOR x) * (b XOR x) = 930.\nIt can be shown that 930 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.\n\n
Example 3:
\n\n\nInput: a = 1, b = 6, n = 3\nOutput: 12\nExplanation: For x = 5, (a XOR x) = 4 and (b XOR x) = 3. Hence, (a XOR x) * (b XOR x) = 12.\nIt can be shown that 12 is the maximum value of (a XOR x) * (b XOR x) for all 0 <= x < 2n.\n\n\n
\n
Constraints:
\n\n0 <= a, b < 250
0 <= n <= 50
You are given a 0-indexed array heights
of positive integers, where heights[i]
represents the height of the ith
building.
If a person is in building i
, they can move to any other building j
if and only if i < j
and heights[i] < heights[j]
.
You are also given another array queries
where queries[i] = [ai, bi]
. On the ith
query, Alice is in building ai
while Bob is in building bi
.
Return an array ans
where ans[i]
is the index of the leftmost building where Alice and Bob can meet on the ith
query. If Alice and Bob cannot move to a common building on query i
, set ans[i]
to -1
.
\n
Example 1:
\n\n\nInput: heights = [6,4,8,5,2,7], queries = [[0,1],[0,3],[2,4],[3,4],[2,2]]\nOutput: [2,5,-1,5,2]\nExplanation: In the first query, Alice and Bob can move to building 2 since heights[0] < heights[2] and heights[1] < heights[2]. \nIn the second query, Alice and Bob can move to building 5 since heights[0] < heights[5] and heights[3] < heights[5]. \nIn the third query, Alice cannot meet Bob since Alice cannot move to any other building.\nIn the fourth query, Alice and Bob can move to building 5 since heights[3] < heights[5] and heights[4] < heights[5].\nIn the fifth query, Alice and Bob are already in the same building. \nFor ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.\nFor ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.\n\n\n
Example 2:
\n\n\nInput: heights = [5,3,8,2,6,1,4,6], queries = [[0,7],[3,5],[5,2],[3,0],[1,6]]\nOutput: [7,6,-1,4,6]\nExplanation: In the first query, Alice can directly move to Bob's building since heights[0] < heights[7].\nIn the second query, Alice and Bob can move to building 6 since heights[3] < heights[6] and heights[5] < heights[6].\nIn the third query, Alice cannot meet Bob since Bob cannot move to any other building.\nIn the fourth query, Alice and Bob can move to building 4 since heights[3] < heights[4] and heights[0] < heights[4].\nIn the fifth query, Alice can directly move to Bob's building since heights[1] < heights[6].\nFor ans[i] != -1, It can be shown that ans[i] is the leftmost building where Alice and Bob can meet.\nFor ans[i] == -1, It can be shown that there is no building where Alice and Bob can meet.\n\n\n\n
\n
Constraints:
\n\n1 <= heights.length <= 5 * 104
1 <= heights[i] <= 109
1 <= queries.length <= 5 * 104
queries[i] = [ai, bi]
0 <= ai, bi <= heights.length - 1
You are given a 0-indexed array of strings words
and a character x
.
Return an array of indices representing the words that contain the character x
.
Note that the returned array may be in any order.
\n\n\n
Example 1:
\n\n\nInput: words = ["leet","code"], x = "e"\nOutput: [0,1]\nExplanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1.\n\n\n
Example 2:
\n\n\nInput: words = ["abc","bcd","aaaa","cbc"], x = "a"\nOutput: [0,2]\nExplanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2.\n\n\n
Example 3:
\n\n\nInput: words = ["abc","bcd","aaaa","cbc"], x = "z"\nOutput: []\nExplanation: "z" does not occur in any of the words. Hence, we return an empty array.\n\n\n
\n
Constraints:
\n\n1 <= words.length <= 50
1 <= words[i].length <= 50
x
is a lowercase English letter.words[i]
consists only of lowercase English letters.You are given the two integers, n
and m
and two integer arrays, hBars
and vBars
. The grid has n + 2
horizontal and m + 2
vertical bars, creating 1 x 1 unit cells. The bars are indexed starting from 1
.
You can remove some of the bars in hBars
from horizontal bars and some of the bars in vBars
from vertical bars. Note that other bars are fixed and cannot be removed.
Return an integer denoting the maximum area of a square-shaped hole in the grid, after removing some bars (possibly none).
\n\n\n
Example 1:
\n\nInput: n = 2, m = 1, hBars = [2,3], vBars = [2]
\n\nOutput: 4
\n\nExplanation:
\n\nThe left image shows the initial grid formed by the bars. The horizontal bars are [1,2,3,4]
, and the vertical bars are [1,2,3]
.
One way to get the maximum square-shaped hole is by removing horizontal bar 2 and vertical bar 2.
\nExample 2:
\n\nInput: n = 1, m = 1, hBars = [2], vBars = [2]
\n\nOutput: 4
\n\nExplanation:
\n\nTo get the maximum square-shaped hole, we remove horizontal bar 2 and vertical bar 2.
\nExample 3:
\n\nInput: n = 2, m = 3, hBars = [2,3], vBars = [2,4]
\n\nOutput: 4
\n\nExplanation:
\n\nOne way to get the maximum square-shaped hole is by removing horizontal bar 3, and vertical bar 4.
\n\n
Constraints:
\n\n1 <= n <= 109
1 <= m <= 109
1 <= hBars.length <= 100
2 <= hBars[i] <= n + 1
1 <= vBars.length <= 100
2 <= vBars[i] <= m + 1
hBars
are distinct.vBars
are distinct.You are given an 0-indexed integer array prices
where prices[i]
denotes the number of coins needed to purchase the (i + 1)th
fruit.
The fruit market has the following reward for each fruit:
\n\n(i + 1)th
fruit at prices[i]
coins, you can get any number of the next i
fruits for free.Note that even if you can take fruit j
for free, you can still purchase it for prices[j - 1]
coins to receive its reward.
Return the minimum number of coins needed to acquire all the fruits.
\n\n\n
Example 1:
\n\nInput: prices = [3,1,2]
\n\nOutput: 4
\n\nExplanation:
\n\nprices[0] = 3
coins, you are allowed to take the 2nd fruit for free.prices[1] = 1
coin, you are allowed to take the 3rd fruit for free.Note that even though you could take the 2nd fruit for free as a reward of buying 1st fruit, you purchase it to receive its reward, which is more optimal.
\nExample 2:
\n\nInput: prices = [1,10,1,1]
\n\nOutput: 2
\n\nExplanation:
\n\nprices[0] = 1
coin, you are allowed to take the 2nd fruit for free.prices[2] = 1
coin, you are allowed to take the 4th fruit for free.Example 3:
\n\nInput: prices = [26,18,6,12,49,7,45,45]
\n\nOutput: 39
\n\nExplanation:
\n\nprices[0] = 26
coin, you are allowed to take the 2nd fruit for free.prices[2] = 6
coin, you are allowed to take the 4th, 5th and 6th (the next three) fruits for free.prices[5] = 7
coin, you are allowed to take the 8th and 9th fruit for free.Note that even though you could take the 6th fruit for free as a reward of buying 3rd fruit, you purchase it to receive its reward, which is more optimal.
\n\n
Constraints:
\n\n1 <= prices.length <= 1000
1 <= prices[i] <= 105
You are given a 0-indexed integer array nums
.
You can perform any number of operations, where each operation involves selecting a subarray of the array and replacing it with the sum of its elements. For example, if the given array is [1,3,5,6]
and you select subarray [3,5]
the array will convert to [1,8,6]
.
Return the maximum length of a non-decreasing array that can be made after applying operations.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [5,2,2]\nOutput: 1\nExplanation: This array with length 3 is not non-decreasing.\nWe have two ways to make the array length two.\nFirst, choosing subarray [2,2] converts the array to [5,4].\nSecond, choosing subarray [5,2] converts the array to [7,2].\nIn these two ways the array is not non-decreasing.\nAnd if we choose subarray [5,2,2] and replace it with [9] it becomes non-decreasing. \nSo the answer is 1.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 4\nExplanation: The array is non-decreasing. So the answer is 4.\n\n\n
Example 3:
\n\n\nInput: nums = [4,3,2,6]\nOutput: 3\nExplanation: Replacing [3,2] with [5] converts the given array to [4,5,6] that is non-decreasing.\nBecause the given array is not non-decreasing, the maximum possible answer is 3.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
You are given an m x n
integer matrix mat
and an integer k
. The matrix rows are 0-indexed.
The following proccess happens k
times:
Return true
if the final modified matrix after k
steps is identical to the original matrix, and false
otherwise.
\n
Example 1:
\n\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 4
\n\nOutput: false
\n\nExplanation:
\n\nIn each step left shift is applied to rows 0 and 2 (even indices), and right shift to row 1 (odd index).
\n\nExample 2:
\n\nInput: mat = [[1,2,1,2],[5,5,5,5],[6,3,6,3]], k = 2
\n\nOutput: true
\n\nExplanation:
\n\nExample 3:
\n\nInput: mat = [[2,2],[2,2]], k = 3
\n\nOutput: true
\n\nExplanation:
\n\nAs all the values are equal in the matrix, even after performing cyclic shifts the matrix will remain the same.
\n\n
Constraints:
\n\n1 <= mat.length <= 25
1 <= mat[i].length <= 25
1 <= mat[i][j] <= 25
1 <= k <= 50
You are given a string s
and a positive integer k
.
Let vowels
and consonants
be the number of vowels and consonants in a string.
A string is beautiful if:
\n\nvowels == consonants
.(vowels * consonants) % k == 0
, in other terms the multiplication of vowels
and consonants
is divisible by k
.Return the number of non-empty beautiful substrings in the given string s
.
A substring is a contiguous sequence of characters in a string.
\n\nVowel letters in English are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Consonant letters in English are every letter except vowels.
\n\n\n
Example 1:
\n\n\nInput: s = "baeyh", k = 2\nOutput: 2\nExplanation: There are 2 beautiful substrings in the given string.\n- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]).\nYou can see that string "aeyh" is beautiful as vowels == consonants and vowels * consonants % k == 0.\n- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]). \nYou can see that string "baey" is beautiful as vowels == consonants and vowels * consonants % k == 0.\nIt can be shown that there are only 2 beautiful substrings in the given string.\n\n\n
Example 2:
\n\n\nInput: s = "abba", k = 1\nOutput: 3\nExplanation: There are 3 beautiful substrings in the given string.\n- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]). \n- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).\n- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]).\nIt can be shown that there are only 3 beautiful substrings in the given string.\n\n\n
Example 3:
\n\n\nInput: s = "bcdf", k = 1\nOutput: 0\nExplanation: There are no beautiful substrings in the given string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 1000
1 <= k <= 1000
s
consists of only English lowercase letters.You are given a 0-indexed array of positive integers nums
and a positive integer limit
.
In one operation, you can choose any two indices i
and j
and swap nums[i]
and nums[j]
if |nums[i] - nums[j]| <= limit
.
Return the lexicographically smallest array that can be obtained by performing the operation any number of times.
\n\nAn array a
is lexicographically smaller than an array b
if in the first position where a
and b
differ, array a
has an element that is less than the corresponding element in b
. For example, the array [2,10,3]
is lexicographically smaller than the array [10,2,3]
because they differ at index 0
and 2 < 10
.
\n
Example 1:
\n\n\nInput: nums = [1,5,3,9,8], limit = 2\nOutput: [1,3,5,8,9]\nExplanation: Apply the operation 2 times:\n- Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8]\n- Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9]\nWe cannot obtain a lexicographically smaller array by applying any more operations.\nNote that it may be possible to get the same result by doing different operations.\n\n\n
Example 2:
\n\n\nInput: nums = [1,7,6,18,2,1], limit = 3\nOutput: [1,6,7,18,1,2]\nExplanation: Apply the operation 3 times:\n- Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1]\n- Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1]\n- Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2]\nWe cannot obtain a lexicographically smaller array by applying any more operations.\n\n\n
Example 3:
\n\n\nInput: nums = [1,7,28,19,10], limit = 3\nOutput: [1,7,28,19,10]\nExplanation: [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= limit <= 109
You are given a string s
and a positive integer k
.
Let vowels
and consonants
be the number of vowels and consonants in a string.
A string is beautiful if:
\n\nvowels == consonants
.(vowels * consonants) % k == 0
, in other terms the multiplication of vowels
and consonants
is divisible by k
.Return the number of non-empty beautiful substrings in the given string s
.
A substring is a contiguous sequence of characters in a string.
\n\nVowel letters in English are 'a'
, 'e'
, 'i'
, 'o'
, and 'u'
.
Consonant letters in English are every letter except vowels.
\n\n\n
Example 1:
\n\n\nInput: s = "baeyh", k = 2\nOutput: 2\nExplanation: There are 2 beautiful substrings in the given string.\n- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]).\nYou can see that string "aeyh" is beautiful as vowels == consonants and vowels * consonants % k == 0.\n- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]).\nYou can see that string "baey" is beautiful as vowels == consonants and vowels * consonants % k == 0.\nIt can be shown that there are only 2 beautiful substrings in the given string.\n\n\n
Example 2:
\n\n\nInput: s = "abba", k = 1\nOutput: 3\nExplanation: There are 3 beautiful substrings in the given string.\n- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).\n- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).\n- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]).\nIt can be shown that there are only 3 beautiful substrings in the given string.\n\n\n
Example 3:
\n\n\nInput: s = "bcdf", k = 1\nOutput: 0\nExplanation: There are no beautiful substrings in the given string.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 104
1 <= k <= 1000
s
consists of only English lowercase letters.O(n * n)
.",
@@ -111142,9 +111432,9 @@
"questionFrontendId": "2951",
"title": "Find the Peaks",
"content": "You are given a 0-indexed array mountain
. Your task is to find all the peaks in the mountain
array.
Return an array that consists of indices of peaks in the given array in any order.
\n\nNotes:
\n\n\n
Example 1:
\n\n\nInput: mountain = [2,4,4]\nOutput: []\nExplanation: mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array.\nmountain[1] also can not be a peak because it is not strictly greater than mountain[2].\nSo the answer is [].\n\n\n
Example 2:
\n\n\nInput: mountain = [1,4,3,8,5]\nOutput: [1,3]\nExplanation: mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array.\nmountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1].\nBut mountain [1] and mountain[3] are strictly greater than their neighboring elements.\nSo the answer is [1,3].\n\n\n
\n
Constraints:
\n\n3 <= mountain.length <= 100
1 <= mountain[i] <= 100
You are given a 0-indexed integer array coins
, representing the values of the coins available, and an integer target
.
An integer x
is obtainable if there exists a subsequence of coins
that sums to x
.
Return the minimum number of coins of any value that need to be added to the array so that every integer in the range [1, target]
is obtainable.
A subsequence of an array is a new non-empty array that is formed from the original array by deleting some (possibly none) of the elements without disturbing the relative positions of the remaining elements.
\n\n\n
Example 1:
\n\n\nInput: coins = [1,4,10], target = 19\nOutput: 2\nExplanation: We need to add coins 2 and 8. The resulting array will be [1,2,4,8,10].\nIt can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 2 is the minimum number of coins that need to be added to the array. \n\n\n
Example 2:
\n\n\nInput: coins = [1,4,10,5,7,19], target = 19\nOutput: 1\nExplanation: We only need to add the coin 2. The resulting array will be [1,2,4,5,7,10,19].\nIt can be shown that all integers from 1 to 19 are obtainable from the resulting array, and that 1 is the minimum number of coins that need to be added to the array. \n\n\n
Example 3:
\n\n\nInput: coins = [1,1,1], target = 20\nOutput: 3\nExplanation: We need to add coins 4, 8, and 16. The resulting array will be [1,1,1,4,8,16].\nIt can be shown that all integers from 1 to 20 are obtainable from the resulting array, and that 3 is the minimum number of coins that need to be added to the array.\n\n\n
\n
Constraints:
\n\n1 <= target <= 105
1 <= coins.length <= 105
1 <= coins[i] <= target
You are given a string word
and an integer k
.
A substring s
of word
is complete if:
s
occurs exactly k
times.2
. That is, for any two adjacent characters c1
and c2
in s
, the absolute difference in their positions in the alphabet is at most 2
.Return the number of complete substrings of word
.
A substring is a non-empty contiguous sequence of characters in a string.
\n\n\n
Example 1:
\n\n\nInput: word = "igigee", k = 2\nOutput: 3\nExplanation: The complete substrings where each character appears exactly twice and the difference between adjacent characters is at most 2 are: igigee, igigee, igigee.\n\n\n
Example 2:
\n\n\nInput: word = "aaabbbccc", k = 3\nOutput: 6\nExplanation: The complete substrings where each character appears exactly three times and the difference between adjacent characters is at most 2 are: aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc, aaabbbccc.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 105
word
consists only of lowercase English letters.1 <= k <= word.length
You are given an integer n
and an array sick
sorted in increasing order, representing positions of infected people in a line of n
people.
At each step, one uninfected person adjacent to an infected person gets infected. This process continues until everyone is infected.
\n\nAn infection sequence is the order in which uninfected people become infected, excluding those initially infected.
\n\nReturn the number of different infection sequences possible, modulo 109+7
.
\n
Example 1:
\n\nInput: n = 5, sick = [0,4]
\n\nOutput: 4
\n\nExplanation:
\n\nThere is a total of 6 different sequences overall.
\n\n[1,2,3]
, [1,3,2]
, [3,2,1]
and [3,1,2]
.[2,3,1]
and [2,1,3]
are not valid infection sequences because the person at index 2 cannot be infected at the first step.Example 2:
\n\nInput: n = 4, sick = [1]
\n\nOutput: 3
\n\nExplanation:
\n\nThere is a total of 6 different sequences overall.
\n\n[0,2,3]
, [2,0,3]
and [2,3,0]
.[3,2,0]
, [3,0,2]
, and [0,3,2]
are not valid infection sequences because the infection starts at the person at index 1, then the order of infection is 2, then 3, and hence 3 cannot be infected earlier than 2.\n
Constraints:
\n\n2 <= n <= 105
1 <= sick.length <= n - 1
0 <= sick[i] <= n - 1
sick
is sorted in increasing order.You are given two integer arrays nums1
and nums2
of sizes n
and m
, respectively. Calculate the following values:
answer1
: the number of indices i
such that nums1[i]
exists in nums2
.answer2
: the number of indices i
such that nums2[i]
exists in nums1
.Return [answer1,answer2]
.
\n
Example 1:
\n\nInput: nums1 = [2,3,2], nums2 = [1,2]
\n\nOutput: [2,1]
\n\nExplanation:
\n\nExample 2:
\n\nInput: nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]
\n\nOutput: [3,4]
\n\nExplanation:
\n\nThe elements at indices 1, 2, and 3 in nums1
exist in nums2
as well. So answer1
is 3.
The elements at indices 0, 1, 3, and 4 in nums2
exist in nums1
. So answer2
is 4.
Example 3:
\n\nInput: nums1 = [3,4,2,3], nums2 = [1,5]
\n\nOutput: [0,0]
\n\nExplanation:
\n\nNo numbers are common between nums1
and nums2
, so answer is [0,0].
\n
Constraints:
\n\nn == nums1.length
m == nums2.length
1 <= n, m <= 100
1 <= nums1[i], nums2[i] <= 100
You are given a 0-indexed string word
.
In one operation, you can pick any index i
of word
and change word[i]
to any lowercase English letter.
Return the minimum number of operations needed to remove all adjacent almost-equal characters from word
.
Two characters a
and b
are almost-equal if a == b
or a
and b
are adjacent in the alphabet.
\n
Example 1:
\n\n\nInput: word = "aaaaa"\nOutput: 2\nExplanation: We can change word into "acaca" which does not have any adjacent almost-equal characters.\nIt can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.\n\n\n
Example 2:
\n\n\nInput: word = "abddez"\nOutput: 2\nExplanation: We can change word into "ybdoez" which does not have any adjacent almost-equal characters.\nIt can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 2.\n\n
Example 3:
\n\n\nInput: word = "zyxyxyz"\nOutput: 3\nExplanation: We can change word into "zaxaxaz" which does not have any adjacent almost-equal characters. \nIt can be shown that the minimum number of operations needed to remove all adjacent almost-equal characters from word is 3.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 100
word
consists only of lowercase English letters.You are given an integer array nums
and an integer k
.
The frequency of an element x
is the number of times it occurs in an array.
An array is called good if the frequency of each element in this array is less than or equal to k
.
Return the length of the longest good subarray of nums
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,1,2,3,1,2], k = 2\nOutput: 6\nExplanation: The longest possible good subarray is [1,2,3,1,2,3] since the values 1, 2, and 3 occur at most twice in this subarray. Note that the subarrays [2,3,1,2,3,1] and [3,1,2,3,1,2] are also good.\nIt can be shown that there are no good subarrays with length more than 6.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,1,2,1,2,1,2], k = 1\nOutput: 2\nExplanation: The longest possible good subarray is [1,2] since the values 1 and 2 occur at most once in this subarray. Note that the subarray [2,1] is also good.\nIt can be shown that there are no good subarrays with length more than 2.\n\n\n
Example 3:
\n\n\nInput: nums = [5,5,5,5,5,5,5], k = 4\nOutput: 4\nExplanation: The longest possible good subarray is [5,5,5,5] since the value 5 occurs 4 times in this subarray.\nIt can be shown that there are no good subarrays with length more than 4.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= nums.length
There is a company with n
branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads.
The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (possibly none). However, they want to ensure that the remaining branches have a distance of at most maxDistance
from each other.
The distance between two branches is the minimum total traveled length needed to reach one branch from another.
\n\nYou are given integers n
, maxDistance
, and a 0-indexed 2D array roads
, where roads[i] = [ui, vi, wi]
represents the undirected road between branches ui
and vi
with length wi
.
Return the number of possible sets of closing branches, so that any branch has a distance of at most maxDistance
from any other.
Note that, after closing a branch, the company will no longer have access to any roads connected to it.
\n\nNote that, multiple roads are allowed.
\n\n\n
Example 1:
\n\nInput: n = 3, maxDistance = 5, roads = [[0,1,2],[1,2,10],[0,2,10]]\nOutput: 5\nExplanation: The possible sets of closing branches are:\n- The set [2], after closing, active branches are [0,1] and they are reachable to each other within distance 2.\n- The set [0,1], after closing, the active branch is [2].\n- The set [1,2], after closing, the active branch is [0].\n- The set [0,2], after closing, the active branch is [1].\n- The set [0,1,2], after closing, there are no active branches.\nIt can be proven, that there are only 5 possible sets of closing branches.\n\n\n
Example 2:
\n\nInput: n = 3, maxDistance = 5, roads = [[0,1,20],[0,1,10],[1,2,2],[0,2,2]]\nOutput: 7\nExplanation: The possible sets of closing branches are:\n- The set [], after closing, active branches are [0,1,2] and they are reachable to each other within distance 4.\n- The set [0], after closing, active branches are [1,2] and they are reachable to each other within distance 2.\n- The set [1], after closing, active branches are [0,2] and they are reachable to each other within distance 2.\n- The set [0,1], after closing, the active branch is [2].\n- The set [1,2], after closing, the active branch is [0].\n- The set [0,2], after closing, the active branch is [1].\n- The set [0,1,2], after closing, there are no active branches.\nIt can be proven, that there are only 7 possible sets of closing branches.\n\n\n
Example 3:
\n\n\nInput: n = 1, maxDistance = 10, roads = []\nOutput: 2\nExplanation: The possible sets of closing branches are:\n- The set [], after closing, the active branch is [0].\n- The set [0], after closing, there are no active branches.\nIt can be proven, that there are only 2 possible sets of closing branches.\n\n\n
\n
Constraints:
\n\n1 <= n <= 10
1 <= maxDistance <= 105
0 <= roads.length <= 1000
roads[i].length == 3
0 <= ui, vi <= n - 1
ui != vi
1 <= wi <= 1000
You are given a 0-indexed integer array batteryPercentages
having length n
, denoting the battery percentages of n
0-indexed devices.
Your task is to test each device i
in order from 0
to n - 1
, by performing the following test operations:
batteryPercentages[i]
is greater than 0
:\n\n\tj
in the range [i + 1, n - 1]
by 1
, ensuring their battery percentage never goes below 0
, i.e, batteryPercentages[j] = max(0, batteryPercentages[j] - 1)
.Return an integer denoting the number of devices that will be tested after performing the test operations in order.
\n\n\n
Example 1:
\n\n\nInput: batteryPercentages = [1,1,2,1,3]\nOutput: 3\nExplanation: Performing the test operations in order starting from device 0:\nAt device 0, batteryPercentages[0] > 0, so there is now 1 tested device, and batteryPercentages becomes [1,0,1,0,2].\nAt device 1, batteryPercentages[1] == 0, so we move to the next device without testing.\nAt device 2, batteryPercentages[2] > 0, so there are now 2 tested devices, and batteryPercentages becomes [1,0,1,0,1].\nAt device 3, batteryPercentages[3] == 0, so we move to the next device without testing.\nAt device 4, batteryPercentages[4] > 0, so there are now 3 tested devices, and batteryPercentages stays the same.\nSo, the answer is 3.\n\n\n
Example 2:
\n\n\nInput: batteryPercentages = [0,1,2]\nOutput: 2\nExplanation: Performing the test operations in order starting from device 0:\nAt device 0, batteryPercentages[0] == 0, so we move to the next device without testing.\nAt device 1, batteryPercentages[1] > 0, so there is now 1 tested device, and batteryPercentages becomes [0,1,1].\nAt device 2, batteryPercentages[2] > 0, so there are now 2 tested devices, and batteryPercentages stays the same.\nSo, the answer is 2.\n\n\n
\n
Constraints:
\n\n1 <= n == batteryPercentages.length <= 100
0 <= batteryPercentages[i] <= 100
You are given a 0-indexed 2D array variables
where variables[i] = [ai, bi, ci, mi]
, and an integer target
.
An index i
is good if the following formula holds:
0 <= i < variables.length
((aibi % 10)ci) % mi == target
Return an array consisting of good indices in any order.
\n\n\n
Example 1:
\n\n\nInput: variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2\nOutput: [0,2]\nExplanation: For each index i in the variables array:\n1) For the index 0, variables[0] = [2,3,3,10], (23 % 10)3 % 10 = 2.\n2) For the index 1, variables[1] = [3,3,3,1], (33 % 10)3 % 1 = 0.\n3) For the index 2, variables[2] = [6,1,1,4], (61 % 10)1 % 4 = 2.\nTherefore we return [0,2] as the answer.\n\n\n
Example 2:
\n\n\nInput: variables = [[39,3,1000,1000]], target = 17\nOutput: []\nExplanation: For each index i in the variables array:\n1) For the index 0, variables[0] = [39,3,1000,1000], (393 % 10)1000 % 1000 = 1.\nTherefore we return [] as the answer.\n\n\n
\n
Constraints:
\n\n1 <= variables.length <= 100
variables[i] == [ai, bi, ci, mi]
1 <= ai, bi, ci, mi <= 103
0 <= target <= 103
You are given an integer array nums
and a positive integer k
.
Return the number of subarrays where the maximum element of nums
appears at least k
times in that subarray.
A subarray is a contiguous sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,2,3,3], k = 2\nOutput: 6\nExplanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,2,1], k = 3\nOutput: 0\nExplanation: No subarray contains the element 4 at least 3 times.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= k <= 105
You are given a 0-indexed array nums
consisting of positive integers.
A partition of an array into one or more contiguous subarrays is called good if no two subarrays contain the same number.
\n\nReturn the total number of good partitions of nums
.
Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 8\nExplanation: The 8 possible good partitions are: ([1], [2], [3], [4]), ([1], [2], [3,4]), ([1], [2,3], [4]), ([1], [2,3,4]), ([1,2], [3], [4]), ([1,2], [3,4]), ([1,2,3], [4]), and ([1,2,3,4]).\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1]\nOutput: 1\nExplanation: The only possible good partition is: ([1,1,1,1]).\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,1,3]\nOutput: 2\nExplanation: The 2 possible good partitions are: ([1,2,1], [3]) and ([1,2,1,3]).\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed 2D integer matrix grid
of size n * n
with values in the range [1, n2]
. Each integer appears exactly once except a
which appears twice and b
which is missing. The task is to find the repeating and missing numbers a
and b
.
Return a 0-indexed integer array ans
of size 2
where ans[0]
equals to a
and ans[1]
equals to b
.
\n
Example 1:
\n\n\nInput: grid = [[1,3],[2,2]]\nOutput: [2,4]\nExplanation: Number 2 is repeated and number 4 is missing so the answer is [2,4].\n\n\n
Example 2:
\n\n\nInput: grid = [[9,1,7],[8,9,2],[3,4,6]]\nOutput: [9,5]\nExplanation: Number 9 is repeated and number 5 is missing so the answer is [9,5].\n\n\n
\n
Constraints:
\n\n2 <= n == grid.length == grid[i].length <= 50
1 <= grid[i][j] <= n * n
x
that 1 <= x <= n * n
there is exactly one x
that is not equal to any of the grid members.x
that 1 <= x <= n * n
there is exactly one x
that is equal to exactly two of the grid members.x
that 1 <= x <= n * n
except two of them there is exatly one pair of i, j
that 0 <= i, j <= n - 1
and grid[i][j] == x
.You are given a 0-indexed 2D integer matrix grid
of size n * n
with values in the range [1, n2]
. Each integer appears exactly once except a
which appears twice and b
which is missing. The task is to find the repeating and missing numbers a
and b
.
Return a 0-indexed integer array ans
of size 2
where ans[0]
equals to a
and ans[1]
equals to b
.
\n
Example 1:
\n\n\nInput: grid = [[1,3],[2,2]]\nOutput: [2,4]\nExplanation: Number 2 is repeated and number 4 is missing so the answer is [2,4].\n\n\n
Example 2:
\n\n\nInput: grid = [[9,1,7],[8,9,2],[3,4,6]]\nOutput: [9,5]\nExplanation: Number 9 is repeated and number 5 is missing so the answer is [9,5].\n\n\n
\n
Constraints:
\n\n2 <= n == grid.length == grid[i].length <= 50
1 <= grid[i][j] <= n * n
x
that 1 <= x <= n * n
there is exactly one x
that is not equal to any of the grid members.x
that 1 <= x <= n * n
there is exactly one x
that is equal to exactly two of the grid members.x
that 1 <= x <= n * n
except two of them there is exactly one pair of i, j
that 0 <= i, j <= n - 1
and grid[i][j] == x
.You are given an integer array nums
of size n
where n
is a multiple of 3 and a positive integer k
.
Divide the array nums
into n / 3
arrays of size 3 satisfying the following condition:
k
.Return a 2D array containing the arrays. If it is impossible to satisfy the conditions, return an empty array. And if there are multiple answers, return any of them.
\n\n\n
Example 1:
\n\nInput: nums = [1,3,4,8,7,9,3,5,1], k = 2
\n\nOutput: [[1,1,3],[3,4,5],[7,8,9]]
\n\nExplanation:
\n\nThe difference between any two elements in each array is less than or equal to 2.
\nExample 2:
\n\nInput: nums = [2,4,2,2,5,2], k = 2
\n\nOutput: []
\n\nExplanation:
\n\nDifferent ways to divide nums
into 2 arrays of size 3 are:
Because there are four 2s there will be an array with the elements 2 and 5 no matter how we divide it. since 5 - 2 = 3 > k
, the condition is not satisfied and so there is no valid division.
Example 3:
\n\nInput: nums = [4,2,9,8,2,12,7,12,10,5,8,5,5,7,9,2,5,11], k = 14
\n\nOutput: [[2,2,12],[4,8,5],[5,9,7],[7,8,5],[5,9,10],[11,12,2]]
\n\nExplanation:
\n\nThe difference between any two elements in each array is less than or equal to 14.
\n\n
Constraints:
\n\nn == nums.length
1 <= n <= 105
n
is a multiple of 31 <= nums[i] <= 105
1 <= k <= 105
You are given a 0-indexed integer array nums
having length n
.
You are allowed to perform a special move any number of times (including zero) on nums
. In one special move you perform the following steps in order:
i
in the range [0, n - 1]
, and a positive integer x
.|nums[i] - x|
to the total cost.nums[i]
to x
.A palindromic number is a positive integer that remains the same when its digits are reversed. For example, 121
, 2552
and 65756
are palindromic numbers whereas 24
, 46
, 235
are not palindromic numbers.
An array is considered equalindromic if all the elements in the array are equal to an integer y
, where y
is a palindromic number less than 109
.
Return an integer denoting the minimum possible total cost to make nums
equalindromic by performing any number of special moves.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 6\nExplanation: We can make the array equalindromic by changing all elements to 3 which is a palindromic number. The cost of changing the array to [3,3,3,3,3] using 4 special moves is given by |1 - 3| + |2 - 3| + |4 - 3| + |5 - 3| = 6.\nIt can be shown that changing all elements to any palindromic number other than 3 cannot be achieved at a lower cost.\n\n\n
Example 2:
\n\n\nInput: nums = [10,12,13,14,15]\nOutput: 11\nExplanation: We can make the array equalindromic by changing all elements to 11 which is a palindromic number. The cost of changing the array to [11,11,11,11,11] using 5 special moves is given by |10 - 11| + |12 - 11| + |13 - 11| + |14 - 11| + |15 - 11| = 11.\nIt can be shown that changing all elements to any palindromic number other than 11 cannot be achieved at a lower cost.\n\n\n
Example 3:
\n\n\nInput: nums = [22,33,22,33,22]\nOutput: 22\nExplanation: We can make the array equalindromic by changing all elements to 22 which is a palindromic number. The cost of changing the array to [22,22,22,22,22] using 2 special moves is given by |33 - 22| + |33 - 22| = 22.\nIt can be shown that changing all elements to any palindromic number other than 22 cannot be achieved at a lower cost.\n\n\n
\n
Constraints:
\n\n1 <= n <= 105
1 <= nums[i] <= 109
You are given a 0-indexed integer array nums
and an integer k
.
You can perform the following operation on the array at most k
times:
i
from the array and increase or decrease nums[i]
by 1
.The score of the final array is the frequency of the most frequent element in the array.
\n\nReturn the maximum score you can achieve.
\n\nThe frequency of an element is the number of occurences of that element in the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,6,4], k = 3\nOutput: 3\nExplanation: We can do the following operations on the array:\n- Choose i = 0, and increase the value of nums[0] by 1. The resulting array is [2,2,6,4].\n- Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3].\n- Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,2].\nThe element 2 is the most frequent in the final array so our score is 3.\nIt can be shown that we cannot achieve a better score.\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,4,2,4], k = 0\nOutput: 3\nExplanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= k <= 1014
You are given a 0-indexed array of positive integers nums
.
A subarray of nums
is called incremovable if nums
becomes strictly increasing on removing the subarray. For example, the subarray [3, 4]
is an incremovable subarray of [5, 3, 4, 6, 7]
because removing this subarray changes the array [5, 3, 4, 6, 7]
to [5, 6, 7]
which is strictly increasing.
Return the total number of incremovable subarrays of nums
.
Note that an empty array is considered strictly increasing.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 10\nExplanation: The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray.\n\n\n
Example 2:
\n\n\nInput: nums = [6,5,7,8]\nOutput: 7\nExplanation: The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8].\nIt can be shown that there are only 7 incremovable subarrays in nums.\n\n\n
Example 3:
\n\n\nInput: nums = [8,7,6,6]\nOutput: 3\nExplanation: The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 50
You are given an array of positive integers nums
of length n
.
A polygon is a closed plane figure that has at least 3
sides. The longest side of a polygon is smaller than the sum of its other sides.
Conversely, if you have k
(k >= 3
) positive real numbers a1
, a2
, a3
, ..., ak
where a1 <= a2 <= a3 <= ... <= ak
and a1 + a2 + a3 + ... + ak-1 > ak
, then there always exists a polygon with k
sides whose lengths are a1
, a2
, a3
, ..., ak
.
The perimeter of a polygon is the sum of lengths of its sides.
\n\nReturn the largest possible perimeter of a polygon whose sides can be formed from nums
, or -1
if it is not possible to create a polygon.
\n
Example 1:
\n\n\nInput: nums = [5,5,5]\nOutput: 15\nExplanation: The only possible polygon that can be made from nums has 3 sides: 5, 5, and 5. The perimeter is 5 + 5 + 5 = 15.\n\n\n
Example 2:
\n\n\nInput: nums = [1,12,1,2,5,50,3]\nOutput: 12\nExplanation: The polygon with the largest perimeter which can be made from nums has 5 sides: 1, 1, 2, 3, and 5. The perimeter is 1 + 1 + 2 + 3 + 5 = 12.\nWe cannot have a polygon with either 12 or 50 as the longest side because it is not possible to include 2 or more smaller sides that have a greater sum than either of them.\nIt can be shown that the largest possible perimeter is 12.\n\n\n
Example 3:
\n\n\nInput: nums = [5,5,50]\nOutput: -1\nExplanation: There is no possible way to form a polygon from nums, as a polygon has at least 3 sides and 50 > 5 + 5.\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
1 <= nums[i] <= 109
You are given a 0-indexed array of positive integers nums
.
A subarray of nums
is called incremovable if nums
becomes strictly increasing on removing the subarray. For example, the subarray [3, 4]
is an incremovable subarray of [5, 3, 4, 6, 7]
because removing this subarray changes the array [5, 3, 4, 6, 7]
to [5, 6, 7]
which is strictly increasing.
Return the total number of incremovable subarrays of nums
.
Note that an empty array is considered strictly increasing.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,4]\nOutput: 10\nExplanation: The 10 incremovable subarrays are: [1], [2], [3], [4], [1,2], [2,3], [3,4], [1,2,3], [2,3,4], and [1,2,3,4], because on removing any one of these subarrays nums becomes strictly increasing. Note that you cannot select an empty subarray.\n\n\n
Example 2:
\n\n\nInput: nums = [6,5,7,8]\nOutput: 7\nExplanation: The 7 incremovable subarrays are: [5], [6], [5,7], [6,5], [5,7,8], [6,5,7] and [6,5,7,8].\nIt can be shown that there are only 7 incremovable subarrays in nums.\n\n\n
Example 3:
\n\n\nInput: nums = [8,7,6,6]\nOutput: 3\nExplanation: The 3 incremovable subarrays are: [8,7,6], [7,6,6], and [8,7,6,6]. Note that [8,7] is not an incremovable subarray because after removing [8,7] nums becomes [6,6], which is sorted in ascending order but not strictly increasing.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given an undirected tree with n
nodes labeled from 0
to n - 1
, and rooted at node 0
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
You are also given a 0-indexed integer array cost
of length n
, where cost[i]
is the cost assigned to the ith
node.
You need to place some coins on every node of the tree. The number of coins to be placed at node i
can be calculated as:
i
is less than 3
, place 1
coin.3
distinct nodes in the subtree of node i
. If this product is negative, place 0
coins.Return an array coin
of size n
such that coin[i]
is the number of coins placed at node i
.
\n
Example 1:
\n\nInput: edges = [[0,1],[0,2],[0,3],[0,4],[0,5]], cost = [1,2,3,4,5,6]\nOutput: [120,1,1,1,1,1]\nExplanation: For node 0 place 6 * 5 * 4 = 120 coins. All other nodes are leaves with subtree of size 1, place 1 coin on each of them.\n\n\n
Example 2:
\n\nInput: edges = [[0,1],[0,2],[1,3],[1,4],[1,5],[2,6],[2,7],[2,8]], cost = [1,4,2,3,5,7,8,-4,2]\nOutput: [280,140,32,1,1,1,1,1,1]\nExplanation: The coins placed on each node are:\n- Place 8 * 7 * 5 = 280 coins on node 0.\n- Place 7 * 5 * 4 = 140 coins on node 1.\n- Place 8 * 2 * 2 = 32 coins on node 2.\n- All other nodes are leaves with subtree of size 1, place 1 coin on each of them.\n\n\n
Example 3:
\n\nInput: edges = [[0,1],[0,2]], cost = [1,2,-2]\nOutput: [0,1,1]\nExplanation: Node 1 and 2 are leaves with subtree of size 1, place 1 coin on each of them. For node 0 the only possible product of cost is 2 * 1 * -2 = -4. Hence place 0 coins on node 0.\n\n\n
\n
Constraints:
\n\n2 <= n <= 2 * 104
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
cost.length == n
1 <= |cost[i]| <= 104
edges
represents a valid tree.You are given a 0-indexed integer array nums
of even length and there is also an empty array arr
. Alice and Bob decided to play a game where in every round Alice and Bob will do one move. The rules of the game are as follows:
nums
, and then Bob does the same.arr
, and then Alice does the same.nums
becomes empty.Return the resulting array arr
.
\n
Example 1:
\n\n\nInput: nums = [5,4,2,3]\nOutput: [3,2,5,4]\nExplanation: In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2].\nAt the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4].\n\n\n
Example 2:
\n\n\nInput: nums = [2,5]\nOutput: [5,2]\nExplanation: In round one, first Alice removes 2 and then Bob removes 5. Then in arr firstly Bob appends and then Alice appends. So arr = [5,2].\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 100
nums.length % 2 == 0
There is a large (m - 1) x (n - 1)
rectangular field with corners at (1, 1)
and (m, n)
containing some horizontal and vertical fences given in arrays hFences
and vFences
respectively.
Horizontal fences are from the coordinates (hFences[i], 1)
to (hFences[i], n)
and vertical fences are from the coordinates (1, vFences[i])
to (m, vFences[i])
.
Return the maximum area of a square field that can be formed by removing some fences (possibly none) or -1
if it is impossible to make a square field.
Since the answer may be large, return it modulo 109 + 7
.
Note: The field is surrounded by two horizontal fences from the coordinates (1, 1)
to (1, n)
and (m, 1)
to (m, n)
and two vertical fences from the coordinates (1, 1)
to (m, 1)
and (1, n)
to (m, n)
. These fences cannot be removed.
\n
Example 1:
\n\n\nInput: m = 4, n = 3, hFences = [2,3], vFences = [2]\nOutput: 4\nExplanation: Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4.\n\n\n
Example 2:
\n\n\nInput: m = 6, n = 7, hFences = [2], vFences = [4]\nOutput: -1\nExplanation: It can be proved that there is no way to create a square field by removing fences.\n\n\n
\n
Constraints:
\n\n3 <= m, n <= 109
1 <= hFences.length, vFences.length <= 600
1 < hFences[i] < m
1 < vFences[i] < n
hFences
and vFences
are unique.You are given two 0-indexed strings source
and target
, both of length n
and consisting of lowercase English letters. You are also given two 0-indexed character arrays original
and changed
, and an integer array cost
, where cost[i]
represents the cost of changing the character original[i]
to the character changed[i]
.
You start with the string source
. In one operation, you can pick a character x
from the string and change it to the character y
at a cost of z
if there exists any index j
such that cost[j] == z
, original[j] == x
, and changed[j] == y
.
Return the minimum cost to convert the string source
to the string target
using any number of operations. If it is impossible to convert source
to target
, return -1
.
Note that there may exist indices i
, j
such that original[j] == original[i]
and changed[j] == changed[i]
.
\n
Example 1:
\n\n\nInput: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]\nOutput: 28\nExplanation: To convert the string "abcd" to string "acbe":\n- Change value at index 1 from 'b' to 'c' at a cost of 5.\n- Change value at index 2 from 'c' to 'e' at a cost of 1.\n- Change value at index 2 from 'e' to 'b' at a cost of 2.\n- Change value at index 3 from 'd' to 'e' at a cost of 20.\nThe total cost incurred is 5 + 1 + 2 + 20 = 28.\nIt can be shown that this is the minimum possible cost.\n\n\n
Example 2:
\n\n\nInput: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2]\nOutput: 12\nExplanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred.\n\n\n
Example 3:
\n\n\nInput: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000]\nOutput: -1\nExplanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'.\n\n\n
\n
Constraints:
\n\n1 <= source.length == target.length <= 105
source
, target
consist of lowercase English letters.1 <= cost.length == original.length == changed.length <= 2000
original[i]
, changed[i]
are lowercase English letters.1 <= cost[i] <= 106
original[i] != changed[i]
You are given two 0-indexed strings source
and target
, both of length n
and consisting of lowercase English characters. You are also given two 0-indexed string arrays original
and changed
, and an integer array cost
, where cost[i]
represents the cost of converting the string original[i]
to the string changed[i]
.
You start with the string source
. In one operation, you can pick a substring x
from the string, and change it to y
at a cost of z
if there exists any index j
such that cost[j] == z
, original[j] == x
, and changed[j] == y
. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions:
source[a..b]
and source[c..d]
with either b < c
or d < a
. In other words, the indices picked in both operations are disjoint.source[a..b]
and source[c..d]
with a == c
and b == d
. In other words, the indices picked in both operations are identical.Return the minimum cost to convert the string source
to the string target
using any number of operations. If it is impossible to convert source
to target
, return -1
.
Note that there may exist indices i
, j
such that original[j] == original[i]
and changed[j] == changed[i]
.
\n
Example 1:
\n\n\nInput: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]\nOutput: 28\nExplanation: To convert "abcd" to "acbe", do the following operations:\n- Change substring source[1..1] from "b" to "c" at a cost of 5.\n- Change substring source[2..2] from "c" to "e" at a cost of 1.\n- Change substring source[2..2] from "e" to "b" at a cost of 2.\n- Change substring source[3..3] from "d" to "e" at a cost of 20.\nThe total cost incurred is 5 + 1 + 2 + 20 = 28. \nIt can be shown that this is the minimum possible cost.\n\n\n
Example 2:
\n\n\nInput: source = "abcdefgh", target = "acdeeghh", original = ["bcd","fgh","thh"], changed = ["cde","thh","ghh"], cost = [1,3,5]\nOutput: 9\nExplanation: To convert "abcdefgh" to "acdeeghh", do the following operations:\n- Change substring source[1..3] from "bcd" to "cde" at a cost of 1.\n- Change substring source[5..7] from "fgh" to "thh" at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation.\n- Change substring source[5..7] from "thh" to "ghh" at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation.\nThe total cost incurred is 1 + 3 + 5 = 9.\nIt can be shown that this is the minimum possible cost.\n\n\n
Example 3:
\n\n\nInput: source = "abcdefgh", target = "addddddd", original = ["bcd","defgh"], changed = ["ddd","ddddd"], cost = [100,1578]\nOutput: -1\nExplanation: It is impossible to convert "abcdefgh" to "addddddd".\nIf you select substring source[1..3] as the first operation to change "abcdefgh" to "adddefgh", you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation.\nIf you select substring source[3..7] as the first operation to change "abcdefgh" to "abcddddd", you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation.\n\n\n
\n
Constraints:
\n\n1 <= source.length == target.length <= 1000
source
, target
consist only of lowercase English characters.1 <= cost.length == original.length == changed.length <= 100
1 <= original[i].length == changed[i].length <= source.length
original[i]
, changed[i]
consist only of lowercase English characters.original[i] != changed[i]
1 <= cost[i] <= 106
You are given an array of positive integers nums
.
You have to check if it is possible to select two or more elements in the array such that the bitwise OR
of the selected elements has at least one trailing zero in its binary representation.
For example, the binary representation of 5
, which is "101"
, does not have any trailing zeros, whereas the binary representation of 4
, which is "100"
, has two trailing zeros.
Return true
if it is possible to select two or more elements whose bitwise OR
has trailing zeros, return false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation "110" with one trailing zero.\n\n\n
Example 2:
\n\n\nInput: nums = [2,4,8,16]\nOutput: true\nExplanation: If we select the elements 2 and 4, their bitwise OR is 6, which has the binary representation "110" with one trailing zero.\nOther possible ways to select elements to have trailing zeroes in the binary representation of their bitwise OR are: (2, 8), (2, 16), (4, 8), (4, 16), (8, 16), (2, 4, 8), (2, 4, 16), (2, 8, 16), (4, 8, 16), and (2, 4, 8, 16).\n\n\n
Example 3:
\n\n\nInput: nums = [1,3,5,7,9]\nOutput: false\nExplanation: There is no possible way to select two or more elements to have trailing zeros in the binary representation of their bitwise OR.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 100
You are given a string s
that consists of lowercase English letters.
A string is called special if it is made up of only a single character. For example, the string "abc"
is not special, whereas the strings "ddd"
, "zz"
, and "f"
are special.
Return the length of the longest special substring of s
which occurs at least thrice, or -1
if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "aaaa"\nOutput: 2\nExplanation: The longest special substring which occurs thrice is "aa": substrings "aaaa", "aaaa", and "aaaa".\nIt can be shown that the maximum length achievable is 2.\n\n\n
Example 2:
\n\n\nInput: s = "abcdef"\nOutput: -1\nExplanation: There exists no special substring which occurs at least thrice. Hence return -1.\n\n\n
Example 3:
\n\n\nInput: s = "abcaba"\nOutput: 1\nExplanation: The longest special substring which occurs thrice is "a": substrings "abcaba", "abcaba", and "abcaba".\nIt can be shown that the maximum length achievable is 1.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 50
s
consists of only lowercase English letters.You are given a string s
that consists of lowercase English letters.
A string is called special if it is made up of only a single character. For example, the string "abc"
is not special, whereas the strings "ddd"
, "zz"
, and "f"
are special.
Return the length of the longest special substring of s
which occurs at least thrice, or -1
if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\n\nInput: s = "aaaa"\nOutput: 2\nExplanation: The longest special substring which occurs thrice is "aa": substrings "aaaa", "aaaa", and "aaaa".\nIt can be shown that the maximum length achievable is 2.\n\n\n
Example 2:
\n\n\nInput: s = "abcdef"\nOutput: -1\nExplanation: There exists no special substring which occurs at least thrice. Hence return -1.\n\n\n
Example 3:
\n\n\nInput: s = "abcaba"\nOutput: 1\nExplanation: The longest special substring which occurs thrice is "a": substrings "abcaba", "abcaba", and "abcaba".\nIt can be shown that the maximum length achievable is 1.\n\n\n
\n
Constraints:
\n\n3 <= s.length <= 5 * 105
s
consists of only lowercase English letters.You are given a 0-indexed string s
having an even length n
.
You are also given a 0-indexed 2D integer array, queries
, where queries[i] = [ai, bi, ci, di]
.
For each query i
, you are allowed to perform the following operations:
s[ai:bi]
, where 0 <= ai <= bi < n / 2
.s[ci:di]
, where n / 2 <= ci <= di < n
.For each query, your task is to determine whether it is possible to make s
a palindrome by performing the operations.
Each query is answered independently of the others.
\n\nReturn a 0-indexed array answer
, where answer[i] == true
if it is possible to make s
a palindrome by performing operations specified by the ith
query, and false
otherwise.
s[x:y]
represents the substring consisting of characters from the index x
to index y
in s
, both inclusive.\n
Example 1:
\n\n\nInput: s = "abcabc", queries = [[1,1,3,5],[0,2,5,5]]\nOutput: [true,true]\nExplanation: In this example, there are two queries:\nIn the first query:\n- a0 = 1, b0 = 1, c0 = 3, d0 = 5.\n- So, you are allowed to rearrange s[1:1] => abcabc and s[3:5] => abcabc.\n- To make s a palindrome, s[3:5] can be rearranged to become => abccba.\n- Now, s is a palindrome. So, answer[0] = true.\nIn the second query:\n- a1 = 0, b1 = 2, c1 = 5, d1 = 5.\n- So, you are allowed to rearrange s[0:2] => abcabc and s[5:5] => abcabc.\n- To make s a palindrome, s[0:2] can be rearranged to become => cbaabc.\n- Now, s is a palindrome. So, answer[1] = true.\n\n\n
Example 2:
\n\n\nInput: s = "abbcdecbba", queries = [[0,2,7,9]]\nOutput: [false]\nExplanation: In this example, there is only one query.\na0 = 0, b0 = 2, c0 = 7, d0 = 9.\nSo, you are allowed to rearrange s[0:2] => abbcdecbba and s[7:9] => abbcdecbba.\nIt is not possible to make s a palindrome by rearranging these substrings because s[3:6] is not a palindrome.\nSo, answer[0] = false.\n\n
Example 3:
\n\n\nInput: s = "acbcab", queries = [[1,2,4,5]]\nOutput: [true]\nExplanation: In this example, there is only one query.\na0 = 1, b0 = 2, c0 = 4, d0 = 5.\nSo, you are allowed to rearrange s[1:2] => acbcab and s[4:5] => acbcab.\nTo make s a palindrome s[1:2] can be rearranged to become abccab.\nThen, s[4:5] can be rearranged to become abccba.\nNow, s is a palindrome. So, answer[0] = true.\n\n
\n
Constraints:
\n\n2 <= n == s.length <= 105
1 <= queries.length <= 105
queries[i].length == 4
ai == queries[i][0], bi == queries[i][1]
ci == queries[i][2], di == queries[i][3]
0 <= ai <= bi < n / 2
n / 2 <= ci <= di < n
n
is even.s
consists of only lowercase English letters.You are given a 0-indexed array of integers nums
.
A prefix nums[0..i]
is sequential if, for all 1 <= j <= i
, nums[j] = nums[j - 1] + 1
. In particular, the prefix consisting only of nums[0]
is sequential.
Return the smallest integer x
missing from nums
such that x
is greater than or equal to the sum of the longest sequential prefix.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,2,5]\nOutput: 6\nExplanation: The longest sequential prefix of nums is [1,2,3] with a sum of 6. 6 is not in the array, therefore 6 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.\n\n\n
Example 2:
\n\n\nInput: nums = [3,4,5,1,12,14,13]\nOutput: 15\nExplanation: The longest sequential prefix of nums is [3,4,5] with a sum of 12. 12, 13, and 14 belong to the array while 15 does not. Therefore 15 is the smallest missing integer greater than or equal to the sum of the longest sequential prefix.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 50
You are given a 0-indexed integer array nums
and a positive integer k
.
You can apply the following operation on the array any number of times:
\n\n0
to 1
or vice versa.Return the minimum number of operations required to make the bitwise XOR
of all elements of the final array equal to k
.
Note that you can flip leading zero bits in the binary representation of elements. For example, for the number (101)2
you can flip the fourth bit and obtain (1101)2
.
\n
Example 1:
\n\n\nInput: nums = [2,1,3,4], k = 1\nOutput: 2\nExplanation: We can do the following operations:\n- Choose element 2 which is 3 == (011)2, we flip the first bit and we obtain (010)2 == 2. nums becomes [2,1,2,4].\n- Choose element 0 which is 2 == (010)2, we flip the third bit and we obtain (110)2 = 6. nums becomes [6,1,2,4].\nThe XOR of elements of the final array is (6 XOR 1 XOR 2 XOR 4) == 1 == k.\nIt can be shown that we cannot make the XOR equal to k in less than 2 operations.\n\n\n
Example 2:
\n\n\nInput: nums = [2,0,2,0], k = 0\nOutput: 0\nExplanation: The XOR of elements of the array is (2 XOR 0 XOR 2 XOR 0) == 0 == k. So no operation is needed.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 106
0 <= k <= 106
You are given two positive integers x
and y
.
In one operation, you can do one of the four following operations:
\n\nx
by 11
if x
is a multiple of 11
.x
by 5
if x
is a multiple of 5
.x
by 1
.x
by 1
.Return the minimum number of operations required to make x
and y
equal.
\n
Example 1:
\n\n\nInput: x = 26, y = 1\nOutput: 3\nExplanation: We can make 26 equal to 1 by applying the following operations: \n1. Decrement x by 1\n2. Divide x by 5\n3. Divide x by 5\nIt can be shown that 3 is the minimum number of operations required to make 26 equal to 1.\n\n\n
Example 2:
\n\n\nInput: x = 54, y = 2\nOutput: 4\nExplanation: We can make 54 equal to 2 by applying the following operations: \n1. Increment x by 1\n2. Divide x by 11 \n3. Divide x by 5\n4. Increment x by 1\nIt can be shown that 4 is the minimum number of operations required to make 54 equal to 2.\n\n\n
Example 3:
\n\n\nInput: x = 25, y = 30\nOutput: 5\nExplanation: We can make 25 equal to 30 by applying the following operations: \n1. Increment x by 1\n2. Increment x by 1\n3. Increment x by 1\n4. Increment x by 1\n5. Increment x by 1\nIt can be shown that 5 is the minimum number of operations required to make 25 equal to 30.\n\n\n
\n
Constraints:
\n\n1 <= x, y <= 104
You are given three integers start
, finish
, and limit
. You are also given a 0-indexed string s
representing a positive integer.
A positive integer x
is called powerful if it ends with s
(in other words, s
is a suffix of x
) and each digit in x
is at most limit
.
Return the total number of powerful integers in the range [start..finish]
.
A string x
is a suffix of a string y
if and only if x
is a substring of y
that starts from some index (including 0
) in y
and extends to the index y.length - 1
. For example, 25
is a suffix of 5125
whereas 512
is not.
\n
Example 1:
\n\n\nInput: start = 1, finish = 6000, limit = 4, s = "124"\nOutput: 5\nExplanation: The powerful integers in the range [1..6000] are 124, 1124, 2124, 3124, and, 4124. All these integers have each digit <= 4, and "124" as a suffix. Note that 5124 is not a powerful integer because the first digit is 5 which is greater than 4.\nIt can be shown that there are only 5 powerful integers in this range.\n\n\n
Example 2:
\n\n\nInput: start = 15, finish = 215, limit = 6, s = "10"\nOutput: 2\nExplanation: The powerful integers in the range [15..215] are 110 and 210. All these integers have each digit <= 6, and "10" as a suffix.\nIt can be shown that there are only 2 powerful integers in this range.\n\n\n
Example 3:
\n\n\nInput: start = 1000, finish = 2000, limit = 4, s = "3000"\nOutput: 0\nExplanation: All integers in the range [1000..2000] are smaller than 3000, hence "3000" cannot be a suffix of any integer in this range.\n\n\n
\n
Constraints:
\n\n1 <= start <= finish <= 1015
1 <= limit <= 9
1 <= s.length <= floor(log10(finish)) + 1
s
only consists of numeric digits which are at most limit
.s
does not have leading zeros.You are given a 2D 0-indexed integer array dimensions
.
For all indices i
, 0 <= i < dimensions.length
, dimensions[i][0]
represents the length and dimensions[i][1]
represents the width of the rectangle i
.
Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the maximum area.
\n\n\n
Example 1:
\n\n\nInput: dimensions = [[9,3],[8,6]]\nOutput: 48\nExplanation: \nFor index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈ 9.487.\nFor index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10.\nSo, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.\n\n\n
Example 2:
\n\n\nInput: dimensions = [[3,4],[4,3]]\nOutput: 12\nExplanation: Length of diagonal is the same for both which is 5, so maximum area = 12.\n\n\n
\n
Constraints:
\n\n1 <= dimensions.length <= 100
dimensions[i].length == 2
1 <= dimensions[i][0], dimensions[i][1] <= 100
There is a 1-indexed 8 x 8
chessboard containing 3
pieces.
You are given 6
integers a
, b
, c
, d
, e
, and f
where:
(a, b)
denotes the position of the white rook.(c, d)
denotes the position of the white bishop.(e, f)
denotes the position of the black queen.Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen.
\n\nNote that:
\n\n\n
Example 1:
\n\nInput: a = 1, b = 1, c = 8, d = 8, e = 2, f = 3\nOutput: 2\nExplanation: We can capture the black queen in two moves by moving the white rook to (1, 3) then to (2, 3).\nIt is impossible to capture the black queen in less than two moves since it is not being attacked by any of the pieces at the beginning.\n\n\n
Example 2:
\n\nInput: a = 5, b = 3, c = 3, d = 4, e = 5, f = 2\nOutput: 1\nExplanation: We can capture the black queen in a single move by doing one of the following: \n- Move the white rook to (5, 2).\n- Move the white bishop to (5, 2).\n\n\n
\n
Constraints:
\n\n1 <= a, b, c, d, e, f <= 8
You are given two 0-indexed integer arrays nums1
and nums2
of even length n
.
You must remove n / 2
elements from nums1
and n / 2
elements from nums2
. After the removals, you insert the remaining elements of nums1
and nums2
into a set s
.
Return the maximum possible size of the set s
.
\n
Example 1:
\n\n\nInput: nums1 = [1,2,1,2], nums2 = [1,1,1,1]\nOutput: 2\nExplanation: We remove two occurences of 1 from nums1 and nums2. After the removals, the arrays become equal to nums1 = [2,2] and nums2 = [1,1]. Therefore, s = {1,2}.\nIt can be shown that 2 is the maximum possible size of the set s after the removals.\n\n\n
Example 2:
\n\n\nInput: nums1 = [1,2,3,4,5,6], nums2 = [2,3,2,3,2,3]\nOutput: 5\nExplanation: We remove 2, 3, and 6 from nums1, as well as 2 and two occurrences of 3 from nums2. After the removals, the arrays become equal to nums1 = [1,4,5] and nums2 = [2,3,2]. Therefore, s = {1,2,3,4,5}.\nIt can be shown that 5 is the maximum possible size of the set s after the removals.\n\n\n
Example 3:
\n\n\nInput: nums1 = [1,1,2,2,3,3], nums2 = [4,4,5,5,6,6]\nOutput: 6\nExplanation: We remove 1, 2, and 3 from nums1, as well as 4, 5, and 6 from nums2. After the removals, the arrays become equal to nums1 = [1,2,3] and nums2 = [4,5,6]. Therefore, s = {1,2,3,4,5,6}.\nIt can be shown that 6 is the maximum possible size of the set s after the removals.\n\n\n
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 2 * 104
n
is even.1 <= nums1[i], nums2[i] <= 109
You are given a string s
and an integer k
.
First, you are allowed to change at most one index in s
to another lowercase English letter.
After that, do the following partitioning operation until s
is empty:
s
containing at most k
distinct characters.s
and increase the number of partitions by one. The remaining characters (if any) in s
maintain their initial order.Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one index to change.
\n\n\n
Example 1:
\n\nInput: s = "accca", k = 2
\n\nOutput: 3
\n\nExplanation:
\n\nThe optimal way is to change s[2]
to something other than a and c, for example, b. then it becomes "acbca"
.
Then we perform the operations:
\n\n"ac"
, we remove it and s
becomes "bca"
."bc"
, so we remove it and s
becomes "a"
."a"
and s
becomes empty, so the procedure ends.Doing the operations, the string is divided into 3 partitions, so the answer is 3.
\nExample 2:
\n\nInput: s = "aabaab", k = 3
\n\nOutput: 1
\n\nExplanation:
\n\nInitially s
contains 2 distinct characters, so whichever character we change, it will contain at most 3 distinct characters, so the longest prefix with at most 3 distinct characters would always be all of it, therefore the answer is 1.
Example 3:
\n\nInput: s = "xxyz", k = 1
\n\nOutput: 4
\n\nExplanation:
\n\nThe optimal way is to change s[0]
or s[1]
to something other than characters in s
, for example, to change s[0]
to w
.
Then s
becomes "wxyz"
, which consists of 4 distinct characters, so as k
is 1, it will divide into 4 partitions.
\n
Constraints:
\n\n1 <= s.length <= 104
s
consists only of lowercase English letters.1 <= k <= 26
You are given an array nums
consisting of positive integers.
Return the total frequencies of elements in nums
such that those elements all have the maximum frequency.
The frequency of an element is the number of occurrences of that element in the array.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,2,3,1,4]\nOutput: 4\nExplanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.\nSo the number of elements in the array with maximum frequency is 4.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: 5\nExplanation: All elements of the array have a frequency of 1 which is the maximum.\nSo the number of elements in the array with maximum frequency is 5.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given a 0-indexed string s
, a string a
, a string b
, and an integer k
.
An index i
is beautiful if:
0 <= i <= s.length - a.length
s[i..(i + a.length - 1)] == a
j
such that:\n\t0 <= j <= s.length - b.length
s[j..(j + b.length - 1)] == b
|j - i| <= k
Return the array that contains beautiful indices in sorted order from smallest to largest.
\n\n\n
Example 1:
\n\n\nInput: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15\nOutput: [16,33]\nExplanation: There are 2 beautiful indices: [16,33].\n- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.\n- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.\nThus we return [16,33] as the result.\n\n\n
Example 2:
\n\n\nInput: s = "abcd", a = "a", b = "a", k = 4\nOutput: [0]\nExplanation: There is 1 beautiful index: [0].\n- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.\nThus we return [0] as the result.\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 105
1 <= a.length, b.length <= 10
s
, a
, and b
contain only lowercase English letters.You are given an integer k
and an integer x
. The price of a number num
is calculated by the count of set bits at positions x
, 2x
, 3x
, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.
x | \n\t\t\tnum | \n\t\t\tBinary Representation | \n\t\t\tPrice | \n\t\t
---|---|---|---|
1 | \n\t\t\t13 | \n\t\t\t000001101 | \n\t\t\t3 | \n\t\t
2 | \n\t\t\t13 | \n\t\t\t000001101 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t233 | \n\t\t\t011101001 | \n\t\t\t3 | \n\t\t
3 | \n\t\t\t13 | \n\t\t\t000001101 | \n\t\t\t1 | \n\t\t
3 | \n\t\t\t362 | \n\t\t\t101101010 | \n\t\t\t2 | \n\t\t
The accumulated price of num
is the total price of numbers from 1
to num
. num
is considered cheap if its accumulated price is less than or equal to k
.
Return the greatest cheap number.
\n\n\n
Example 1:
\n\nInput: k = 9, x = 1
\n\nOutput: 6
\n\nExplanation:
\n\nAs shown in the table below, 6
is the greatest cheap number.
x | \n\t\t\tnum | \n\t\t\tBinary Representation | \n\t\t\tPrice | \n\t\t\tAccumulated Price | \n\t\t
---|---|---|---|---|
1 | \n\t\t\t1 | \n\t\t\t001 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t2 | \n\t\t\t010 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
1 | \n\t\t\t3 | \n\t\t\t011 | \n\t\t\t2 | \n\t\t\t4 | \n\t\t
1 | \n\t\t\t4 | \n\t\t\t100 | \n\t\t\t1 | \n\t\t\t5 | \n\t\t
1 | \n\t\t\t5 | \n\t\t\t101 | \n\t\t\t2 | \n\t\t\t7 | \n\t\t
1 | \n\t\t\t6 | \n\t\t\t110 | \n\t\t\t2 | \n\t\t\t9 | \n\t\t
1 | \n\t\t\t7 | \n\t\t\t111 | \n\t\t\t3 | \n\t\t\t12 | \n\t\t
Example 2:
\n\nInput: k = 7, x = 2
\n\nOutput: 9
\n\nExplanation:
\n\nAs shown in the table below, 9
is the greatest cheap number.
x | \n\t\t\tnum | \n\t\t\tBinary Representation | \n\t\t\tPrice | \n\t\t\tAccumulated Price | \n\t\t
---|---|---|---|---|
2 | \n\t\t\t1 | \n\t\t\t0001 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
2 | \n\t\t\t2 | \n\t\t\t0010 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t3 | \n\t\t\t0011 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
2 | \n\t\t\t4 | \n\t\t\t0100 | \n\t\t\t0 | \n\t\t\t2 | \n\t\t
2 | \n\t\t\t5 | \n\t\t\t0101 | \n\t\t\t0 | \n\t\t\t2 | \n\t\t
2 | \n\t\t\t6 | \n\t\t\t0110 | \n\t\t\t1 | \n\t\t\t3 | \n\t\t
2 | \n\t\t\t7 | \n\t\t\t0111 | \n\t\t\t1 | \n\t\t\t4 | \n\t\t
2 | \n\t\t\t8 | \n\t\t\t1000 | \n\t\t\t1 | \n\t\t\t5 | \n\t\t
2 | \n\t\t\t9 | \n\t\t\t1001 | \n\t\t\t1 | \n\t\t\t6 | \n\t\t
2 | \n\t\t\t10 | \n\t\t\t1010 | \n\t\t\t2 | \n\t\t\t8 | \n\t\t
\n
Constraints:
\n\n1 <= k <= 1015
1 <= x <= 8
You are given a 0-indexed string s
, a string a
, a string b
, and an integer k
.
An index i
is beautiful if:
0 <= i <= s.length - a.length
s[i..(i + a.length - 1)] == a
j
such that:\n\t0 <= j <= s.length - b.length
s[j..(j + b.length - 1)] == b
|j - i| <= k
Return the array that contains beautiful indices in sorted order from smallest to largest.
\n\n\n
Example 1:
\n\n\nInput: s = "isawsquirrelnearmysquirrelhouseohmy", a = "my", b = "squirrel", k = 15\nOutput: [16,33]\nExplanation: There are 2 beautiful indices: [16,33].\n- The index 16 is beautiful as s[16..17] == "my" and there exists an index 4 with s[4..11] == "squirrel" and |16 - 4| <= 15.\n- The index 33 is beautiful as s[33..34] == "my" and there exists an index 18 with s[18..25] == "squirrel" and |33 - 18| <= 15.\nThus we return [16,33] as the result.\n\n\n
Example 2:
\n\n\nInput: s = "abcd", a = "a", b = "a", k = 4\nOutput: [0]\nExplanation: There is 1 beautiful index: [0].\n- The index 0 is beautiful as s[0..0] == "a" and there exists an index 0 with s[0..0] == "a" and |0 - 0| <= 4.\nThus we return [0] as the result.\n\n\n
\n
Constraints:
\n\n1 <= k <= s.length <= 5 * 105
1 <= a.length, b.length <= 5 * 105
s
, a
, and b
contain only lowercase English letters.You are given an array of integers nums
of length n
.
The cost of an array is the value of its first element. For example, the cost of [1,2,3]
is 1
while the cost of [3,4,1]
is 3
.
You need to divide nums
into 3
disjoint contiguous subarrays.
Return the minimum possible sum of the cost of these subarrays.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,2,3,12]\nOutput: 6\nExplanation: The best possible way to form 3 subarrays is: [1], [2], and [3,12] at a total cost of 1 + 2 + 3 = 6.\nThe other possible ways to form 3 subarrays are:\n- [1], [2,3], and [12] at a total cost of 1 + 2 + 12 = 15.\n- [1,2], [3], and [12] at a total cost of 1 + 3 + 12 = 16.\n\n\n
Example 2:
\n\n\nInput: nums = [5,4,3]\nOutput: 12\nExplanation: The best possible way to form 3 subarrays is: [5], [4], and [3] at a total cost of 5 + 4 + 3 = 12.\nIt can be shown that 12 is the minimum cost achievable.\n\n\n
Example 3:
\n\n\nInput: nums = [10,3,1,1]\nOutput: 12\nExplanation: The best possible way to form 3 subarrays is: [10,3], [1], and [1] at a total cost of 10 + 1 + 1 = 12.\nIt can be shown that 12 is the minimum cost achievable.\n\n\n
\n
Constraints:
\n\n3 <= n <= 50
1 <= nums[i] <= 50
You are given a 0-indexed array of positive integers nums
.
In one operation, you can swap any two adjacent elements if they have the same number of set bits. You are allowed to do this operation any number of times (including zero).
\n\nReturn true
if you can sort the array in ascending order, else return false
.
\n
Example 1:
\n\n\nInput: nums = [8,4,2,30,15]\nOutput: true\nExplanation: Let's look at the binary representation of every element. The numbers 2, 4, and 8 have one set bit each with binary representation "10", "100", and "1000" respectively. The numbers 15 and 30 have four set bits each with binary representation "1111" and "11110".\nWe can sort the array using 4 operations:\n- Swap nums[0] with nums[1]. This operation is valid because 8 and 4 have one set bit each. The array becomes [4,8,2,30,15].\n- Swap nums[1] with nums[2]. This operation is valid because 8 and 2 have one set bit each. The array becomes [4,2,8,30,15].\n- Swap nums[0] with nums[1]. This operation is valid because 4 and 2 have one set bit each. The array becomes [2,4,8,30,15].\n- Swap nums[3] with nums[4]. This operation is valid because 30 and 15 have four set bits each. The array becomes [2,4,8,15,30].\nThe array has become sorted, hence we return true.\nNote that there may be other sequences of operations which also sort the array.\n\n\n
Example 2:
\n\n\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: The array is already sorted, hence we return true.\n\n\n
Example 3:
\n\n\nInput: nums = [3,16,8,4,2]\nOutput: false\nExplanation: It can be shown that it is not possible to sort the input array using any number of operations.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 28
You are given a 0-indexed integer array nums
containing positive integers.
Your task is to minimize the length of nums
by performing the following operations any number of times (including zero):
i
and j
from nums
, such that nums[i] > 0
and nums[j] > 0
.nums[i] % nums[j]
at the end of nums
.i
and j
from nums
.Return an integer denoting the minimum length of nums
after performing the operation any number of times.
\n
Example 1:
\n\n\nInput: nums = [1,4,3,1]\nOutput: 1\nExplanation: One way to minimize the length of the array is as follows:\nOperation 1: Select indices 2 and 1, insert nums[2] % nums[1] at the end and it becomes [1,4,3,1,3], then delete elements at indices 2 and 1.\nnums becomes [1,1,3].\nOperation 2: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [1,1,3,1], then delete elements at indices 1 and 2.\nnums becomes [1,1].\nOperation 3: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [1,1,0], then delete elements at indices 1 and 0.\nnums becomes [0].\nThe length of nums cannot be reduced further. Hence, the answer is 1.\nIt can be shown that 1 is the minimum achievable length.\n\n
Example 2:
\n\n\nInput: nums = [5,5,5,10,5]\nOutput: 2\nExplanation: One way to minimize the length of the array is as follows:\nOperation 1: Select indices 0 and 3, insert nums[0] % nums[3] at the end and it becomes [5,5,5,10,5,5], then delete elements at indices 0 and 3.\nnums becomes [5,5,5,5]. \nOperation 2: Select indices 2 and 3, insert nums[2] % nums[3] at the end and it becomes [5,5,5,5,0], then delete elements at indices 2 and 3. \nnums becomes [5,5,0]. \nOperation 3: Select indices 0 and 1, insert nums[0] % nums[1] at the end and it becomes [5,5,0,0], then delete elements at indices 0 and 1.\nnums becomes [0,0].\nThe length of nums cannot be reduced further. Hence, the answer is 2.\nIt can be shown that 2 is the minimum achievable length.\n\n
Example 3:
\n\n\nInput: nums = [2,3,4]\nOutput: 1\nExplanation: One way to minimize the length of the array is as follows: \nOperation 1: Select indices 1 and 2, insert nums[1] % nums[2] at the end and it becomes [2,3,4,3], then delete elements at indices 1 and 2.\nnums becomes [2,3].\nOperation 2: Select indices 1 and 0, insert nums[1] % nums[0] at the end and it becomes [2,3,1], then delete elements at indices 1 and 0.\nnums becomes [1].\nThe length of nums cannot be reduced further. Hence, the answer is 1.\nIt can be shown that 1 is the minimum achievable length.\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a 0-indexed array of integers nums
of length n
, and two positive integers k
and dist
.
The cost of an array is the value of its first element. For example, the cost of [1,2,3]
is 1
while the cost of [3,4,1]
is 3
.
You need to divide nums
into k
disjoint contiguous subarrays, such that the difference between the starting index of the second subarray and the starting index of the kth
subarray should be less than or equal to dist
. In other words, if you divide nums
into the subarrays nums[0..(i1 - 1)], nums[i1..(i2 - 1)], ..., nums[ik-1..(n - 1)]
, then ik-1 - i1 <= dist
.
Return the minimum possible sum of the cost of these subarrays.
\n\n\n
Example 1:
\n\n\nInput: nums = [1,3,2,6,4,2], k = 3, dist = 3\nOutput: 5\nExplanation: The best possible way to divide nums into 3 subarrays is: [1,3], [2,6,4], and [2]. This choice is valid because ik-1 - i1 is 5 - 2 = 3 which is equal to dist. The total cost is nums[0] + nums[2] + nums[5] which is 1 + 2 + 2 = 5.\nIt can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 5.\n\n\n
Example 2:
\n\n\nInput: nums = [10,1,2,2,2,1], k = 4, dist = 3\nOutput: 15\nExplanation: The best possible way to divide nums into 4 subarrays is: [10], [1], [2], and [2,2,1]. This choice is valid because ik-1 - i1 is 3 - 1 = 2 which is less than dist. The total cost is nums[0] + nums[1] + nums[2] + nums[3] which is 10 + 1 + 2 + 2 = 15.\nThe division [10], [1], [2,2,2], and [1] is not valid, because the difference between ik-1 and i1 is 5 - 1 = 4, which is greater than dist.\nIt can be shown that there is no possible way to divide nums into 4 subarrays at a cost lower than 15.\n\n\n
Example 3:
\n\n\nInput: nums = [10,8,18,9], k = 3, dist = 1\nOutput: 36\nExplanation: The best possible way to divide nums into 4 subarrays is: [10], [8], and [18,9]. This choice is valid because ik-1 - i1 is 2 - 1 = 1 which is equal to dist.The total cost is nums[0] + nums[1] + nums[2] which is 10 + 8 + 18 = 36.\nThe division [10], [8,18], and [9] is not valid, because the difference between ik-1 and i1 is 3 - 1 = 2, which is greater than dist.\nIt can be shown that there is no possible way to divide nums into 3 subarrays at a cost lower than 36.\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
1 <= nums[i] <= 109
3 <= k <= n
k - 2 <= dist <= n - 2
You are given a string word
containing distinct lowercase English letters.
Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2
is mapped with ["a","b","c"]
, we need to push the key one time to type "a"
, two times to type "b"
, and three times to type "c"
.
It is allowed to remap the keys numbered 2
to 9
to distinct collections of letters. The keys can be remapped to any amount of letters, but each letter must be mapped to exactly one key. You need to find the minimum number of times the keys will be pushed to type the string word
.
Return the minimum number of pushes needed to type word
after remapping the keys.
An example mapping of letters to keys on a telephone keypad is given below. Note that 1
, *
, #
, and 0
do not map to any letters.
\n
Example 1:
\n\nInput: word = "abcde"\nOutput: 5\nExplanation: The remapped keypad given in the image provides the minimum cost.\n"a" -> one push on key 2\n"b" -> one push on key 3\n"c" -> one push on key 4\n"d" -> one push on key 5\n"e" -> one push on key 6\nTotal cost is 1 + 1 + 1 + 1 + 1 = 5.\nIt can be shown that no other mapping can provide a lower cost.\n\n\n
Example 2:
\n\nInput: word = "xycdefghij"\nOutput: 12\nExplanation: The remapped keypad given in the image provides the minimum cost.\n"x" -> one push on key 2\n"y" -> two pushes on key 2\n"c" -> one push on key 3\n"d" -> two pushes on key 3\n"e" -> one push on key 4\n"f" -> one push on key 5\n"g" -> one push on key 6\n"h" -> one push on key 7\n"i" -> one push on key 8\n"j" -> one push on key 9\nTotal cost is 1 + 2 + 1 + 2 + 1 + 1 + 1 + 1 + 1 + 1 = 12.\nIt can be shown that no other mapping can provide a lower cost.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 26
word
consists of lowercase English letters.word
are distinct.You are given three positive integers n
, x
, and y
.
In a city, there exist houses numbered 1
to n
connected by n
streets. There is a street connecting the house numbered i
with the house numbered i + 1
for all 1 <= i <= n - 1
. An additional street connects the house numbered x
with the house numbered y
.
For each k
, such that 1 <= k <= n
, you need to find the number of pairs of houses (house1, house2)
such that the minimum number of streets that need to be traveled to reach house2
from house1
is k
.
Return a 1-indexed array result
of length n
where result[k]
represents the total number of pairs of houses such that the minimum streets required to reach one house from the other is k
.
Note that x
and y
can be equal.
\n
Example 1:
\n\nInput: n = 3, x = 1, y = 3\nOutput: [6,0,0]\nExplanation: Let's look at each pair of houses:\n- For the pair (1, 2), we can go from house 1 to house 2 directly.\n- For the pair (2, 1), we can go from house 2 to house 1 directly.\n- For the pair (1, 3), we can go from house 1 to house 3 directly.\n- For the pair (3, 1), we can go from house 3 to house 1 directly.\n- For the pair (2, 3), we can go from house 2 to house 3 directly.\n- For the pair (3, 2), we can go from house 3 to house 2 directly.\n\n\n
Example 2:
\n\nInput: n = 5, x = 2, y = 4\nOutput: [10,8,2,0,0]\nExplanation: For each distance k the pairs are:\n- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4).\n- For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3).\n- For k == 3, the pairs are (1, 5), and (5, 1).\n- For k == 4 and k == 5, there are no pairs.\n\n\n
Example 3:
\n\nInput: n = 4, x = 1, y = 1\nOutput: [6,4,2,0]\nExplanation: For each distance k the pairs are:\n- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3).\n- For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2).\n- For k == 3, the pairs are (1, 4), and (4, 1).\n- For k == 4, there are no pairs.\n\n\n
\n
Constraints:
\n\n2 <= n <= 100
1 <= x, y <= n
You are given a string word
containing lowercase English letters.
Telephone keypads have keys mapped with distinct collections of lowercase English letters, which can be used to form words by pushing them. For example, the key 2
is mapped with ["a","b","c"]
, we need to push the key one time to type "a"
, two times to type "b"
, and three times to type "c"
.
It is allowed to remap the keys numbered 2
to 9
to distinct collections of letters. The keys can be remapped to any amount of letters, but each letter must be mapped to exactly one key. You need to find the minimum number of times the keys will be pushed to type the string word
.
Return the minimum number of pushes needed to type word
after remapping the keys.
An example mapping of letters to keys on a telephone keypad is given below. Note that 1
, *
, #
, and 0
do not map to any letters.
\n
Example 1:
\n\nInput: word = "abcde"\nOutput: 5\nExplanation: The remapped keypad given in the image provides the minimum cost.\n"a" -> one push on key 2\n"b" -> one push on key 3\n"c" -> one push on key 4\n"d" -> one push on key 5\n"e" -> one push on key 6\nTotal cost is 1 + 1 + 1 + 1 + 1 = 5.\nIt can be shown that no other mapping can provide a lower cost.\n\n\n
Example 2:
\n\nInput: word = "xyzxyzxyzxyz"\nOutput: 12\nExplanation: The remapped keypad given in the image provides the minimum cost.\n"x" -> one push on key 2\n"y" -> one push on key 3\n"z" -> one push on key 4\nTotal cost is 1 * 4 + 1 * 4 + 1 * 4 = 12\nIt can be shown that no other mapping can provide a lower cost.\nNote that the key 9 is not mapped to any letter: it is not necessary to map letters to every key, but to map all the letters.\n\n\n
Example 3:
\n\nInput: word = "aabbccddeeffgghhiiiiii"\nOutput: 24\nExplanation: The remapped keypad given in the image provides the minimum cost.\n"a" -> one push on key 2\n"b" -> one push on key 3\n"c" -> one push on key 4\n"d" -> one push on key 5\n"e" -> one push on key 6\n"f" -> one push on key 7\n"g" -> one push on key 8\n"h" -> two pushes on key 9\n"i" -> one push on key 9\nTotal cost is 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24.\nIt can be shown that no other mapping can provide a lower cost.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 105
word
consists of lowercase English letters.You are given three positive integers n
, x
, and y
.
In a city, there exist houses numbered 1
to n
connected by n
streets. There is a street connecting the house numbered i
with the house numbered i + 1
for all 1 <= i <= n - 1
. An additional street connects the house numbered x
with the house numbered y
.
For each k
, such that 1 <= k <= n
, you need to find the number of pairs of houses (house1, house2)
such that the minimum number of streets that need to be traveled to reach house2
from house1
is k
.
Return a 1-indexed array result
of length n
where result[k]
represents the total number of pairs of houses such that the minimum streets required to reach one house from the other is k
.
Note that x
and y
can be equal.
\n
Example 1:
\n\nInput: n = 3, x = 1, y = 3\nOutput: [6,0,0]\nExplanation: Let's look at each pair of houses:\n- For the pair (1, 2), we can go from house 1 to house 2 directly.\n- For the pair (2, 1), we can go from house 2 to house 1 directly.\n- For the pair (1, 3), we can go from house 1 to house 3 directly.\n- For the pair (3, 1), we can go from house 3 to house 1 directly.\n- For the pair (2, 3), we can go from house 2 to house 3 directly.\n- For the pair (3, 2), we can go from house 3 to house 2 directly.\n\n\n
Example 2:
\n\nInput: n = 5, x = 2, y = 4\nOutput: [10,8,2,0,0]\nExplanation: For each distance k the pairs are:\n- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3), (4, 5), and (5, 4).\n- For k == 2, the pairs are (1, 3), (3, 1), (1, 4), (4, 1), (2, 5), (5, 2), (3, 5), and (5, 3).\n- For k == 3, the pairs are (1, 5), and (5, 1).\n- For k == 4 and k == 5, there are no pairs.\n\n\n
Example 3:
\n\nInput: n = 4, x = 1, y = 1\nOutput: [6,4,2,0]\nExplanation: For each distance k the pairs are:\n- For k == 1, the pairs are (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), and (4, 3).\n- For k == 2, the pairs are (1, 3), (3, 1), (2, 4), and (4, 2).\n- For k == 3, the pairs are (1, 4), and (4, 1).\n- For k == 4, there are no pairs.\n\n\n
\n
Constraints:
\n\n2 <= n <= 105
1 <= x, y <= n
You are given a 0-indexed string s
typed by a user. Changing a key is defined as using a key different from the last used key. For example, s = "ab"
has a change of a key while s = "bBBb"
does not have any.
Return the number of times the user had to change the key.
\n\nNote: Modifiers like shift
or caps lock
won't be counted in changing the key that is if a user typed the letter 'a'
and then the letter 'A'
then it will not be considered as a changing of key.
\n
Example 1:
\n\n\nInput: s = "aAbBcC"\nOutput: 2\nExplanation: \nFrom s[0] = 'a' to s[1] = 'A', there is no change of key as caps lock or shift is not counted.\nFrom s[1] = 'A' to s[2] = 'b', there is a change of key.\nFrom s[2] = 'b' to s[3] = 'B', there is no change of key as caps lock or shift is not counted.\nFrom s[3] = 'B' to s[4] = 'c', there is a change of key.\nFrom s[4] = 'c' to s[5] = 'C', there is no change of key as caps lock or shift is not counted.\n\n\n\n
Example 2:
\n\n\nInput: s = "AaAaAaaA"\nOutput: 0\nExplanation: There is no change of key since only the letters 'a' and 'A' are pressed which does not require change of key.\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of only upper case and lower case English letters.You are given an array of positive integers nums
.
You need to select a subset of nums
which satisfies the following condition:
[x, x2, x4, ..., xk/2, xk, xk/2, ..., x4, x2, x]
(Note that k
can be be any non-negative power of 2
). For example, [2, 4, 16, 4, 2]
and [3, 9, 3]
follow the pattern while [2, 4, 8, 4, 2]
does not.Return the maximum number of elements in a subset that satisfies these conditions.
\n\n\n
Example 1:
\n\n\nInput: nums = [5,4,1,2,2]\nOutput: 3\nExplanation: We can select the subset {4,2,2}, which can be placed in the array as [2,4,2] which follows the pattern and 22 == 4. Hence the answer is 3.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3,2,4]\nOutput: 1\nExplanation: We can select the subset {1}, which can be placed in the array as [1] which follows the pattern. Hence the answer is 1. Note that we could have also selected the subsets {2}, {3}, or {4}, there may be multiple subsets which provide the same answer. \n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] <= 109
Alice and Bob are playing a turn-based game on a circular field surrounded by flowers. The circle represents the field, and there are x
flowers in the clockwise direction between Alice and Bob, and y
flowers in the anti-clockwise direction between them.
The game proceeds as follows:
\n\nGiven two integers, n
and m
, the task is to compute the number of possible pairs (x, y)
that satisfy the conditions:
x
in the clockwise direction must be in the range [1,n]
.y
in the anti-clockwise direction must be in the range [1,m]
.Return the number of possible pairs (x, y)
that satisfy the conditions mentioned in the statement.
\n
Example 1:
\n\n\nInput: n = 3, m = 2\nOutput: 3\nExplanation: The following pairs satisfy conditions described in the statement: (1,2), (3,2), (2,1).\n\n\n
Example 2:
\n\n\nInput: n = 1, m = 1\nOutput: 0\nExplanation: No pairs satisfy the conditions described in the statement.\n\n\n
\n
Constraints:
\n\n1 <= n, m <= 105
You are given a 0-indexed integer array nums
and an integer k
.
In one operation, you can pick any index i
of nums
such that 0 <= i < nums.length - 1
and replace nums[i]
and nums[i + 1]
with a single occurrence of nums[i] & nums[i + 1]
, where &
represents the bitwise AND
operator.
Return the minimum possible value of the bitwise OR
of the remaining elements of nums
after applying at most k
operations.
\n
Example 1:
\n\n\nInput: nums = [3,5,3,2,7], k = 2\nOutput: 3\nExplanation: Let's do the following operations:\n1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [1,3,2,7].\n2. Replace nums[2] and nums[3] with (nums[2] & nums[3]) so that nums becomes equal to [1,3,2].\nThe bitwise-or of the final array is 3.\nIt can be shown that 3 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.\n\n
Example 2:
\n\n\nInput: nums = [7,3,15,14,2,8], k = 4\nOutput: 2\nExplanation: Let's do the following operations:\n1. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,15,14,2,8]. \n2. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [3,14,2,8].\n3. Replace nums[0] and nums[1] with (nums[0] & nums[1]) so that nums becomes equal to [2,2,8].\n4. Replace nums[1] and nums[2] with (nums[1] & nums[2]) so that nums becomes equal to [2,0].\nThe bitwise-or of the final array is 2.\nIt can be shown that 2 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.\n\n\n
Example 3:
\n\n\nInput: nums = [10,7,10,3,9,14,9,4], k = 1\nOutput: 15\nExplanation: Without applying any operations, the bitwise-or of nums is 15.\nIt can be shown that 15 is the minimum possible value of the bitwise OR of the remaining elements of nums after applying at most k operations.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] < 230
0 <= k < nums.length
You are given a 0-indexed integer array nums
of size 3
which can form the sides of a triangle.
Return a string representing the type of triangle that can be formed or "none"
if it cannot form a triangle.
\n
Example 1:
\n\n\nInput: nums = [3,3,3]\nOutput: "equilateral"\nExplanation: Since all the sides are of equal length, therefore, it will form an equilateral triangle.\n\n\n
Example 2:
\n\n\nInput: nums = [3,4,5]\nOutput: "scalene"\nExplanation: \nnums[0] + nums[1] = 3 + 4 = 7, which is greater than nums[2] = 5.\nnums[0] + nums[2] = 3 + 5 = 8, which is greater than nums[1] = 4.\nnums[1] + nums[2] = 4 + 5 = 9, which is greater than nums[0] = 3. \nSince the sum of the two sides is greater than the third side for all three cases, therefore, it can form a triangle.\nAs all the sides are of different lengths, it will form a scalene triangle.\n\n\n
\n
Constraints:
\n\nnums.length == 3
1 <= nums[i] <= 100
You are given a 2D array points
of size n x 2
representing integer coordinates of some points on a 2D plane, where points[i] = [xi, yi]
.
Count the number of pairs of points (A, B)
, where
A
is on the upper left side of B
, andReturn the count.
\n\n\n
Example 1:
\n\nInput: points = [[1,1],[2,2],[3,3]]
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no way to choose A
and B
so A
is on the upper left side of B
.
Example 2:
\n\nInput: points = [[6,2],[4,4],[2,6]]
\n\nOutput: 2
\n\nExplanation:
\n\n(points[1], points[0])
, where points[1]
is on the upper left side of points[0]
and the rectangle is empty.(points[2], points[1])
, same as the left one it is a valid pair.(points[2], points[0])
, where points[2]
is on the upper left side of points[0]
, but points[1]
is inside the rectangle so it's not a valid pair.Example 3:
\n\nInput: points = [[3,1],[1,3],[1,1]]
\n\nOutput: 2
\n\nExplanation:
\n\n(points[2], points[0])
, where points[2]
is on the upper left side of points[0]
and there are no other points on the line they form. Note that it is a valid state when the two points form a line.(points[1], points[2])
, it is a valid pair same as the left one.(points[1], points[0])
, it is not a valid pair as points[2]
is on the border of the rectangle.\n
Constraints:
\n\n2 <= n <= 50
points[i].length == 2
0 <= points[i][0], points[i][1] <= 50
points[i]
are distinct.You are given an array nums
of length n
and a positive integer k
.
A subarray of nums
is called good if the absolute difference between its first and last element is exactly k
, in other words, the subarray nums[i..j]
is good if |nums[i] - nums[j]| == k
.
Return the maximum sum of a good subarray of nums
. If there are no good subarrays, return 0
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6], k = 1\nOutput: 11\nExplanation: The absolute difference between the first and last element must be 1 for a good subarray. All the good subarrays are: [1,2], [2,3], [3,4], [4,5], and [5,6]. The maximum subarray sum is 11 for the subarray [5,6].\n\n\n
Example 2:
\n\n\nInput: nums = [-1,3,2,4,5], k = 3\nOutput: 11\nExplanation: The absolute difference between the first and last element must be 3 for a good subarray. All the good subarrays are: [-1,3,2], and [2,4,5]. The maximum subarray sum is 11 for the subarray [2,4,5].\n\n\n
Example 3:
\n\n\nInput: nums = [-1,-2,-3,-4], k = 2\nOutput: -6\nExplanation: The absolute difference between the first and last element must be 2 for a good subarray. All the good subarrays are: [-1,-2,-3], and [-2,-3,-4]. The maximum subarray sum is -6 for the subarray [-1,-2,-3].\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 105
-109 <= nums[i] <= 109
1 <= k <= 109
You are given a 2D array points
of size n x 2
representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi]
.
We define the right direction as positive x-axis (increasing x-coordinate) and the left direction as negative x-axis (decreasing x-coordinate). Similarly, we define the up direction as positive y-axis (increasing y-coordinate) and the down direction as negative y-axis (decreasing y-coordinate)
\n\nYou have to place n
people, including Alice and Bob, at these points such that there is exactly one person at every point. Alice wants to be alone with Bob, so Alice will build a rectangular fence with Alice's position as the upper left corner and Bob's position as the lower right corner of the fence (Note that the fence might not enclose any area, i.e. it can be a line). If any person other than Alice and Bob is either inside the fence or on the fence, Alice will be sad.
Return the number of pairs of points where you can place Alice and Bob, such that Alice does not become sad on building the fence.
\n\nNote that Alice can only build a fence with Alice's position as the upper left corner, and Bob's position as the lower right corner. For example, Alice cannot build either of the fences in the picture below with four corners (1, 1)
, (1, 3)
, (3, 1)
, and (3, 3)
, because:
(3, 3)
and Bob at (1, 1)
, Alice's position is not the upper left corner and Bob's position is not the lower right corner of the fence.(1, 3)
and Bob at (1, 1)
, Bob's position is not the lower right corner of the fence.\n
Example 1:
\n\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 0\nExplanation: There is no way to place Alice and Bob such that Alice can build a fence with Alice's position as the upper left corner and Bob's position as the lower right corner. Hence we return 0. \n\n\n
Example 2:
\n\nInput: points = [[6,2],[4,4],[2,6]]\nOutput: 2\nExplanation: There are two ways to place Alice and Bob such that Alice will not be sad:\n- Place Alice at (4, 4) and Bob at (6, 2).\n- Place Alice at (2, 6) and Bob at (4, 4).\nYou cannot place Alice at (2, 6) and Bob at (6, 2) because the person at (4, 4) will be inside the fence.\n\n\n
Example 3:
\n\nInput: points = [[3,1],[1,3],[1,1]]\nOutput: 2\nExplanation: There are two ways to place Alice and Bob such that Alice will not be sad:\n- Place Alice at (1, 1) and Bob at (3, 1).\n- Place Alice at (1, 3) and Bob at (1, 1).\nYou cannot place Alice at (1, 3) and Bob at (3, 1) because the person at (1, 1) will be on the fence.\nNote that it does not matter if the fence encloses any area, the first and second fences in the image are valid.\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
points[i].length == 2
-109 <= points[i][0], points[i][1] <= 109
points[i]
are distinct.An ant is on a boundary. It sometimes goes left and sometimes right.
\n\nYou are given an array of non-zero integers nums
. The ant starts reading nums
from the first element of it to its end. At each step, it moves according to the value of the current element:
nums[i] < 0
, it moves left by -nums[i]
units.nums[i] > 0
, it moves right by nums[i]
units.Return the number of times the ant returns to the boundary.
\n\nNotes:
\n\n|nums[i]|
units. In other words, if the ant crosses the boundary during its movement, it does not count.\n
Example 1:
\n\n\nInput: nums = [2,3,-5]\nOutput: 1\nExplanation: After the first step, the ant is 2 steps to the right of the boundary.\nAfter the second step, the ant is 5 steps to the right of the boundary.\nAfter the third step, the ant is on the boundary.\nSo the answer is 1.\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,-3,-4]\nOutput: 0\nExplanation: After the first step, the ant is 3 steps to the right of the boundary.\nAfter the second step, the ant is 5 steps to the right of the boundary.\nAfter the third step, the ant is 2 steps to the right of the boundary.\nAfter the fourth step, the ant is 2 steps to the left of the boundary.\nThe ant never returned to the boundary, so the answer is 0.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
-10 <= nums[i] <= 10
nums[i] != 0
You are given a 0-indexed string word
and an integer k
.
At every second, you must perform the following operations:
\n\nk
characters of word
.k
characters to the end of word
.Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second.
\n\nReturn the minimum time greater than zero required for word
to revert to its initial state.
\n
Example 1:
\n\n\nInput: word = "abacaba", k = 3\nOutput: 2\nExplanation: At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".\nAt the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.\nIt can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
Example 2:
\n\n\nInput: word = "abacaba", k = 4\nOutput: 1\nExplanation: At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.\nIt can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
Example 3:
\n\n\nInput: word = "abcbabcd", k = 2\nOutput: 4\nExplanation: At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.\nAfter 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.\nIt can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 50
1 <= k <= word.length
word
consists only of lowercase English letters.You are given m x n
grid image
which represents a grayscale image, where image[i][j]
represents a pixel with intensity in the range [0..255]
. You are also given a non-negative integer threshold
.
Two pixels are adjacent if they share an edge.
\n\nA region is a 3 x 3
subgrid where the absolute difference in intensity between any two adjacent pixels is less than or equal to threshold
.
All pixels in a region belong to that region, note that a pixel can belong to multiple regions.
\n\nYou need to calculate a m x n
grid result
, where result[i][j]
is the average intensity of the regions to which image[i][j]
belongs, rounded down to the nearest integer. If image[i][j]
belongs to multiple regions, result[i][j]
is the average of the rounded-down average intensities of these regions, rounded down to the nearest integer. If image[i][j]
does not belong to any region, result[i][j]
is equal to image[i][j]
.
Return the grid result
.
\n
Example 1:
\n\nInput: image = [[5,6,7,10],[8,9,10,10],[11,12,13,10]], threshold = 3
\n\nOutput: [[9,9,9,9],[9,9,9,9],[9,9,9,9]]
\n\nExplanation:
\n\nThere are two regions as illustrated above. The average intensity of the first region is 9, while the average intensity of the second region is 9.67 which is rounded down to 9. The average intensity of both of the regions is (9 + 9) / 2 = 9. As all the pixels belong to either region 1, region 2, or both of them, the intensity of every pixel in the result is 9.
\n\nPlease note that the rounded-down values are used when calculating the average of multiple regions, hence the calculation is done using 9 as the average intensity of region 2, not 9.67.
\nExample 2:
\n\nInput: image = [[10,20,30],[15,25,35],[20,30,40],[25,35,45]], threshold = 12
\n\nOutput: [[25,25,25],[27,27,27],[27,27,27],[30,30,30]]
\n\nExplanation:
\n\nThere are two regions as illustrated above. The average intensity of the first region is 25, while the average intensity of the second region is 30. The average intensity of both of the regions is (25 + 30) / 2 = 27.5 which is rounded down to 27.
\n\nAll the pixels in row 0 of the image belong to region 1, hence all the pixels in row 0 in the result are 25. Similarly, all the pixels in row 3 in the result are 30. The pixels in rows 1 and 2 of the image belong to region 1 and region 2, hence their assigned value is 27 in the result.
\nExample 3:
\n\nInput: image = [[5,6,7],[8,9,10],[11,12,13]], threshold = 1
\n\nOutput: [[5,6,7],[8,9,10],[11,12,13]]
\n\nExplanation:
\n\nThere is only one 3 x 3
subgrid, while it does not have the condition on difference of adjacent pixels, for example, the difference between image[0][0]
and image[1][0]
is |5 - 8| = 3 > threshold = 1
. None of them belong to any valid regions, so the result
should be the same as image
.
\n
Constraints:
\n\n3 <= n, m <= 500
0 <= image[i][j] <= 255
0 <= threshold <= 255
You are given a 0-indexed string word
and an integer k
.
At every second, you must perform the following operations:
\n\nk
characters of word
.k
characters to the end of word
.Note that you do not necessarily need to add the same characters that you removed. However, you must perform both operations at every second.
\n\nReturn the minimum time greater than zero required for word
to revert to its initial state.
\n
Example 1:
\n\n\nInput: word = "abacaba", k = 3\nOutput: 2\nExplanation: At the 1st second, we remove characters "aba" from the prefix of word, and add characters "bac" to the end of word. Thus, word becomes equal to "cababac".\nAt the 2nd second, we remove characters "cab" from the prefix of word, and add "aba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.\nIt can be shown that 2 seconds is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
Example 2:
\n\n\nInput: word = "abacaba", k = 4\nOutput: 1\nExplanation: At the 1st second, we remove characters "abac" from the prefix of word, and add characters "caba" to the end of word. Thus, word becomes equal to "abacaba" and reverts to its initial state.\nIt can be shown that 1 second is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
Example 3:
\n\n\nInput: word = "abcbabcd", k = 2\nOutput: 4\nExplanation: At every second, we will remove the first 2 characters of word, and add the same characters to the end of word.\nAfter 4 seconds, word becomes equal to "abcbabcd" and reverts to its initial state.\nIt can be shown that 4 seconds is the minimum time greater than zero required for word to revert to its initial state.\n\n\n
\n
Constraints:
\n\n1 <= word.length <= 106
1 <= k <= word.length
word
consists only of lowercase English letters.Given a 0-indexed m x n
integer matrix matrix
, create a new 0-indexed matrix called answer
. Make answer
equal to matrix
, then replace each element with the value -1
with the maximum element in its respective column.
Return the matrix answer
.
\n
Example 1:
\n\nInput: matrix = [[1,2,-1],[4,-1,6],[7,8,9]]\nOutput: [[1,2,9],[4,8,6],[7,8,9]]\nExplanation: The diagram above shows the elements that are changed (in blue).\n- We replace the value in the cell [1][1] with the maximum value in the column 1, that is 8.\n- We replace the value in the cell [0][2] with the maximum value in the column 2, that is 9.\n\n\n
Example 2:
\n\nInput: matrix = [[3,-1],[5,2]]\nOutput: [[3,2],[5,2]]\nExplanation: The diagram above shows the elements that are changed (in blue).\n\n\n
\n
Constraints:
\n\nm == matrix.length
n == matrix[i].length
2 <= m, n <= 50
-1 <= matrix[i][j] <= 100
You are given a 0-indexed integer array nums
of size n
, and a 0-indexed integer array pattern
of size m
consisting of integers -1
, 0
, and 1
.
A subarray nums[i..j]
of size m + 1
is said to match the pattern
if the following conditions hold for each element pattern[k]
:
nums[i + k + 1] > nums[i + k]
if pattern[k] == 1
.nums[i + k + 1] == nums[i + k]
if pattern[k] == 0
.nums[i + k + 1] < nums[i + k]
if pattern[k] == -1
.Return the count of subarrays in nums
that match the pattern
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6], pattern = [1,1]\nOutput: 4\nExplanation: The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.\nHence, there are 4 subarrays in nums that match the pattern.\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]\nOutput: 2\nExplanation: Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.\nHence, there are 2 subarrays in nums that match the pattern.\n\n\n
\n
Constraints:
\n\n2 <= n == nums.length <= 100
1 <= nums[i] <= 109
1 <= m == pattern.length < n
-1 <= pattern[i] <= 1
You are given a 0-indexed string array words
having length n
and containing 0-indexed strings.
You are allowed to perform the following operation any number of times (including zero):
\n\ni
, j
, x
, and y
such that 0 <= i, j < n
, 0 <= x < words[i].length
, 0 <= y < words[j].length
, and swap the characters words[i][x]
and words[j][y]
.Return an integer denoting the maximum number of palindromes words
can contain, after performing some operations.
Note: i
and j
may be equal during an operation.
\n
Example 1:
\n\n\nInput: words = ["abbb","ba","aa"]\nOutput: 3\nExplanation: In this example, one way to get the maximum number of palindromes is:\nChoose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].\nAll strings in words are now palindromes.\nHence, the maximum number of palindromes achievable is 3.\n\n
Example 2:
\n\n\nInput: words = ["abc","ab"]\nOutput: 2\nExplanation: In this example, one way to get the maximum number of palindromes is: \nChoose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].\nChoose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].\nBoth strings are now palindromes.\nHence, the maximum number of palindromes achievable is 2.\n\n\n
Example 3:
\n\n\nInput: words = ["cd","ef","a"]\nOutput: 1\nExplanation: In this example, there is no need to perform any operation.\nThere is one palindrome in words "a".\nIt can be shown that it is not possible to get more than one palindrome after any number of operations.\nHence, the answer is 1.\n\n
\n
Constraints:
\n\n1 <= words.length <= 1000
1 <= words[i].length <= 100
words[i]
consists only of lowercase English letters.You are given a 0-indexed integer array nums
of size n
, and a 0-indexed integer array pattern
of size m
consisting of integers -1
, 0
, and 1
.
A subarray nums[i..j]
of size m + 1
is said to match the pattern
if the following conditions hold for each element pattern[k]
:
nums[i + k + 1] > nums[i + k]
if pattern[k] == 1
.nums[i + k + 1] == nums[i + k]
if pattern[k] == 0
.nums[i + k + 1] < nums[i + k]
if pattern[k] == -1
.Return the count of subarrays in nums
that match the pattern
.
\n
Example 1:
\n\n\nInput: nums = [1,2,3,4,5,6], pattern = [1,1]\nOutput: 4\nExplanation: The pattern [1,1] indicates that we are looking for strictly increasing subarrays of size 3. In the array nums, the subarrays [1,2,3], [2,3,4], [3,4,5], and [4,5,6] match this pattern.\nHence, there are 4 subarrays in nums that match the pattern.\n\n\n
Example 2:
\n\n\nInput: nums = [1,4,4,1,3,5,5,3], pattern = [1,0,-1]\nOutput: 2\nExplanation: Here, the pattern [1,0,-1] indicates that we are looking for a sequence where the first number is smaller than the second, the second is equal to the third, and the third is greater than the fourth. In the array nums, the subarrays [1,4,4,1], and [3,5,5,3] match this pattern.\nHence, there are 2 subarrays in nums that match the pattern.\n\n\n
\n
Constraints:
\n\n2 <= n == nums.length <= 106
1 <= nums[i] <= 109
1 <= m == pattern.length < n
-1 <= pattern[i] <= 1
You are given an array of integers nums
. Consider the following operation:
nums
and define the score of the operation as the sum of these two elements.You can perform this operation until nums
contains fewer than two elements. Additionally, the same score must be achieved in all operations.
Return the maximum number of operations you can perform.
\n\n\n
Example 1:
\n\nInput: nums = [3,2,1,4,5]
\n\nOutput: 2
\n\nExplanation:
\n\n3 + 2 = 5
. After this operation, nums = [1,4,5]
.4 + 1 = 5
, the same as the previous operation. After this operation, nums = [5]
.Example 2:
\n\nInput: nums = [1,5,3,3,4,1,3,2,2,3]
\n\nOutput: 2
\n\nExplanation:
\n\n1 + 5 = 6
. After this operation, nums = [3,3,4,1,3,2,2,3]
.3 + 3 = 6
, the same as the previous operation. After this operation, nums = [4,1,3,2,2,3]
.4 + 1 = 5
, which is different from the previous scores.Example 3:
\n\nInput: nums = [5,3]
\n\nOutput: 1
\n\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 1000
You are given a string s
.
Consider performing the following operation until s
becomes empty:
'a'
to 'z'
, remove the first occurrence of that character in s
(if it exists).For example, let initially s = "aabcbbca"
. We do the following operations:
s = "aabcbbca"
. The resulting string is s = "abbca"
.s = "abbca"
. The resulting string is s = "ba"
.s = "ba"
. The resulting string is s = ""
.Return the value of the string s
right before applying the last operation. In the example above, answer is "ba"
.
\n
Example 1:
\n\n\nInput: s = "aabcbbca"\nOutput: "ba"\nExplanation: Explained in the statement.\n\n\n
Example 2:
\n\n\nInput: s = "abcd"\nOutput: "abcd"\nExplanation: We do the following operation:\n- Remove the underlined characters s = "abcd". The resulting string is s = "".\nThe string just before the last operation is "abcd".\n\n\n
\n
Constraints:
\n\n1 <= s.length <= 5 * 105
s
consists only of lowercase English letters.Given an array of integers called nums
, you can perform any of the following operation while nums
contains at least 2
elements:
nums
and delete them.nums
and delete them.nums
and delete them.The score of the operation is the sum of the deleted elements.
\n\nYour task is to find the maximum number of operations that can be performed, such that all operations have the same score.
\n\nReturn the maximum number of operations possible that satisfy the condition mentioned above.
\n\n\n
Example 1:
\n\n\nInput: nums = [3,2,1,2,3,4]\nOutput: 3\nExplanation: We perform the following operations:\n- Delete the first two elements, with score 3 + 2 = 5, nums = [1,2,3,4].\n- Delete the first and the last elements, with score 1 + 4 = 5, nums = [2,3].\n- Delete the first and the last elements, with score 2 + 3 = 5, nums = [].\nWe are unable to perform any more operations as nums is empty.\n\n\n
Example 2:
\n\n\nInput: nums = [3,2,6,1,4]\nOutput: 2\nExplanation: We perform the following operations:\n- Delete the first two elements, with score 3 + 2 = 5, nums = [6,1,4].\n- Delete the last two elements, with score 1 + 4 = 5, nums = [6].\nIt can be proven that we can perform at most 2 operations.\n\n\n
\n
Constraints:
\n\n2 <= nums.length <= 2000
1 <= nums[i] <= 1000
You are given a 0-indexed array nums
consisting of positive integers.
Initially, you can increase the value of any element in the array by at most 1
.
After that, you need to select one or more elements from the final array such that those elements are consecutive when sorted in increasing order. For example, the elements [3, 4, 5]
are consecutive while [3, 4, 6]
and [1, 1, 2, 3]
are not.
Return the maximum number of elements that you can select.
\n\n\n
Example 1:
\n\n\nInput: nums = [2,1,5,1,1]\nOutput: 3\nExplanation: We can increase the elements at indices 0 and 3. The resulting array is nums = [3,1,5,2,1].\nWe select the elements [3,1,5,2,1] and we sort them to obtain [1,2,3], which are consecutive.\nIt can be shown that we cannot select more than 3 consecutive elements.\n\n
Example 2:
\n\n\nInput: nums = [1,4,7,10]\nOutput: 1\nExplanation: The maximum consecutive elements that we can select is 1.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
You are given a 0-indexed string array words
.
Let's define a boolean function isPrefixAndSuffix
that takes two strings, str1
and str2
:
isPrefixAndSuffix(str1, str2)
returns true
if str1
is both a prefix and a suffix of str2
, and false
otherwise.For example, isPrefixAndSuffix("aba", "ababa")
is true
because "aba"
is a prefix of "ababa"
and also a suffix, but isPrefixAndSuffix("abc", "abcd")
is false
.
Return an integer denoting the number of index pairs (i, j)
such that i < j
, and isPrefixAndSuffix(words[i], words[j])
is true
.
\n
Example 1:
\n\n\nInput: words = ["a","aba","ababa","aa"]\nOutput: 4\nExplanation: In this example, the counted index pairs are:\ni = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.\ni = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.\ni = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.\ni = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.\nTherefore, the answer is 4.\n\n
Example 2:
\n\n\nInput: words = ["pa","papa","ma","mama"]\nOutput: 2\nExplanation: In this example, the counted index pairs are:\ni = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.\ni = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.\nTherefore, the answer is 2.\n\n
Example 3:
\n\n\nInput: words = ["abab","ab"]\nOutput: 0\nExplanation: In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.\nTherefore, the answer is 0.\n\n
\n
Constraints:
\n\n1 <= words.length <= 50
1 <= words[i].length <= 10
words[i]
consists only of lowercase English letters.You are given two arrays with positive integers arr1
and arr2
.
A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123
is a prefix of the integer 12345
, while 234
is not.
A common prefix of two integers a
and b
is an integer c
, such that c
is a prefix of both a
and b
. For example, 5655359
and 56554
have common prefixes 565
and 5655
while 1223
and 43456
do not have a common prefix.
You need to find the length of the longest common prefix between all pairs of integers (x, y)
such that x
belongs to arr1
and y
belongs to arr2
.
Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0
.
\n
Example 1:
\n\n\nInput: arr1 = [1,10,100], arr2 = [1000]\nOutput: 3\nExplanation: There are 3 pairs (arr1[i], arr2[j]):\n- The longest common prefix of (1, 1000) is 1.\n- The longest common prefix of (10, 1000) is 10.\n- The longest common prefix of (100, 1000) is 100.\nThe longest common prefix is 100 with a length of 3.\n\n\n
Example 2:
\n\n\nInput: arr1 = [1,2,3], arr2 = [4,4,4]\nOutput: 0\nExplanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0.\nNote that common prefixes between elements of the same array do not count.\n\n\n
\n
Constraints:
\n\n1 <= arr1.length, arr2.length <= 5 * 104
1 <= arr1[i], arr2[i] <= 108
You are given a m x n
0-indexed 2D matrix mat
. From every cell, you can create numbers in the following way:
8
paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east.1, 9, 1
, then there will be three numbers generated along the way: 1, 19, 191
.Return the most frequent prime number greater than 10
out of all the numbers created by traversing the matrix or -1
if no such prime number exists. If there are multiple prime numbers with the highest frequency, then return the largest among them.
Note: It is invalid to change the direction during the move.
\n\n\n
Example 1:
\n\n\nInput: mat = [[1,1],[9,9],[1,1]]\nOutput: 19\nExplanation: \nFrom cell (0,0) there are 3 possible directions and the numbers greater than 10 which can be created in those directions are:\nEast: [11], South-East: [19], South: [19,191].\nNumbers greater than 10 created from the cell (0,1) in all possible directions are: [19,191,19,11].\nNumbers greater than 10 created from the cell (1,0) in all possible directions are: [99,91,91,91,91].\nNumbers greater than 10 created from the cell (1,1) in all possible directions are: [91,91,99,91,91].\nNumbers greater than 10 created from the cell (2,0) in all possible directions are: [11,19,191,19].\nNumbers greater than 10 created from the cell (2,1) in all possible directions are: [11,19,19,191].\nThe most frequent prime number among all the created numbers is 19.\n\n
Example 2:
\n\n\nInput: mat = [[7]]\nOutput: -1\nExplanation: The only number which can be formed is 7. It is a prime number however it is not greater than 10, so return -1.\n\n
Example 3:
\n\n\nInput: mat = [[9,7,8],[4,6,5],[2,8,6]]\nOutput: 97\nExplanation: \nNumbers greater than 10 created from the cell (0,0) in all possible directions are: [97,978,96,966,94,942].\nNumbers greater than 10 created from the cell (0,1) in all possible directions are: [78,75,76,768,74,79].\nNumbers greater than 10 created from the cell (0,2) in all possible directions are: [85,856,86,862,87,879].\nNumbers greater than 10 created from the cell (1,0) in all possible directions are: [46,465,48,42,49,47].\nNumbers greater than 10 created from the cell (1,1) in all possible directions are: [65,66,68,62,64,69,67,68].\nNumbers greater than 10 created from the cell (1,2) in all possible directions are: [56,58,56,564,57,58].\nNumbers greater than 10 created from the cell (2,0) in all possible directions are: [28,286,24,249,26,268].\nNumbers greater than 10 created from the cell (2,1) in all possible directions are: [86,82,84,86,867,85].\nNumbers greater than 10 created from the cell (2,2) in all possible directions are: [68,682,66,669,65,658].\nThe most frequent prime number among all the created numbers is 97.\n\n\n
\n
Constraints:
\n\nm == mat.length
n == mat[i].length
1 <= m, n <= 6
1 <= mat[i][j] <= 9
You are given a 0-indexed string array words
.
Let's define a boolean function isPrefixAndSuffix
that takes two strings, str1
and str2
:
isPrefixAndSuffix(str1, str2)
returns true
if str1
is both a prefix and a suffix of str2
, and false
otherwise.For example, isPrefixAndSuffix("aba", "ababa")
is true
because "aba"
is a prefix of "ababa"
and also a suffix, but isPrefixAndSuffix("abc", "abcd")
is false
.
Return an integer denoting the number of index pairs (i, j)
such that i < j
, and isPrefixAndSuffix(words[i], words[j])
is true
.
\n
Example 1:
\n\n\nInput: words = ["a","aba","ababa","aa"]\nOutput: 4\nExplanation: In this example, the counted index pairs are:\ni = 0 and j = 1 because isPrefixAndSuffix("a", "aba") is true.\ni = 0 and j = 2 because isPrefixAndSuffix("a", "ababa") is true.\ni = 0 and j = 3 because isPrefixAndSuffix("a", "aa") is true.\ni = 1 and j = 2 because isPrefixAndSuffix("aba", "ababa") is true.\nTherefore, the answer is 4.\n\n
Example 2:
\n\n\nInput: words = ["pa","papa","ma","mama"]\nOutput: 2\nExplanation: In this example, the counted index pairs are:\ni = 0 and j = 1 because isPrefixAndSuffix("pa", "papa") is true.\ni = 2 and j = 3 because isPrefixAndSuffix("ma", "mama") is true.\nTherefore, the answer is 2.\n\n
Example 3:
\n\n\nInput: words = ["abab","ab"]\nOutput: 0\nExplanation: In this example, the only valid index pair is i = 0 and j = 1, and isPrefixAndSuffix("abab", "ab") is false.\nTherefore, the answer is 0.\n\n
\n
Constraints:
\n\n1 <= words.length <= 105
1 <= words[i].length <= 105
words[i]
consists only of lowercase English letters.words[i]
does not exceed 5 * 105
.You are given an integer array nums
of even length. You have to split the array into two parts nums1
and nums2
such that:
nums1.length == nums2.length == nums.length / 2
.nums1
should contain distinct elements.nums2
should also contain distinct elements.Return true
if it is possible to split the array, and false
otherwise.
\n
Example 1:
\n\n\nInput: nums = [1,1,2,2,3,4]\nOutput: true\nExplanation: One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,1,1]\nOutput: false\nExplanation: The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100
There exist n
rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays bottomLeft
and topRight
where bottomLeft[i] = [a_i, b_i]
and topRight[i] = [c_i, d_i]
represent the bottom-left and top-right coordinates of the ith
rectangle, respectively.
You need to find the maximum area of a square that can fit inside the intersecting region of at least two rectangles. Return 0
if such a square does not exist.
\n
Example 1:
\nInput: bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[6,6]]
\n\nOutput: 1
\n\nExplanation:
\n\nA square with side length 1 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 1. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.
\n\nExample 2:
\nInput: bottomLeft = [[1,1],[1,3],[1,5]], topRight = [[5,5],[5,7],[5,9]]
\n\nOutput: 4
\n\nExplanation:
\n\nA square with side length 2 can fit inside either the intersecting region of rectangles 0 and 1 or the intersecting region of rectangles 1 and 2. Hence the maximum area is 2 * 2 = 4
. It can be shown that a square with a greater side length can not fit inside any intersecting region of two rectangles.
Example 3:
\n
\n\nInput: bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[3,3],[4,4],[3,4]]
\n\nOutput: 1
\n\nExplanation:
\n\nA square with side length 1 can fit inside the intersecting region of any two rectangles. Also, no larger square can, so the maximum area is 1. Note that the region can be formed by the intersection of more than 2 rectangles.
\n\nExample 4:
\n
\n\nInput: bottomLeft = [[1,1],[3,3],[3,1]], topRight = [[2,2],[4,4],[4,2]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo pair of rectangles intersect, hence, the answer is 0.
\n\n\n
Constraints:
\n\nn == bottomLeft.length == topRight.length
2 <= n <= 103
bottomLeft[i].length == topRight[i].length == 2
1 <= bottomLeft[i][0], bottomLeft[i][1] <= 107
1 <= topRight[i][0], topRight[i][1] <= 107
bottomLeft[i][0] < topRight[i][0]
bottomLeft[i][1] < topRight[i][1]
You are given two 1-indexed integer arrays, nums
and, changeIndices
, having lengths n
and m
, respectively.
Initially, all indices in nums
are unmarked. Your task is to mark all indices in nums
.
In each second, s
, in order from 1
to m
(inclusive), you can perform one of the following operations:
i
in the range [1, n]
and decrement nums[i]
by 1
.nums[changeIndices[s]]
is equal to 0
, mark the index changeIndices[s]
.Return an integer denoting the earliest second in the range [1, m]
when all indices in nums
can be marked by choosing operations optimally, or -1
if it is impossible.
\n
Example 1:
\n\n\nInput: nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,1]\nOutput: 8\nExplanation: In this example, we have 8 seconds. The following operations can be performed to mark all indices:\nSecond 1: Choose index 1 and decrement nums[1] by one. nums becomes [1,2,0].\nSecond 2: Choose index 1 and decrement nums[1] by one. nums becomes [0,2,0].\nSecond 3: Choose index 2 and decrement nums[2] by one. nums becomes [0,1,0].\nSecond 4: Choose index 2 and decrement nums[2] by one. nums becomes [0,0,0].\nSecond 5: Mark the index changeIndices[5], which is marking index 3, since nums[3] is equal to 0.\nSecond 6: Mark the index changeIndices[6], which is marking index 2, since nums[2] is equal to 0.\nSecond 7: Do nothing.\nSecond 8: Mark the index changeIndices[8], which is marking index 1, since nums[1] is equal to 0.\nNow all indices have been marked.\nIt can be shown that it is not possible to mark all indices earlier than the 8th second.\nHence, the answer is 8.\n\n\n
Example 2:
\n\n\nInput: nums = [1,3], changeIndices = [1,1,1,2,1,1,1]\nOutput: 6\nExplanation: In this example, we have 7 seconds. The following operations can be performed to mark all indices:\nSecond 1: Choose index 2 and decrement nums[2] by one. nums becomes [1,2].\nSecond 2: Choose index 2 and decrement nums[2] by one. nums becomes [1,1].\nSecond 3: Choose index 2 and decrement nums[2] by one. nums becomes [1,0].\nSecond 4: Mark the index changeIndices[4], which is marking index 2, since nums[2] is equal to 0.\nSecond 5: Choose index 1 and decrement nums[1] by one. nums becomes [0,0].\nSecond 6: Mark the index changeIndices[6], which is marking index 1, since nums[1] is equal to 0.\nNow all indices have been marked.\nIt can be shown that it is not possible to mark all indices earlier than the 6th second.\nHence, the answer is 6.\n\n\n
Example 3:
\n\n\nInput: nums = [0,1], changeIndices = [2,2,2]\nOutput: -1\nExplanation: In this example, it is impossible to mark all indices because index 1 isn't in changeIndices.\nHence, the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 2000
0 <= nums[i] <= 109
1 <= m == changeIndices.length <= 2000
1 <= changeIndices[i] <= n
You are given two 1-indexed integer arrays, nums
and, changeIndices
, having lengths n
and m
, respectively.
Initially, all indices in nums
are unmarked. Your task is to mark all indices in nums
.
In each second, s
, in order from 1
to m
(inclusive), you can perform one of the following operations:
i
in the range [1, n]
and decrement nums[i]
by 1
.nums[changeIndices[s]]
to any non-negative value.i
in the range [1, n]
, where nums[i]
is equal to 0
, and mark index i
.Return an integer denoting the earliest second in the range [1, m]
when all indices in nums
can be marked by choosing operations optimally, or -1
if it is impossible.
\n
Example 1:
\n\n\nInput: nums = [3,2,3], changeIndices = [1,3,2,2,2,2,3]\nOutput: 6\nExplanation: In this example, we have 7 seconds. The following operations can be performed to mark all indices:\nSecond 1: Set nums[changeIndices[1]] to 0. nums becomes [0,2,3].\nSecond 2: Set nums[changeIndices[2]] to 0. nums becomes [0,2,0].\nSecond 3: Set nums[changeIndices[3]] to 0. nums becomes [0,0,0].\nSecond 4: Mark index 1, since nums[1] is equal to 0.\nSecond 5: Mark index 2, since nums[2] is equal to 0.\nSecond 6: Mark index 3, since nums[3] is equal to 0.\nNow all indices have been marked.\nIt can be shown that it is not possible to mark all indices earlier than the 6th second.\nHence, the answer is 6.\n\n\n
Example 2:
\n\n\nInput: nums = [0,0,1,2], changeIndices = [1,2,1,2,1,2,1,2]\nOutput: 7\nExplanation: In this example, we have 8 seconds. The following operations can be performed to mark all indices:\nSecond 1: Mark index 1, since nums[1] is equal to 0.\nSecond 2: Mark index 2, since nums[2] is equal to 0.\nSecond 3: Decrement index 4 by one. nums becomes [0,0,1,1].\nSecond 4: Decrement index 4 by one. nums becomes [0,0,1,0].\nSecond 5: Decrement index 3 by one. nums becomes [0,0,0,0].\nSecond 6: Mark index 3, since nums[3] is equal to 0.\nSecond 7: Mark index 4, since nums[4] is equal to 0.\nNow all indices have been marked.\nIt can be shown that it is not possible to mark all indices earlier than the 7th second.\nHence, the answer is 7.\n\n\n
Example 3:
\n\n\nInput: nums = [1,2,3], changeIndices = [1,2,3]\nOutput: -1\nExplanation: In this example, it can be shown that it is impossible to mark all indices, as we don't have enough seconds. \nHence, the answer is -1.\n\n\n
\n
Constraints:
\n\n1 <= n == nums.length <= 5000
0 <= nums[i] <= 109
1 <= m == changeIndices.length <= 5000
1 <= changeIndices[i] <= n
You are given a 0-indexed integer array nums
, and an integer k
.
In one operation, you can remove one occurrence of the smallest element of nums
.
Return the minimum number of operations needed so that all elements of the array are greater than or equal to k
.
\n
Example 1:
\n\n\nInput: nums = [2,11,10,1,3], k = 10\nOutput: 3\nExplanation: After one operation, nums becomes equal to [2, 11, 10, 3].\nAfter two operations, nums becomes equal to [11, 10, 3].\nAfter three operations, nums becomes equal to [11, 10].\nAt this stage, all the elements of nums are greater than or equal to 10 so we can stop.\nIt can be shown that 3 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,2,4,9], k = 1\nOutput: 0\nExplanation: All elements of the array are greater than or equal to 1 so we do not need to apply any operations on nums.\n\n
Example 3:
\n\n\nInput: nums = [1,1,2,4,9], k = 9\nOutput: 4\nExplanation: only a single element of nums is greater than or equal to 9 so we need to apply the operations 4 times on nums.\n\n\n
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 109
1 <= k <= 109
i
such that nums[i] >= k
.You are given a 0-indexed integer array nums
, and an integer k
.
In one operation, you will:
\n\nx
and y
in nums
.x
and y
from nums
.min(x, y) * 2 + max(x, y)
anywhere in the array.Note that you can only apply the described operation if nums
contains at least two elements.
Return the minimum number of operations needed so that all elements of the array are greater than or equal to k
.
\n
Example 1:
\n\n\nInput: nums = [2,11,10,1,3], k = 10\nOutput: 2\nExplanation: In the first operation, we remove elements 1 and 2, then add 1 * 2 + 2 to nums. nums becomes equal to [4, 11, 10, 3].\nIn the second operation, we remove elements 3 and 4, then add 3 * 2 + 4 to nums. nums becomes equal to [10, 11, 10].\nAt this stage, all the elements of nums are greater than or equal to 10 so we can stop.\nIt can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.\n\n\n
Example 2:
\n\n\nInput: nums = [1,1,2,4,9], k = 20\nOutput: 4\nExplanation: After one operation, nums becomes equal to [2, 4, 9, 3].\nAfter two operations, nums becomes equal to [7, 4, 9].\nAfter three operations, nums becomes equal to [15, 9].\nAfter four operations, nums becomes equal to [33].\nAt this stage, all the elements of nums are greater than 20 so we can stop.\nIt can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.\n\n
\n
Constraints:
\n\n2 <= nums.length <= 2 * 105
1 <= nums[i] <= 109
1 <= k <= 109
k
.You are given a 0-indexed integer array nums
, and an integer k
.
You are allowed to perform some operations on nums
, where in a single operation, you can:
x
and y
from nums
.x
and y
from nums
.(min(x, y) * 2 + max(x, y))
at any position in the array.Note that you can only apply the described operation if nums
contains at least two elements.
Return the minimum number of operations needed so that all elements of the array are greater than or equal to k
.
\n
Example 1:
\n\nInput: nums = [2,11,10,1,3], k = 10
\n\nOutput: 2
\n\nExplanation:
\n\n1 * 2 + 2
to nums
. nums
becomes equal to [4, 11, 10, 3]
.3 * 2 + 4
to nums
. nums
becomes equal to [10, 11, 10]
.At this stage, all the elements of nums are greater than or equal to 10 so we can stop.
\n\nIt can be shown that 2 is the minimum number of operations needed so that all elements of the array are greater than or equal to 10.
\nExample 2:
\n\nInput: nums = [1,1,2,4,9], k = 20
\n\nOutput: 4
\n\nExplanation:
\n\nnums
becomes equal to [2, 4, 9, 3]
. nums
becomes equal to [7, 4, 9]
. nums
becomes equal to [15, 9]
. nums
becomes equal to [33]
.At this stage, all the elements of nums
are greater than 20 so we can stop.
It can be shown that 4 is the minimum number of operations needed so that all elements of the array are greater than or equal to 20.
\n\n
Constraints:
\n\n2 <= nums.length <= 2 * 105
1 <= nums[i] <= 109
1 <= k <= 109
k
.You are given an unrooted weighted tree with n
vertices representing servers numbered from 0
to n - 1
, an array edges
where edges[i] = [ai, bi, weighti]
represents a bidirectional edge between vertices ai
and bi
of weight weighti
. You are also given an integer signalSpeed
.
Two servers a
and b
are connectable through a server c
if:
a < b
, a != c
and b != c
.c
to a
is divisible by signalSpeed
.c
to b
is divisible by signalSpeed
.c
to b
and the path from c
to a
do not share any edges.Return an integer array count
of length n
where count[i]
is the number of server pairs that are connectable through the server i
.
\n
Example 1:
\n\nInput: edges = [[0,1,1],[1,2,5],[2,3,13],[3,4,9],[4,5,2]], signalSpeed = 1\nOutput: [0,4,6,6,4,0]\nExplanation: Since signalSpeed is 1, count[c] is equal to the number of pairs of paths that start at c and do not share any edges.\nIn the case of the given path graph, count[c] is equal to the number of servers to the left of c multiplied by the servers to the right of c.\n\n\n
Example 2:
\n\nInput: edges = [[0,6,3],[6,5,3],[0,3,1],[3,2,7],[3,1,6],[3,4,2]], signalSpeed = 3\nOutput: [2,0,0,0,0,0,2]\nExplanation: Through server 0, there are 2 pairs of connectable servers: (4, 5) and (4, 6).\nThrough server 6, there are 2 pairs of connectable servers: (4, 5) and (0, 5).\nIt can be shown that no two servers are connectable through servers other than 0 and 6.\n\n\n
\n
Constraints:
\n\n2 <= n <= 1000
edges.length == n - 1
edges[i].length == 3
0 <= ai, bi < n
edges[i] = [ai, bi, weighti]
1 <= weighti <= 106
1 <= signalSpeed <= 106
edges
represents a valid tree.There exists an undirected tree with n
nodes numbered 0
to n - 1
. You are given a 0-indexed 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the tree. You are also given a positive integer k
, and a 0-indexed array of non-negative integers nums
of length n
, where nums[i]
represents the value of the node numbered i
.
Alice wants the sum of values of tree nodes to be maximum, for which Alice can perform the following operation any number of times (including zero) on the tree:
\n\n[u, v]
connecting the nodes u
and v
, and update their values as follows:\n\n\tnums[u] = nums[u] XOR k
nums[v] = nums[v] XOR k
Return the maximum possible sum of the values Alice can achieve by performing the operation any number of times.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,1], k = 3, edges = [[0,1],[0,2]]\nOutput: 6\nExplanation: Alice can achieve the maximum sum of 6 using a single operation:\n- Choose the edge [0,2]. nums[0] and nums[2] become: 1 XOR 3 = 2, and the array nums becomes: [1,2,1] -> [2,2,2].\nThe total sum of values is 2 + 2 + 2 = 6.\nIt can be shown that 6 is the maximum achievable sum of values.\n\n\n
Example 2:
\n\nInput: nums = [2,3], k = 7, edges = [[0,1]]\nOutput: 9\nExplanation: Alice can achieve the maximum sum of 9 using a single operation:\n- Choose the edge [0,1]. nums[0] becomes: 2 XOR 7 = 5 and nums[1] become: 3 XOR 7 = 4, and the array nums becomes: [2,3] -> [5,4].\nThe total sum of values is 5 + 4 = 9.\nIt can be shown that 9 is the maximum achievable sum of values.\n\n\n
Example 3:
\n\nInput: nums = [7,7,7,7,7,7], k = 3, edges = [[0,1],[0,2],[0,3],[0,4],[0,5]]\nOutput: 42\nExplanation: The maximum achievable sum is 42 which can be achieved by Alice performing no operations.\n\n\n
\n
Constraints:
\n\n2 <= n == nums.length <= 2 * 104
1 <= k <= 109
0 <= nums[i] <= 109
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
edges
represent a valid tree.You are given a 1-indexed array of distinct integers nums
of length n
.
You need to distribute all the elements of nums
between two arrays arr1
and arr2
using n
operations. In the first operation, append nums[1]
to arr1
. In the second operation, append nums[2]
to arr2
. Afterwards, in the ith
operation:
arr1
is greater than the last element of arr2
, append nums[i]
to arr1
. Otherwise, append nums[i]
to arr2
.The array result
is formed by concatenating the arrays arr1
and arr2
. For example, if arr1 == [1,2,3]
and arr2 == [4,5,6]
, then result = [1,2,3,4,5,6]
.
Return the array result
.
\n
Example 1:
\n\n\nInput: nums = [2,1,3]\nOutput: [2,3,1]\nExplanation: After the first 2 operations, arr1 = [2] and arr2 = [1].\nIn the 3rd operation, as the last element of arr1 is greater than the last element of arr2 (2 > 1), append nums[3] to arr1.\nAfter 3 operations, arr1 = [2,3] and arr2 = [1].\nHence, the array result formed by concatenation is [2,3,1].\n\n\n
Example 2:
\n\n\nInput: nums = [5,4,3,8]\nOutput: [5,3,4,8]\nExplanation: After the first 2 operations, arr1 = [5] and arr2 = [4].\nIn the 3rd operation, as the last element of arr1 is greater than the last element of arr2 (5 > 4), append nums[3] to arr1, hence arr1 becomes [5,3].\nIn the 4th operation, as the last element of arr2 is greater than the last element of arr1 (4 > 3), append nums[4] to arr2, hence arr2 becomes [4,8].\nAfter 4 operations, arr1 = [5,3] and arr2 = [4,8].\nHence, the array result formed by concatenation is [5,3,4,8].\n\n\n
\n
Constraints:
\n\n3 <= n <= 50
1 <= nums[i] <= 100
nums
are distinct.You are given a 0-indexed integer matrix grid
and an integer k
.
Return the number of submatrices that contain the top-left element of the grid
, and have a sum less than or equal to k
.
\n
Example 1:
\n\nInput: grid = [[7,6,3],[6,6,1]], k = 18\nOutput: 4\nExplanation: There are only 4 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 18.\n\n
Example 2:
\n\nInput: grid = [[7,2,9],[1,5,0],[2,6,6]], k = 20\nOutput: 6\nExplanation: There are only 6 submatrices, shown in the image above, that contain the top-left element of grid, and have a sum less than or equal to 20.\n\n\n
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= n, m <= 1000
0 <= grid[i][j] <= 1000
1 <= k <= 109
You are given a 0-indexed n x n
grid where n
is odd, and grid[r][c]
is 0
, 1
, or 2
.
We say that a cell belongs to the Letter Y if it belongs to one of the following:
\n\nThe Letter Y is written on the grid if and only if:
\n\nReturn the minimum number of operations needed to write the letter Y on the grid given that in one operation you can change the value at any cell to 0
, 1
, or 2
.
\n
Example 1:
\n\nInput: grid = [[1,2,2],[1,1,0],[0,1,0]]\nOutput: 3\nExplanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 1 while those that do not belong to Y are equal to 0.\nIt can be shown that 3 is the minimum number of operations needed to write Y on the grid.\n\n\n
Example 2:
\n\nInput: grid = [[0,1,0,1,0],[2,1,0,1,2],[2,2,2,0,1],[2,2,2,2,2],[2,1,2,2,2]]\nOutput: 12\nExplanation: We can write Y on the grid by applying the changes highlighted in blue in the image above. After the operations, all cells that belong to Y, denoted in bold, have the same value of 0 while those that do not belong to Y are equal to 2. \nIt can be shown that 12 is the minimum number of operations needed to write Y on the grid.\n\n
\n
Constraints:
\n\n3 <= n <= 49
n == grid.length == grid[i].length
0 <= grid[i][j] <= 2
n
is odd.You are given a 1-indexed array of integers nums
of length n
.
We define a function greaterCount
such that greaterCount(arr, val)
returns the number of elements in arr
that are strictly greater than val
.
You need to distribute all the elements of nums
between two arrays arr1
and arr2
using n
operations. In the first operation, append nums[1]
to arr1
. In the second operation, append nums[2]
to arr2
. Afterwards, in the ith
operation:
greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])
, append nums[i]
to arr1
.greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])
, append nums[i]
to arr2
.greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])
, append nums[i]
to the array with a lesser number of elements.nums[i]
to arr1
.The array result
is formed by concatenating the arrays arr1
and arr2
. For example, if arr1 == [1,2,3]
and arr2 == [4,5,6]
, then result = [1,2,3,4,5,6]
.
Return the integer array result
.
\n
Example 1:
\n\n\nInput: nums = [2,1,3,3]\nOutput: [2,3,1,3]\nExplanation: After the first 2 operations, arr1 = [2] and arr2 = [1].\nIn the 3rd operation, the number of elements greater than 3 is zero in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.\nIn the 4th operation, the number of elements greater than 3 is zero in both arrays. As the length of arr2 is lesser, hence, append nums[4] to arr2.\nAfter 4 operations, arr1 = [2,3] and arr2 = [1,3].\nHence, the array result formed by concatenation is [2,3,1,3].\n\n\n
Example 2:
\n\n\nInput: nums = [5,14,3,1,2]\nOutput: [5,3,1,2,14]\nExplanation: After the first 2 operations, arr1 = [5] and arr2 = [14].\nIn the 3rd operation, the number of elements greater than 3 is one in both arrays. Also, the lengths are equal, hence, append nums[3] to arr1.\nIn the 4th operation, the number of elements greater than 1 is greater in arr1 than arr2 (2 > 1). Hence, append nums[4] to arr1.\nIn the 5th operation, the number of elements greater than 2 is greater in arr1 than arr2 (2 > 1). Hence, append nums[5] to arr1.\nAfter 5 operations, arr1 = [5,3,1,2] and arr2 = [14].\nHence, the array result formed by concatenation is [5,3,1,2,14].\n\n\n
Example 3:
\n\n\nInput: nums = [3,3,3,3]\nOutput: [3,3,3,3]\nExplanation: At the end of 4 operations, arr1 = [3,3] and arr2 = [3,3].\nHence, the array result formed by concatenation is [3,3,3,3].\n\n\n
\n
Constraints:
\n\n3 <= n <= 105
1 <= nums[i] <= 109
You are given an array apple
of size n
and an array capacity
of size m
.
There are n
packs where the ith
pack contains apple[i]
apples. There are m
boxes as well, and the ith
box has a capacity of capacity[i]
apples.
Return the minimum number of boxes you need to select to redistribute these n
packs of apples into boxes.
Note that, apples from the same pack can be distributed into different boxes.
\n\n\n
Example 1:
\n\n\nInput: apple = [1,3,2], capacity = [4,3,1,5,2]\nOutput: 2\nExplanation: We will use boxes with capacities 4 and 5.\nIt is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.\n\n\n
Example 2:
\n\n\nInput: apple = [5,5,5], capacity = [2,4,2,7]\nOutput: 4\nExplanation: We will need to use all the boxes.\n\n\n
\n
Constraints:
\n\n1 <= n == apple.length <= 50
1 <= m == capacity.length <= 50
1 <= apple[i], capacity[i] <= 50
You are given an array happiness
of length n
, and a positive integer k
.
There are n
children standing in a queue, where the ith
child has happiness value happiness[i]
. You want to select k
children from these n
children in k
turns.
In each turn, when you select a child, the happiness value of all the children that have not been selected till now decreases by 1
. Note that the happiness value cannot become negative and gets decremented only if it is positive.
Return the maximum sum of the happiness values of the selected children you can achieve by selecting k
children.
\n
Example 1:
\n\n\nInput: happiness = [1,2,3], k = 2\nOutput: 4\nExplanation: We can pick 2 children in the following way:\n- Pick the child with the happiness value == 3. The happiness value of the remaining children becomes [0,1].\n- Pick the child with the happiness value == 1. The happiness value of the remaining child becomes [0]. Note that the happiness value cannot become less than 0.\nThe sum of the happiness values of the selected children is 3 + 1 = 4.\n\n\n
Example 2:
\n\n\nInput: happiness = [1,1,1,1], k = 2\nOutput: 1\nExplanation: We can pick 2 children in the following way:\n- Pick any child with the happiness value == 1. The happiness value of the remaining children becomes [0,0,0].\n- Pick the child with the happiness value == 0. The happiness value of the remaining child becomes [0,0].\nThe sum of the happiness values of the selected children is 1 + 0 = 1.\n\n\n
Example 3:
\n\n\nInput: happiness = [2,3,4,5], k = 1\nOutput: 5\nExplanation: We can pick 1 child in the following way:\n- Pick the child with the happiness value == 5. The happiness value of the remaining children becomes [1,2,3].\nThe sum of the happiness values of the selected children is 5.\n\n\n
\n
Constraints:
\n\n1 <= n == happiness.length <= 2 * 105
1 <= happiness[i] <= 108
1 <= k <= n
You are given an array arr
of size n
consisting of non-empty strings.
Find a string array answer
of size n
such that:
answer[i]
is the shortest substring of arr[i]
that does not occur as a substring in any other string in arr
. If multiple such substrings exist, answer[i]
should be the lexicographically smallest. And if no such substring exists, answer[i]
should be an empty string.Return the array answer
.
\n
Example 1:
\n\n\nInput: arr = ["cab","ad","bad","c"]\nOutput: ["ab","","ba",""]\nExplanation: We have the following:\n- For the string "cab", the shortest substring that does not occur in any other string is either "ca" or "ab", we choose the lexicographically smaller substring, which is "ab".\n- For the string "ad", there is no substring that does not occur in any other string.\n- For the string "bad", the shortest substring that does not occur in any other string is "ba".\n- For the string "c", there is no substring that does not occur in any other string.\n\n\n
Example 2:
\n\n\nInput: arr = ["abc","bcd","abcd"]\nOutput: ["","","abcd"]\nExplanation: We have the following:\n- For the string "abc", there is no substring that does not occur in any other string.\n- For the string "bcd", there is no substring that does not occur in any other string.\n- For the string "abcd", the shortest substring that does not occur in any other string is "abcd".\n\n\n
\n
Constraints:
\n\nn == arr.length
2 <= n <= 100
1 <= arr[i].length <= 20
arr[i]
consists only of lowercase English letters.You are given an array of integers nums
with length n
, and a positive odd integer k
.
Select exactly k
disjoint subarrays sub1, sub2, ..., subk
from nums
such that the last element of subi
appears before the first element of sub{i+1}
for all 1 <= i <= k-1
. The goal is to maximize their combined strength.
The strength of the selected subarrays is defined as:
\n\nstrength = k * sum(sub1)- (k - 1) * sum(sub2) + (k - 2) * sum(sub3) - ... - 2 * sum(sub{k-1}) + sum(subk)
where sum(subi)
is the sum of the elements in the i
-th subarray.
Return the maximum possible strength that can be obtained from selecting exactly k
disjoint subarrays from nums
.
Note that the chosen subarrays don't need to cover the entire array.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,-1,2], k = 3
\n\nOutput: 22
\n\nExplanation:
\n\nThe best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:
\n\nstrength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22
\n\n
Example 2:
\n\nInput: nums = [12,-2,-2,-2,-2], k = 5
\n\nOutput: 64
\n\nExplanation:
\n\nThe only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:
\n\nstrength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64
Example 3:
\n\nInput: nums = [-1,-2,-3], k = 1
\n\nOutput: -1
\n\nExplanation:
\n\nThe best possible way to select 1 subarray is: nums[0..0]. The strength is -1.
\n\n\n
Constraints:
\n\n1 <= n <= 104
-109 <= nums[i] <= 109
1 <= k <= n
1 <= n * k <= 106
k
is odd.You are given an integer array nums
containing positive integers. We define a function encrypt
such that encrypt(x)
replaces every digit in x
with the largest digit in x
. For example, encrypt(523) = 555
and encrypt(213) = 333
.
Return the sum of encrypted elements.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3]
\n\nOutput: 6
\n\nExplanation: The encrypted elements are [1,2,3]
. The sum of encrypted elements is 1 + 2 + 3 == 6
.
Example 2:
\n\nInput: nums = [10,21,31]
\n\nOutput: 66
\n\nExplanation: The encrypted elements are [11,22,33]
. The sum of encrypted elements is 11 + 22 + 33 == 66
.
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 1000
You are given a 0-indexed array nums
of size n
consisting of positive integers.
You are also given a 2D array queries
of size m
where queries[i] = [indexi, ki]
.
Initially all elements of the array are unmarked.
\n\nYou need to apply m
queries on the array in order, where on the ith
query you do the following:
indexi
if it is not already marked.ki
unmarked elements in the array with the smallest values. If multiple such elements exist, mark the ones with the smallest indices. And if less than ki
unmarked elements exist, then mark all of them.Return an array answer of size m
where answer[i]
is the sum of unmarked elements in the array after the ith
query.
\n
Example 1:
\n\nInput: nums = [1,2,2,1,2,3,1], queries = [[1,2],[3,3],[4,2]]
\n\nOutput: [8,3,0]
\n\nExplanation:
\n\nWe do the following queries on the array:
\n\n1
, and 2
of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]
. The sum of unmarked elements is 2 + 2 + 3 + 1 = 8
.3
, since it is already marked we skip it. Then we mark 3
of the smallest unmarked elements with the smallest indices, the marked elements now are nums = [1,2,2,1,2,3,1]
. The sum of unmarked elements is 3
.4
, since it is already marked we skip it. Then we mark 2
of the smallest unmarked elements with the smallest indices if they exist, the marked elements now are nums = [1,2,2,1,2,3,1]
. The sum of unmarked elements is 0
.Example 2:
\n\nInput: nums = [1,4,2,3], queries = [[0,1]]
\n\nOutput: [7]
\n\nExplanation: We do one query which is mark the element at index 0
and mark the smallest element among unmarked elements. The marked elements will be nums = [1,4,2,3]
, and the sum of unmarked elements is 4 + 3 = 7
.
\n
Constraints:
\n\nn == nums.length
m == queries.length
1 <= m <= n <= 105
1 <= nums[i] <= 105
queries[i].length == 2
0 <= indexi, ki <= n - 1
You are given a string s
. s[i]
is either a lowercase English letter or '?'
.
For a string t
having length m
containing only lowercase English letters, we define the function cost(i)
for an index i
as the number of characters equal to t[i]
that appeared before it, i.e. in the range [0, i - 1]
.
The value of t
is the sum of cost(i)
for all indices i
.
For example, for the string t = "aab"
:
cost(0) = 0
cost(1) = 1
cost(2) = 0
"aab"
is 0 + 1 + 0 = 1
.Your task is to replace all occurrences of '?'
in s
with any lowercase English letter so that the value of s
is minimized.
Return a string denoting the modified string with replaced occurrences of '?'
. If there are multiple strings resulting in the minimum value, return the lexicographically smallest one.
\n
Example 1:
\n\nInput: s = "???"
\n\nOutput: "abc"
\n\nExplanation: In this example, we can replace the occurrences of '?'
to make s
equal to "abc"
.
For "abc"
, cost(0) = 0
, cost(1) = 0
, and cost(2) = 0
.
The value of "abc"
is 0
.
Some other modifications of s
that have a value of 0
are "cba"
, "abz"
, and, "hey"
.
Among all of them, we choose the lexicographically smallest.
\nExample 2:
\n\nInput: s = "a?a?"
\n\nOutput: "abac"
\n\nExplanation: In this example, the occurrences of '?'
can be replaced to make s
equal to "abac"
.
For "abac"
, cost(0) = 0
, cost(1) = 0
, cost(2) = 1
, and cost(3) = 0
.
The value of "abac"
is 1
.
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either a lowercase English letter or '?'
.You are given an integer array nums
of length n
and a positive integer k
.
The power of an array of integers is defined as the number of subsequences with their sum equal to k
.
Return the sum of power of all subsequences of nums
.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [1,2,3], k = 3
\n\nOutput: 6
\n\nExplanation:
\n\nThere are 5
subsequences of nums with non-zero power:
[1,2,3]
has 2
subsequences with sum == 3
: [1,2,3]
and [1,2,3]
.[1,2,3]
has 1
subsequence with sum == 3
: [1,2,3]
.[1,2,3]
has 1
subsequence with sum == 3
: [1,2,3]
.[1,2,3]
has 1
subsequence with sum == 3
: [1,2,3]
.[1,2,3]
has 1
subsequence with sum == 3
: [1,2,3]
.Hence the answer is 2 + 1 + 1 + 1 + 1 = 6
.
Example 2:
\n\nInput: nums = [2,3,3], k = 5
\n\nOutput: 4
\n\nExplanation:
\n\nThere are 3
subsequences of nums with non-zero power:
[2,3,3]
has 2 subsequences with sum == 5
: [2,3,3]
and [2,3,3]
.[2,3,3]
has 1 subsequence with sum == 5
: [2,3,3]
.[2,3,3]
has 1 subsequence with sum == 5
: [2,3,3]
.Hence the answer is 2 + 1 + 1 = 4
.
Example 3:
\n\nInput: nums = [1,2,3], k = 7
\n\nOutput: 0
\n\nExplanation: There exists no subsequence with sum 7
. Hence all subsequences of nums have power = 0
.
\n
Constraints:
\n\n1 <= n <= 100
1 <= nums[i] <= 104
1 <= k <= 100
Given a string s
, find any substring of length 2
which is also present in the reverse of s
.
Return true
if such a substring exists, and false
otherwise.
\n
Example 1:
\n\nInput: s = "leetcode"
\n\nOutput: true
\n\nExplanation: Substring "ee"
is of length 2
which is also present in reverse(s) == "edocteel"
.
Example 2:
\n\nInput: s = "abcba"
\n\nOutput: true
\n\nExplanation: All of the substrings of length 2
"ab"
, "bc"
, "cb"
, "ba"
are also present in reverse(s) == "abcba"
.
Example 3:
\n\nInput: s = "abcd"
\n\nOutput: false
\n\nExplanation: There is no substring of length 2
in s
, which is also present in the reverse of s
.
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of lowercase English letters.You are given a string s
and a character c
. Return the total number of substrings of s
that start and end with c
.
\n
Example 1:
\n\nInput: s = "abada", c = "a"
\n\nOutput: 6
\n\nExplanation: Substrings starting and ending with "a"
are: "abada"
, "abada"
, "abada"
, "abada"
, "abada"
, "abada"
.
Example 2:
\n\nInput: s = "zzz", c = "z"
\n\nOutput: 6
\n\nExplanation: There are a total of 6
substrings in s
and all start and end with "z"
.
\n
Constraints:
\n\n1 <= s.length <= 105
s
and c
consist only of lowercase English letters.You are given a string word
and an integer k
.
We consider word
to be k-special if |freq(word[i]) - freq(word[j])| <= k
for all indices i
and j
in the string.
Here, freq(x)
denotes the frequency of the character x
in word
, and |y|
denotes the absolute value of y
.
Return the minimum number of characters you need to delete to make word
k-special.
\n
Example 1:
\n\nInput: word = "aabcaba", k = 0
\n\nOutput: 3
\n\nExplanation: We can make word
0
-special by deleting 2
occurrences of "a"
and 1
occurrence of "c"
. Therefore, word
becomes equal to "baba"
where freq('a') == freq('b') == 2
.
Example 2:
\n\nInput: word = "dabdcbdcdcd", k = 2
\n\nOutput: 2
\n\nExplanation: We can make word
2
-special by deleting 1
occurrence of "a"
and 1
occurrence of "d"
. Therefore, word
becomes equal to "bdcbdcdcd" where freq('b') == 2
, freq('c') == 3
, and freq('d') == 4
.
Example 3:
\n\nInput: word = "aaabaaa", k = 2
\n\nOutput: 1
\n\nExplanation: We can make word
2
-special by deleting 1
occurrence of "b"
. Therefore, word
becomes equal to "aaaaaa"
where each letter's frequency is now uniformly 6
.
\n
Constraints:
\n\n1 <= word.length <= 105
0 <= k <= 105
word
consists only of lowercase English letters.You are given a binary array nums
of length n
, a positive integer k
and a non-negative integer maxChanges
.
Alice plays a game, where the goal is for Alice to pick up k
ones from nums
using the minimum number of moves. When the game starts, Alice picks up any index aliceIndex
in the range [0, n - 1]
and stands there. If nums[aliceIndex] == 1
, Alice picks up the one and nums[aliceIndex]
becomes 0
(this does not count as a move). After this, Alice can make any number of moves (including zero) where in each move Alice must perform exactly one of the following actions:
j != aliceIndex
such that nums[j] == 0
and set nums[j] = 1
. This action can be performed at most maxChanges
times.x
and y
(|x - y| == 1
) such that nums[x] == 1
, nums[y] == 0
, then swap their values (set nums[y] = 1
and nums[x] = 0
). If y == aliceIndex
, Alice picks up the one after this move and nums[y]
becomes 0
.Return the minimum number of moves required by Alice to pick exactly k
ones.
\n
Example 1:
\n\nInput: nums = [1,1,0,0,0,1,1,0,0,1], k = 3, maxChanges = 1
\n\nOutput: 3
\n\nExplanation: Alice can pick up 3
ones in 3
moves, if Alice performs the following actions in each move when standing at aliceIndex == 1
:
nums[1]
becomes 0
. nums
becomes [1,0,0,0,0,1,1,0,0,1]
.j == 2
and perform an action of the first type. nums
becomes [1,0,1,0,0,1,1,0,0,1]
x == 2
and y == 1
, and perform an action of the second type. nums
becomes [1,1,0,0,0,1,1,0,0,1]
. As y == aliceIndex
, Alice picks up the one and nums
becomes [1,0,0,0,0,1,1,0,0,1]
.x == 0
and y == 1
, and perform an action of the second type. nums
becomes [0,1,0,0,0,1,1,0,0,1]
. As y == aliceIndex
, Alice picks up the one and nums
becomes [0,0,0,0,0,1,1,0,0,1]
.Note that it may be possible for Alice to pick up 3
ones using some other sequence of 3
moves.
Example 2:
\n\nInput: nums = [0,0,0,0], k = 2, maxChanges = 3
\n\nOutput: 4
\n\nExplanation: Alice can pick up 2
ones in 4
moves, if Alice performs the following actions in each move when standing at aliceIndex == 0
:
j == 1
and perform an action of the first type. nums
becomes [0,1,0,0]
.x == 1
and y == 0
, and perform an action of the second type. nums
becomes [1,0,0,0]
. As y == aliceIndex
, Alice picks up the one and nums
becomes [0,0,0,0]
.j == 1
again and perform an action of the first type. nums
becomes [0,1,0,0]
.x == 1
and y == 0
again, and perform an action of the second type. nums
becomes [1,0,0,0]
. As y == aliceIndex
, Alice picks up the one and nums
becomes [0,0,0,0]
.\n
Constraints:
\n\n2 <= n <= 105
0 <= nums[i] <= 1
1 <= k <= 105
0 <= maxChanges <= 105
maxChanges + sum(nums) >= k
s
, return the maximum length of a substring such that it contains at most two occurrences of each character.\n\n
Example 1:
\n\nInput: s = "bcbbbcba"
\n\nOutput: 4
\n\nExplanation:
\nThe following substring has a length of 4 and contains at most two occurrences of each character:"bcbbbcba"
.Example 2:
\n\nInput: s = "aaaa"
\n\nOutput: 2
\n\nExplanation:
\nThe following substring has a length of 2 and contains at most two occurrences of each character:"aaaa"
.\n
Constraints:
\n\n2 <= s.length <= 100
s
consists only of lowercase English letters.You are given a positive integer k
. Initially, you have an array nums = [1]
.
You can perform any of the following operations on the array any number of times (possibly zero):
\n\n1
.Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k
.
\n
Example 1:
\n\nInput: k = 11
\n\nOutput: 5
\n\nExplanation:
\n\nWe can do the following operations on the array nums = [1]
:
1
three times. The resulting array is nums = [4]
.nums = [4,4,4]
.The sum of the final array is 4 + 4 + 4 = 12
which is greater than or equal to k = 11
.
\nThe total number of operations performed is 3 + 2 = 5
.
Example 2:
\n\nInput: k = 1
\n\nOutput: 0
\n\nExplanation:
\n\nThe sum of the original array is already greater than or equal to 1
, so no operations are needed.
\n
Constraints:
\n\n1 <= k <= 105
The problem involves tracking the frequency of IDs in a collection that changes over time. You have two integer arrays, nums
and freq
, of equal length n
. Each element in nums
represents an ID, and the corresponding element in freq
indicates how many times that ID should be added to or removed from the collection at each step.
freq[i]
is positive, it means freq[i]
IDs with the value nums[i]
are added to the collection at step i
.freq[i]
is negative, it means -freq[i]
IDs with the value nums[i]
are removed from the collection at step i
.Return an array ans
of length n
, where ans[i]
represents the count of the most frequent ID in the collection after the ith
step. If the collection is empty at any step, ans[i]
should be 0 for that step.
\n
Example 1:
\n\nInput: nums = [2,3,2,1], freq = [3,2,-3,1]
\n\nOutput: [3,3,2,2]
\n\nExplanation:
\n\nAfter step 0, we have 3 IDs with the value of 2. So ans[0] = 3
.
\nAfter step 1, we have 3 IDs with the value of 2 and 2 IDs with the value of 3. So ans[1] = 3
.
\nAfter step 2, we have 2 IDs with the value of 3. So ans[2] = 2
.
\nAfter step 3, we have 2 IDs with the value of 3 and 1 ID with the value of 1. So ans[3] = 2
.
Example 2:
\n\nInput: nums = [5,5,3], freq = [2,-2,1]
\n\nOutput: [2,0,1]
\n\nExplanation:
\n\nAfter step 0, we have 2 IDs with the value of 5. So ans[0] = 2
.
\nAfter step 1, there are no IDs. So ans[1] = 0
.
\nAfter step 2, we have 1 ID with the value of 3. So ans[2] = 1
.
\n
Constraints:
\n\n1 <= nums.length == freq.length <= 105
1 <= nums[i] <= 105
-105 <= freq[i] <= 105
freq[i] != 0
You are given two arrays of strings wordsContainer
and wordsQuery
.
For each wordsQuery[i]
, you need to find a string from wordsContainer
that has the longest common suffix with wordsQuery[i]
. If there are two or more strings in wordsContainer
that share the longest common suffix, find the string that is the smallest in length. If there are two or more such strings that have the same smallest length, find the one that occurred earlier in wordsContainer
.
Return an array of integers ans
, where ans[i]
is the index of the string in wordsContainer
that has the longest common suffix with wordsQuery[i]
.
\n
Example 1:
\n\nInput: wordsContainer = ["abcd","bcd","xbcd"], wordsQuery = ["cd","bcd","xyz"]
\n\nOutput: [1,1,1]
\n\nExplanation:
\n\nLet's look at each wordsQuery[i]
separately:
wordsQuery[0] = "cd"
, strings from wordsContainer
that share the longest common suffix "cd"
are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.wordsQuery[1] = "bcd"
, strings from wordsContainer
that share the longest common suffix "bcd"
are at indices 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.wordsQuery[2] = "xyz"
, there is no string from wordsContainer
that shares a common suffix. Hence the longest common suffix is ""
, that is shared with strings at index 0, 1, and 2. Among these, the answer is the string at index 1 because it has the shortest length of 3.Example 2:
\n\nInput: wordsContainer = ["abcdefgh","poiuygh","ghghgh"], wordsQuery = ["gh","acbfgh","acbfegh"]
\n\nOutput: [2,0,2]
\n\nExplanation:
\n\nLet's look at each wordsQuery[i]
separately:
wordsQuery[0] = "gh"
, strings from wordsContainer
that share the longest common suffix "gh"
are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.wordsQuery[1] = "acbfgh"
, only the string at index 0 shares the longest common suffix "fgh"
. Hence it is the answer, even though the string at index 2 is shorter.wordsQuery[2] = "acbfegh"
, strings from wordsContainer
that share the longest common suffix "gh"
are at indices 0, 1, and 2. Among these, the answer is the string at index 2 because it has the shortest length of 6.\n
Constraints:
\n\n1 <= wordsContainer.length, wordsQuery.length <= 104
1 <= wordsContainer[i].length <= 5 * 103
1 <= wordsQuery[i].length <= 5 * 103
wordsContainer[i]
consists only of lowercase English letters.wordsQuery[i]
consists only of lowercase English letters.wordsContainer[i].length
is at most 5 * 105
.wordsQuery[i].length
is at most 5 * 105
.You are given an array nums
of non-negative integers and an integer k
.
An array is called special if the bitwise OR
of all of its elements is at least k
.
Return the length of the shortest special non-empty subarray of nums
, or return -1
if no special subarray exists.
\n
Example 1:
\n\nInput: nums = [1,2,3], k = 2
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarray [3]
has OR
value of 3
. Hence, we return 1
.
Note that [2]
is also a special subarray.
Example 2:
\n\nInput: nums = [2,1,8], k = 10
\n\nOutput: 3
\n\nExplanation:
\n\nThe subarray [2,1,8]
has OR
value of 11
. Hence, we return 3
.
Example 3:
\n\nInput: nums = [1,2], k = 0
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarray [1]
has OR
value of 1
. Hence, we return 1
.
\n
Constraints:
\n\n1 <= nums.length <= 50
0 <= nums[i] <= 50
0 <= k < 64
You are given a binary array possible
of length n
.
Alice and Bob are playing a game that consists of n
levels. Some of the levels in the game are impossible to clear while others can always be cleared. In particular, if possible[i] == 0
, then the ith
level is impossible to clear for both the players. A player gains 1
point on clearing a level and loses 1
point if the player fails to clear it.
At the start of the game, Alice will play some levels in the given order starting from the 0th
level, after which Bob will play for the rest of the levels.
Alice wants to know the minimum number of levels she should play to gain more points than Bob, if both players play optimally to maximize their points.
\n\nReturn the minimum number of levels Alice should play to gain more points. If this is not possible, return -1
.
Note that each player must play at least 1
level.
\n
Example 1:
\n\nInput: possible = [1,0,1,0]
\n\nOutput: 1
\n\nExplanation:
\n\nLet's look at all the levels that Alice can play up to:
\n\nAlice must play a minimum of 1 level to gain more points.
\nExample 2:
\n\nInput: possible = [1,1,1,1,1]
\n\nOutput: 3
\n\nExplanation:
\n\nLet's look at all the levels that Alice can play up to:
\n\nAlice must play a minimum of 3 levels to gain more points.
\nExample 3:
\n\nInput: possible = [0,0]
\n\nOutput: -1
\n\nExplanation:
\n\nThe only possible way is for both players to play 1 level each. Alice plays level 0 and loses 1 point. Bob plays level 1 and loses 1 point. As both players have equal points, Alice can't gain more points than Bob.
\n\n
Constraints:
\n\n2 <= n == possible.length <= 105
possible[i]
is either 0
or 1
.You are given an array nums
of non-negative integers and an integer k
.
An array is called special if the bitwise OR
of all of its elements is at least k
.
Return the length of the shortest special non-empty subarray of nums
, or return -1
if no special subarray exists.
\n
Example 1:
\n\nInput: nums = [1,2,3], k = 2
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarray [3]
has OR
value of 3
. Hence, we return 1
.
Example 2:
\n\nInput: nums = [2,1,8], k = 10
\n\nOutput: 3
\n\nExplanation:
\n\nThe subarray [2,1,8]
has OR
value of 11
. Hence, we return 3
.
Example 3:
\n\nInput: nums = [1,2], k = 0
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarray [1]
has OR
value of 1
. Hence, we return 1
.
\n
Constraints:
\n\n1 <= nums.length <= 2 * 105
0 <= nums[i] <= 109
0 <= k <= 109
You are given an integer array nums
of length n
, and a positive integer k
.
The power of a subsequence is defined as the minimum absolute difference between any two elements in the subsequence.
\n\nReturn the sum of powers of all subsequences of nums
which have length equal to k
.
Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4], k = 3
\n\nOutput: 4
\n\nExplanation:
\n\nThere are 4 subsequences in nums
which have length 3: [1,2,3]
, [1,3,4]
, [1,2,4]
, and [2,3,4]
. The sum of powers is |2 - 3| + |3 - 4| + |2 - 1| + |3 - 4| = 4
.
Example 2:
\n\nInput: nums = [2,2], k = 2
\n\nOutput: 0
\n\nExplanation:
\n\nThe only subsequence in nums
which has length 2 is [2,2]
. The sum of powers is |2 - 2| = 0
.
Example 3:
\n\nInput: nums = [4,3,-1], k = 2
\n\nOutput: 10
\n\nExplanation:
\n\nThere are 3 subsequences in nums
which have length 2: [4,3]
, [4,-1]
, and [3,-1]
. The sum of powers is |4 - 3| + |4 - (-1)| + |3 - (-1)| = 10
.
\n
Constraints:
\n\n2 <= n == nums.length <= 50
-108 <= nums[i] <= 108
2 <= k <= n
An integer divisible by the sum of its digits is said to be a Harshad number. You are given an integer x
. Return the sum of the digits of x
if x
is a Harshad number, otherwise, return -1
.
\n
Example 1:
\n\nInput: x = 18
\n\nOutput: 9
\n\nExplanation:
\n\nThe sum of digits of x
is 9
. 18
is divisible by 9
. So 18
is a Harshad number and the answer is 9
.
Example 2:
\n\nInput: x = 23
\n\nOutput: -1
\n\nExplanation:
\n\nThe sum of digits of x
is 5
. 23
is not divisible by 5
. So 23
is not a Harshad number and the answer is -1
.
\n
Constraints:
\n\n1 <= x <= 100
You are given two integers numBottles
and numExchange
.
numBottles
represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:
numExchange
empty bottles with one full water bottle. Then, increase numExchange
by one.Note that you cannot exchange multiple batches of empty bottles for the same value of numExchange
. For example, if numBottles == 3
and numExchange == 1
, you cannot exchange 3
empty water bottles for 3
full bottles.
Return the maximum number of water bottles you can drink.
\n\n\n
Example 1:
\n\nInput: numBottles = 13, numExchange = 6\nOutput: 15\nExplanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.\n\n\n
Example 2:
\n\nInput: numBottles = 10, numExchange = 3\nOutput: 13\nExplanation: The table above shows the number of full water bottles, empty water bottles, the value of numExchange, and the number of bottles drunk.\n\n\n
\n
Constraints:
\n\n1 <= numBottles <= 100
1 <= numExchange <= 100
You are given a binary array nums
.
We call a subarray alternating if no two adjacent elements in the subarray have the same value.
\n\nReturn the number of alternating subarrays in nums
.
\n
Example 1:
\n\nInput: nums = [0,1,1,1]
\n\nOutput: 5
\n\nExplanation:
\n\nThe following subarrays are alternating: [0]
, [1]
, [1]
, [1]
, and [0,1]
.
Example 2:
\n\nInput: nums = [1,0,1,0]
\n\nOutput: 10
\n\nExplanation:
\n\nEvery subarray of the array is alternating. There are 10 possible subarrays that we can choose.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
nums[i]
is either 0
or 1
.You are given an array points
representing integer coordinates of some points on a 2D plane, where points[i] = [xi, yi]
.
The distance between two points is defined as their Manhattan distance.
\n\nReturn the minimum possible value for maximum distance between any two points by removing exactly one point.
\n\n\n
Example 1:
\n\nInput: points = [[3,10],[5,15],[10,2],[4,4]]
\n\nOutput: 12
\n\nExplanation:
\n\nThe maximum distance after removing each point is the following:
\n\n|5 - 10| + |15 - 2| = 18
.|3 - 10| + |10 - 2| = 15
.|5 - 4| + |15 - 4| = 12
.|5 - 10| + |15 - 2| = 18
.12 is the minimum possible maximum distance between any two points after removing exactly one point.
\nExample 2:
\n\nInput: points = [[1,1],[1,1],[1,1]]
\n\nOutput: 0
\n\nExplanation:
\n\nRemoving any of the points results in the maximum distance between any two points of 0.
\n\n
Constraints:
\n\n3 <= points.length <= 105
points[i].length == 2
1 <= points[i][0], points[i][1] <= 108
You are given an array of integers nums
. Return the length of the longest subarray of nums
which is either strictly increasing or strictly decreasing.
\n
Example 1:
\n\nInput: nums = [1,4,3,3,2]
\n\nOutput: 2
\n\nExplanation:
\n\nThe strictly increasing subarrays of nums
are [1]
, [2]
, [3]
, [3]
, [4]
, and [1,4]
.
The strictly decreasing subarrays of nums
are [1]
, [2]
, [3]
, [3]
, [4]
, [3,2]
, and [4,3]
.
Hence, we return 2
.
Example 2:
\n\nInput: nums = [3,3,3,3]
\n\nOutput: 1
\n\nExplanation:
\n\nThe strictly increasing subarrays of nums
are [3]
, [3]
, [3]
, and [3]
.
The strictly decreasing subarrays of nums
are [3]
, [3]
, [3]
, and [3]
.
Hence, we return 1
.
Example 3:
\n\nInput: nums = [3,2,1]
\n\nOutput: 3
\n\nExplanation:
\n\nThe strictly increasing subarrays of nums
are [3]
, [2]
, and [1]
.
The strictly decreasing subarrays of nums
are [3]
, [2]
, [1]
, [3,2]
, [2,1]
, and [3,2,1]
.
Hence, we return 3
.
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 50
You are given a string s
and an integer k
.
Define a function distance(s1, s2)
between two strings s1
and s2
of the same length n
as:
s1[i]
and s2[i]
when the characters from 'a'
to 'z'
are placed in a cyclic order, for all i
in the range [0, n - 1]
.For example, distance("ab", "cd") == 4
, and distance("a", "z") == 1
.
You can change any letter of s
to any other lowercase English letter, any number of times.
Return a string denoting the lexicographically smallest string t
you can get after some changes, such that distance(s, t) <= k
.
\n
Example 1:
\n\nInput: s = "zbbz", k = 3
\n\nOutput: "aaaz"
\n\nExplanation:
\n\nChange s
to "aaaz"
. The distance between "zbbz"
and "aaaz"
is equal to k = 3
.
Example 2:
\n\nInput: s = "xaxcd", k = 4
\n\nOutput: "aawcd"
\n\nExplanation:
\n\nThe distance between "xaxcd" and "aawcd" is equal to k = 4.
\nExample 3:
\n\nInput: s = "lol", k = 0
\n\nOutput: "lol"
\n\nExplanation:
\n\nIt's impossible to change any character as k = 0
.
\n
Constraints:
\n\n1 <= s.length <= 100
0 <= k <= 2000
s
consists only of lowercase English letters.You are given an integer array nums
and a non-negative integer k
. In one operation, you can increase or decrease any element by 1.
Return the minimum number of operations needed to make the median of nums
equal to k
.
The median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the larger of the two values is taken.
\n\n\n
Example 1:
\n\nInput: nums = [2,5,6,8,5], k = 4
\n\nOutput: 2
\n\nExplanation:
\n\nWe can subtract one from nums[1]
and nums[4]
to obtain [2, 4, 6, 8, 4]
. The median of the resulting array is equal to k
.
Example 2:
\n\nInput: nums = [2,5,6,8,5], k = 7
\n\nOutput: 3
\n\nExplanation:
\n\nWe can add one to nums[1]
twice and add one to nums[2]
once to obtain [2, 7, 7, 8, 5]
.
Example 3:
\n\nInput: nums = [1,2,3,4,5,6], k = 4
\n\nOutput: 0
\n\nExplanation:
\n\nThe median of the array is already equal to k
.
\n
Constraints:
\n\n1 <= nums.length <= 2 * 105
1 <= nums[i] <= 109
1 <= k <= 109
There is an undirected weighted graph with n
vertices labeled from 0
to n - 1
.
You are given the integer n
and an array edges
, where edges[i] = [ui, vi, wi]
indicates that there is an edge between vertices ui
and vi
with a weight of wi
.
A walk on a graph is a sequence of vertices and edges. The walk starts and ends with a vertex, and each edge connects the vertex that comes before it and the vertex that comes after it. It's important to note that a walk may visit the same edge or vertex more than once.
\n\nThe cost of a walk starting at node u
and ending at node v
is defined as the bitwise AND
of the weights of the edges traversed during the walk. In other words, if the sequence of edge weights encountered during the walk is w0, w1, w2, ..., wk
, then the cost is calculated as w0 & w1 & w2 & ... & wk
, where &
denotes the bitwise AND
operator.
You are also given a 2D array query
, where query[i] = [si, ti]
. For each query, you need to find the minimum cost of the walk starting at vertex si
and ending at vertex ti
. If there exists no such walk, the answer is -1
.
Return the array answer
, where answer[i]
denotes the minimum cost of a walk for query i
.
\n
Example 1:
\n\nInput: n = 5, edges = [[0,1,7],[1,3,7],[1,2,1]], query = [[0,3],[3,4]]
\n\nOutput: [1,-1]
\n\nExplanation:
\nTo achieve the cost of 1 in the first query, we need to move on the following edges: 0->1
(weight 7), 1->2
(weight 1), 2->1
(weight 1), 1->3
(weight 7).
In the second query, there is no walk between nodes 3 and 4, so the answer is -1.
\n\nExample 2:
\nInput: n = 3, edges = [[0,2,7],[0,1,15],[1,2,6],[1,2,1]], query = [[1,2]]
\n\nOutput: [0]
\n\nExplanation:
\nTo achieve the cost of 0 in the first query, we need to move on the following edges: 1->2
(weight 1), 2->1
(weight 6), 1->2
(weight 1).
\n
Constraints:
\n\n2 <= n <= 105
0 <= edges.length <= 105
edges[i].length == 3
0 <= ui, vi <= n - 1
ui != vi
0 <= wi <= 105
1 <= query.length <= 105
query[i].length == 2
0 <= si, ti <= n - 1
si != ti
You are given a string s
. The score of a string is defined as the sum of the absolute difference between the ASCII values of adjacent characters.
Return the score of s
.
\n
Example 1:
\n\nInput: s = "hello"
\n\nOutput: 13
\n\nExplanation:
\n\nThe ASCII values of the characters in s
are: 'h' = 104
, 'e' = 101
, 'l' = 108
, 'o' = 111
. So, the score of s
would be |104 - 101| + |101 - 108| + |108 - 108| + |108 - 111| = 3 + 7 + 0 + 3 = 13
.
Example 2:
\n\nInput: s = "zaz"
\n\nOutput: 50
\n\nExplanation:
\n\nThe ASCII values of the characters in s
are: 'z' = 122
, 'a' = 97
. So, the score of s
would be |122 - 97| + |97 - 122| = 25 + 25 = 50
.
\n
Constraints:
\n\n2 <= s.length <= 100
s
consists only of lowercase English letters.You are given a 2D integer array points
, where points[i] = [xi, yi]
. You are also given an integer w
. Your task is to cover all the given points with rectangles.
Each rectangle has its lower end at some point (x1, 0)
and its upper end at some point (x2, y2)
, where x1 <= x2
, y2 >= 0
, and the condition x2 - x1 <= w
must be satisfied for each rectangle.
A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.
\n\nReturn an integer denoting the minimum number of rectangles needed so that each point is covered by at least one rectangle.
\n\nNote: A point may be covered by more than one rectangle.
\n\n\n
Example 1:
\n\nInput: points = [[2,1],[1,0],[1,4],[1,8],[3,5],[4,6]], w = 1
\n\nOutput: 2
\n\nExplanation:
\n\nThe image above shows one possible placement of rectangles to cover the points:
\n\n(1, 0)
and its upper end at (2, 8)
(3, 0)
and its upper end at (4, 8)
Example 2:
\n\nInput: points = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]], w = 2
\n\nOutput: 3
\n\nExplanation:
\n\nThe image above shows one possible placement of rectangles to cover the points:
\n\n(0, 0)
and its upper end at (2, 2)
(3, 0)
and its upper end at (5, 5)
(6, 0)
and its upper end at (6, 6)
Example 3:
\n\nInput: points = [[2,3],[1,2]], w = 0
\n\nOutput: 2
\n\nExplanation:
\n\nThe image above shows one possible placement of rectangles to cover the points:
\n\n(1, 0)
and its upper end at (1, 2)
(2, 0)
and its upper end at (2, 3)
\n
Constraints:
\n\n1 <= points.length <= 105
points[i].length == 2
0 <= xi == points[i][0] <= 109
0 <= yi == points[i][1] <= 109
0 <= w <= 109
(xi, yi)
are distinct.There is an undirected graph of n
nodes. You are given a 2D array edges
, where edges[i] = [ui, vi, lengthi]
describes an edge between node ui
and node vi
with a traversal time of lengthi
units.
Additionally, you are given an array disappear
, where disappear[i]
denotes the time when the node i
disappears from the graph and you won't be able to visit it.
Note that the graph might be disconnected and might contain multiple edges.
\n\nReturn the array answer
, with answer[i]
denoting the minimum units of time required to reach node i
from node 0. If node i
is unreachable from node 0 then answer[i]
is -1
.
\n
Example 1:
\n\nInput: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,1,5]
\n\nOutput: [0,-1,4]
\n\nExplanation:
\n\nWe are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
\n\nedges[0]
. Unfortunately, it disappears at that moment, so we won't be able to visit it.edges[2]
.Example 2:
\n\nInput: n = 3, edges = [[0,1,2],[1,2,1],[0,2,4]], disappear = [1,3,5]
\n\nOutput: [0,2,3]
\n\nExplanation:
\n\nWe are starting our journey from node 0, and our goal is to find the minimum time required to reach each node before it disappears.
\n\nedges[0]
.edges[0]
and edges[1]
.Example 3:
\n\nInput: n = 2, edges = [[0,1,1]], disappear = [1,1]
\n\nOutput: [0,-1]
\n\nExplanation:
\n\nExactly when we reach node 1, it disappears.
\n\n
Constraints:
\n\n1 <= n <= 5 * 104
0 <= edges.length <= 105
edges[i] == [ui, vi, lengthi]
0 <= ui, vi <= n - 1
1 <= lengthi <= 105
disappear.length == n
1 <= disappear[i] <= 105
You are given an array of positive integers nums
.
Return the number of subarrays of nums
, where the first and the last elements of the subarray are equal to the largest element in the subarray.
\n
Example 1:
\n\nInput: nums = [1,4,3,3,2]
\n\nOutput: 6
\n\nExplanation:
\n\nThere are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
\n\n[1,4,3,3,2]
, with its largest element 1. The first element is 1 and the last element is also 1.[1,4,3,3,2]
, with its largest element 4. The first element is 4 and the last element is also 4.[1,4,3,3,2]
, with its largest element 3. The first element is 3 and the last element is also 3.[1,4,3,3,2]
, with its largest element 3. The first element is 3 and the last element is also 3.[1,4,3,3,2]
, with its largest element 2. The first element is 2 and the last element is also 2.[1,4,3,3,2]
, with its largest element 3. The first element is 3 and the last element is also 3.Hence, we return 6.
\nExample 2:
\n\nInput: nums = [3,3,3]
\n\nOutput: 6
\n\nExplanation:
\n\nThere are 6 subarrays which have the first and the last elements equal to the largest element of the subarray:
\n\n[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.[3,3,3]
, with its largest element 3. The first element is 3 and the last element is also 3.Hence, we return 6.
\nExample 3:
\n\nInput: nums = [1]
\n\nOutput: 1
\n\nExplanation:
\n\nThere is a single subarray of nums
which is [1]
, with its largest element 1. The first element is 1 and the last element is also 1.
Hence, we return 1.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
You are given a string s
representing a 12-hour format time where some of the digits (possibly none) are replaced with a "?"
.
12-hour times are formatted as "HH:MM"
, where HH
is between 00
and 11
, and MM
is between 00
and 59
. The earliest 12-hour time is 00:00
, and the latest is 11:59
.
You have to replace all the "?"
characters in s
with digits such that the time we obtain by the resulting string is a valid 12-hour format time and is the latest possible.
Return the resulting string.
\n\n\n
Example 1:
\n\nInput: s = "1?:?4"
\n\nOutput: "11:54"
\n\nExplanation: The latest 12-hour format time we can achieve by replacing "?"
characters is "11:54"
.
Example 2:
\n\nInput: s = "0?:5?"
\n\nOutput: "09:59"
\n\nExplanation: The latest 12-hour format time we can achieve by replacing "?"
characters is "09:59"
.
\n
Constraints:
\n\ns.length == 5
s[2]
is equal to the character ":"
.s[2]
are digits or "?"
characters."00:00"
and "11:59"
that you can obtain after replacing the "?"
characters.You are given an integer array nums
.
Return an integer that is the maximum distance between the indices of two (not necessarily different) prime numbers in nums
.
\n
Example 1:
\n\nInput: nums = [4,2,9,5,3]
\n\nOutput: 3
\n\nExplanation: nums[1]
, nums[3]
, and nums[4]
are prime. So the answer is |4 - 1| = 3
.
Example 2:
\n\nInput: nums = [4,8,2,8]
\n\nOutput: 0
\n\nExplanation: nums[2]
is prime. Because there is just one prime number, the answer is |2 - 2| = 0
.
\n
Constraints:
\n\n1 <= nums.length <= 3 * 105
1 <= nums[i] <= 100
nums
is at least one.You are given an integer array coins
representing coins of different denominations and an integer k
.
You have an infinite number of coins of each denomination. However, you are not allowed to combine coins of different denominations.
\n\nReturn the kth
smallest amount that can be made using these coins.
\n
Example 1:
\n\nInput: coins = [3,6,9], k = 3
\n\nOutput: 9
\n\nExplanation: The given coins can make the following amounts:
\nCoin 3 produces multiples of 3: 3, 6, 9, 12, 15, etc.
\nCoin 6 produces multiples of 6: 6, 12, 18, 24, etc.
\nCoin 9 produces multiples of 9: 9, 18, 27, 36, etc.
\nAll of the coins combined produce: 3, 6, 9, 12, 15, etc.
Example 2:
\n\nInput: coins = [5,2], k = 7
\n\nOutput: 12
\n\nExplanation: The given coins can make the following amounts:
\nCoin 5 produces multiples of 5: 5, 10, 15, 20, etc.
\nCoin 2 produces multiples of 2: 2, 4, 6, 8, 10, 12, etc.
\nAll of the coins combined produce: 2, 4, 5, 6, 8, 10, 12, 14, 15, etc.
\n
Constraints:
\n\n1 <= coins.length <= 15
1 <= coins[i] <= 25
1 <= k <= 2 * 109
coins
contains pairwise distinct integers.You are given two arrays nums
and andValues
of length n
and m
respectively.
The value of an array is equal to the last element of that array.
\n\nYou have to divide nums
into m
disjoint contiguous subarrays such that for the ith
subarray [li, ri]
, the bitwise AND
of the subarray elements is equal to andValues[i]
, in other words, nums[li] & nums[li + 1] & ... & nums[ri] == andValues[i]
for all 1 <= i <= m
, where &
represents the bitwise AND
operator.
Return the minimum possible sum of the values of the m
subarrays nums
is divided into. If it is not possible to divide nums
into m
subarrays satisfying these conditions, return -1
.
\n
Example 1:
\n\nInput: nums = [1,4,3,3,2], andValues = [0,3,3,2]
\n\nOutput: 12
\n\nExplanation:
\n\nThe only possible way to divide nums
is:
[1,4]
as 1 & 4 == 0
.[3]
as the bitwise AND
of a single element subarray is that element itself.[3]
as the bitwise AND
of a single element subarray is that element itself.[2]
as the bitwise AND
of a single element subarray is that element itself.The sum of the values for these subarrays is 4 + 3 + 3 + 2 = 12
.
Example 2:
\n\nInput: nums = [2,3,5,7,7,7,5], andValues = [0,7,5]
\n\nOutput: 17
\n\nExplanation:
\n\nThere are three ways to divide nums
:
[[2,3,5],[7,7,7],[5]]
with the sum of the values 5 + 7 + 5 == 17
.[[2,3,5,7],[7,7],[5]]
with the sum of the values 7 + 7 + 5 == 19
.[[2,3,5,7,7],[7],[5]]
with the sum of the values 7 + 7 + 5 == 19
.The minimum possible sum of the values is 17
.
Example 3:
\n\nInput: nums = [1,2,3,4], andValues = [2]
\n\nOutput: -1
\n\nExplanation:
\n\nThe bitwise AND
of the entire array nums
is 0
. As there is no possible way to divide nums
into a single subarray to have the bitwise AND
of elements 2
, return -1
.
\n
Constraints:
\n\n1 <= n == nums.length <= 104
1 <= m == andValues.length <= min(n, 10)
1 <= nums[i] < 105
0 <= andValues[j] < 105
dp[i][j]
be the optimal answer to split nums[0..(i - 1)]
into the first j
andValues.",
@@ -117400,7 +117705,7 @@
"content": null,
"likes": 4,
"dislikes": 6,
- "stats": "{\"totalAccepted\": \"1.4K\", \"totalSubmission\": \"2.3K\", \"totalAcceptedRaw\": 1369, \"totalSubmissionRaw\": 2313, \"acRate\": \"59.2%\"}",
+ "stats": "{\"totalAccepted\": \"1.8K\", \"totalSubmission\": \"3.1K\", \"totalAcceptedRaw\": 1760, \"totalSubmissionRaw\": 3093, \"acRate\": \"56.9%\"}",
"similarQuestions": "[]",
"categoryTitle": "Database",
"hints": [],
@@ -117426,9 +117731,9 @@
"questionFrontendId": "3119",
"title": "Maximum Number of Potholes That Can Be Fixed",
"content": null,
- "likes": 15,
+ "likes": 17,
"dislikes": 2,
- "stats": "{\"totalAccepted\": \"2.5K\", \"totalSubmission\": \"4.7K\", \"totalAcceptedRaw\": 2536, \"totalSubmissionRaw\": 4744, \"acRate\": \"53.5%\"}",
+ "stats": "{\"totalAccepted\": \"3.3K\", \"totalSubmission\": \"6.2K\", \"totalAcceptedRaw\": 3276, \"totalSubmissionRaw\": 6154, \"acRate\": \"53.2%\"}",
"similarQuestions": "[]",
"categoryTitle": "Algorithms",
"hints": [
@@ -117464,9 +117769,9 @@
"questionFrontendId": "3120",
"title": "Count the Number of Special Characters I",
"content": "You are given a string word
. A letter is called special if it appears both in lowercase and uppercase in word
.
Return the number of special letters in word
.
\n
Example 1:
\n\nInput: word = "aaAbcBC"
\n\nOutput: 3
\n\nExplanation:
\n\nThe special characters in word
are 'a'
, 'b'
, and 'c'
.
Example 2:
\n\nInput: word = "abc"
\n\nOutput: 0
\n\nExplanation:
\n\nNo character in word
appears in uppercase.
Example 3:
\n\nInput: word = "abBCab"
\n\nOutput: 1
\n\nExplanation:
\n\nThe only special character in word
is 'b'
.
\n
Constraints:
\n\n1 <= word.length <= 50
word
consists of only lowercase and uppercase English letters.You are given a string word
. A letter c
is called special if it appears both in lowercase and uppercase in word
, and every lowercase occurrence of c
appears before the first uppercase occurrence of c
.
Return the number of special letters in word
.
\n
Example 1:
\n\nInput: word = "aaAbcBC"
\n\nOutput: 3
\n\nExplanation:
\n\nThe special characters are 'a'
, 'b'
, and 'c'
.
Example 2:
\n\nInput: word = "abc"
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no special characters in word
.
Example 3:
\n\nInput: word = "AbBCab"
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no special characters in word
.
\n
Constraints:
\n\n1 <= word.length <= 2 * 105
word
consists of only lowercase and uppercase English letters.You are given a 2D matrix grid
of size m x n
. In one operation, you can change the value of any cell to any non-negative number. You need to perform some operations such that each cell grid[i][j]
is:
grid[i][j] == grid[i + 1][j]
(if it exists).grid[i][j] != grid[i][j + 1]
(if it exists).Return the minimum number of operations needed.
\n\n\n
Example 1:
\n\nInput: grid = [[1,0,2],[1,0,2]]
\n\nOutput: 0
\n\nExplanation:
\n\nAll the cells in the matrix already satisfy the properties.
\nExample 2:
\n\nInput: grid = [[1,1,1],[0,0,0]]
\n\nOutput: 3
\n\nExplanation:
\n\nThe matrix becomes [[1,0,1],[1,0,1]]
which satisfies the properties, by doing these 3 operations:
grid[1][0]
to 1.grid[0][1]
to 0.grid[1][2]
to 1.Example 3:
\n\nInput: grid = [[1],[2],[3]]
\n\nOutput: 2
\n\nExplanation:
\n\nThere is a single column. We can change the value to 1 in each cell using 2 operations.
\n\n
Constraints:
\n\n1 <= n, m <= 1000
0 <= grid[i][j] <= 9
You are given an undirected weighted graph of n
nodes numbered from 0 to n - 1
. The graph consists of m
edges represented by a 2D array edges
, where edges[i] = [ai, bi, wi]
indicates that there is an edge between nodes ai
and bi
with weight wi
.
Consider all the shortest paths from node 0 to node n - 1
in the graph. You need to find a boolean array answer
where answer[i]
is true
if the edge edges[i]
is part of at least one shortest path. Otherwise, answer[i]
is false
.
Return the array answer
.
Note that the graph may not be connected.
\n\n\n
Example 1:
\nInput: n = 6, edges = [[0,1,4],[0,2,1],[1,3,2],[1,4,3],[1,5,1],[2,3,1],[3,5,3],[4,5,2]]
\n\nOutput: [true,true,true,false,true,true,true,false]
\n\nExplanation:
\n\nThe following are all the shortest paths between nodes 0 and 5:
\n\n0 -> 1 -> 5
: The sum of weights is 4 + 1 = 5
.0 -> 2 -> 3 -> 5
: The sum of weights is 1 + 1 + 3 = 5
.0 -> 2 -> 3 -> 1 -> 5
: The sum of weights is 1 + 1 + 2 + 1 = 5
.Example 2:
\nInput: n = 4, edges = [[2,0,1],[0,1,1],[0,3,4],[3,2,2]]
\n\nOutput: [true,false,false,true]
\n\nExplanation:
\n\nThere is one shortest path between nodes 0 and 3, which is the path 0 -> 2 -> 3
with the sum of weights 1 + 2 = 3
.
\n
Constraints:
\n\n2 <= n <= 5 * 104
m == edges.length
1 <= m <= min(5 * 104, n * (n - 1) / 2)
0 <= ai, bi < n
ai != bi
1 <= wi <= 105
You are given a 2D matrix grid
of size 3 x 3
consisting only of characters 'B'
and 'W'
. Character 'W'
represents the white color, and character 'B'
represents the black color.
Your task is to change the color of at most one cell so that the matrix has a 2 x 2
square where all cells are of the same color.
Return true
if it is possible to create a 2 x 2
square of the same color, otherwise, return false
.
\n\n\n
Example 1:
\n\nInput: grid = [["B","W","B"],["B","W","W"],["B","W","B"]]
\n\nOutput: true
\n\nExplanation:
\n\nIt can be done by changing the color of the grid[0][2]
.
Example 2:
\n\nInput: grid = [["B","W","B"],["W","B","W"],["B","W","B"]]
\n\nOutput: false
\n\nExplanation:
\n\nIt cannot be done by changing at most one cell.
\nExample 3:
\n\nInput: grid = [["B","W","B"],["B","W","W"],["B","W","W"]]
\n\nOutput: true
\n\nExplanation:
\n\nThe grid
already contains a 2 x 2
square of the same color.
\n
Constraints:
\n\ngrid.length == 3
grid[i].length == 3
grid[i][j]
is either 'W'
or 'B'
.You are given a 2D boolean matrix grid
.
A collection of 3 elements of grid
is a right triangle if one of its elements is in the same row with another element and in the same column with the third element. The 3 elements may not be next to each other.
Return an integer that is the number of right triangles that can be made with 3 elements of grid
such that all of them have a value of 1.
\n
Example 1:
\n\n0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
Input: grid = [[0,1,0],[0,1,1],[0,1,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nThere are two right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle because the 3 elements are in the same column.
\nExample 2:
\n\n1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
Input: grid = [[1,0,0,0],[0,1,0,1],[1,0,0,0]]
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no right triangles with elements of the value 1. Notice that the blue ones do not form a right triangle.
\nExample 3:
\n\n1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
1 | \n\t\t\t0 | \n\t\t\t0 | \n\t\t
Input: grid = [[1,0,1],[1,0,0],[1,0,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nThere are two right triangles with elements of the value 1.
\n\n
Constraints:
\n\n1 <= grid.length <= 1000
1 <= grid[i].length <= 1000
0 <= grid[i][j] <= 1
You are given 3 positive integers zero
, one
, and limit
.
A binary array arr
is called stable if:
arr
is exactly zero
.arr
is exactly one
.arr
with a size greater than limit
must contain both 0 and 1.Return the total number of stable binary arrays.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: zero = 1, one = 1, limit = 2
\n\nOutput: 2
\n\nExplanation:
\n\nThe two possible stable binary arrays are [1,0]
and [0,1]
, as both arrays have a single 0 and a single 1, and no subarray has a length greater than 2.
Example 2:
\n\nInput: zero = 1, one = 2, limit = 1
\n\nOutput: 1
\n\nExplanation:
\n\nThe only possible stable binary array is [1,0,1]
.
Note that the binary arrays [1,1,0]
and [0,1,1]
have subarrays of length 2 with identical elements, hence, they are not stable.
Example 3:
\n\nInput: zero = 3, one = 3, limit = 2
\n\nOutput: 14
\n\nExplanation:
\n\nAll the possible stable binary arrays are [0,0,1,0,1,1]
, [0,0,1,1,0,1]
, [0,1,0,0,1,1]
, [0,1,0,1,0,1]
, [0,1,0,1,1,0]
, [0,1,1,0,0,1]
, [0,1,1,0,1,0]
, [1,0,0,1,0,1]
, [1,0,0,1,1,0]
, [1,0,1,0,0,1]
, [1,0,1,0,1,0]
, [1,0,1,1,0,0]
, [1,1,0,0,1,0]
, and [1,1,0,1,0,0]
.
\n
Constraints:
\n\n1 <= zero, one, limit <= 200
You are given 3 positive integers zero
, one
, and limit
.
A binary array arr
is called stable if:
arr
is exactly zero
.arr
is exactly one
.arr
with a size greater than limit
must contain both 0 and 1.Return the total number of stable binary arrays.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: zero = 1, one = 1, limit = 2
\n\nOutput: 2
\n\nExplanation:
\n\nThe two possible stable binary arrays are [1,0]
and [0,1]
.
Example 2:
\n\nInput: zero = 1, one = 2, limit = 1
\n\nOutput: 1
\n\nExplanation:
\n\nThe only possible stable binary array is [1,0,1]
.
Example 3:
\n\nInput: zero = 3, one = 3, limit = 2
\n\nOutput: 14
\n\nExplanation:
\n\nAll the possible stable binary arrays are [0,0,1,0,1,1]
, [0,0,1,1,0,1]
, [0,1,0,0,1,1]
, [0,1,0,1,0,1]
, [0,1,0,1,1,0]
, [0,1,1,0,0,1]
, [0,1,1,0,1,0]
, [1,0,0,1,0,1]
, [1,0,0,1,1,0]
, [1,0,1,0,0,1]
, [1,0,1,0,1,0]
, [1,0,1,1,0,0]
, [1,1,0,0,1,0]
, and [1,1,0,1,0,0]
.
\n
Constraints:
\n\n1 <= zero, one, limit <= 1000
You are given two arrays of equal length, nums1
and nums2
.
Each element in nums1
has been increased (or decreased in the case of negative) by an integer, represented by the variable x
.
As a result, nums1
becomes equal to nums2
. Two arrays are considered equal when they contain the same integers with the same frequencies.
Return the integer x
.
\n
Example 1:
\n\nInput: nums1 = [2,6,4], nums2 = [9,7,5]
\n\nOutput: 3
\n\nExplanation:
\n\nThe integer added to each element of nums1
is 3.
Example 2:
\n\nInput: nums1 = [10], nums2 = [5]
\n\nOutput: -5
\n\nExplanation:
\n\nThe integer added to each element of nums1
is -5.
Example 3:
\n\nInput: nums1 = [1,1,1,1], nums2 = [1,1,1,1]
\n\nOutput: 0
\n\nExplanation:
\n\nThe integer added to each element of nums1
is 0.
\n
Constraints:
\n\n1 <= nums1.length == nums2.length <= 100
0 <= nums1[i], nums2[i] <= 1000
x
such that nums1
can become equal to nums2
by adding x
to each element of nums1
.You are given two integer arrays nums1
and nums2
.
From nums1
two elements have been removed, and all other elements have been increased (or decreased in the case of negative) by an integer, represented by the variable x
.
As a result, nums1
becomes equal to nums2
. Two arrays are considered equal when they contain the same integers with the same frequencies.
Return the minimum possible integer x
that achieves this equivalence.
\n
Example 1:
\n\nInput: nums1 = [4,20,16,12,8], nums2 = [14,18,10]
\n\nOutput: -2
\n\nExplanation:
\n\nAfter removing elements at indices [0,4]
and adding -2, nums1
becomes [18,14,10]
.
Example 2:
\n\nInput: nums1 = [3,5,5,3], nums2 = [7,7]
\n\nOutput: 2
\n\nExplanation:
\n\nAfter removing elements at indices [0,3]
and adding 2, nums1
becomes [7,7]
.
\n
Constraints:
\n\n3 <= nums1.length <= 200
nums2.length == nums1.length - 2
0 <= nums1[i], nums2[i] <= 1000
x
such that nums1
can become equal to nums2
by removing two elements and adding x
to each element of nums1
.You are given two integers n
and x
. You have to construct an array of positive integers nums
of size n
where for every 0 <= i < n - 1
, nums[i + 1]
is greater than nums[i]
, and the result of the bitwise AND
operation between all elements of nums
is x
.
Return the minimum possible value of nums[n - 1]
.
\n
Example 1:
\n\nInput: n = 3, x = 4
\n\nOutput: 6
\n\nExplanation:
\n\nnums
can be [4,5,6]
and its last element is 6.
Example 2:
\n\nInput: n = 2, x = 7
\n\nOutput: 15
\n\nExplanation:
\n\nnums
can be [7,15]
and its last element is 15.
\n
Constraints:
\n\n1 <= n, x <= 108
You are given an integer array nums
. The uniqueness array of nums
is the sorted array that contains the number of distinct elements of all the subarrays of nums
. In other words, it is a sorted array consisting of distinct(nums[i..j])
, for all 0 <= i <= j < nums.length
.
Here, distinct(nums[i..j])
denotes the number of distinct elements in the subarray that starts at index i
and ends at index j
.
Return the median of the uniqueness array of nums
.
Note that the median of an array is defined as the middle element of the array when it is sorted in non-decreasing order. If there are two choices for a median, the smaller of the two values is taken.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3]
\n\nOutput: 1
\n\nExplanation:
\n\nThe uniqueness array of nums
is [distinct(nums[0..0]), distinct(nums[1..1]), distinct(nums[2..2]), distinct(nums[0..1]), distinct(nums[1..2]), distinct(nums[0..2])]
which is equal to [1, 1, 1, 2, 2, 3]
. The uniqueness array has a median of 1. Therefore, the answer is 1.
Example 2:
\n\nInput: nums = [3,4,3,4,5]
\n\nOutput: 2
\n\nExplanation:
\n\nThe uniqueness array of nums
is [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3]
. The uniqueness array has a median of 2. Therefore, the answer is 2.
Example 3:
\n\nInput: nums = [4,3,5,4]
\n\nOutput: 2
\n\nExplanation:
\n\nThe uniqueness array of nums
is [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]
. The uniqueness array has a median of 2. Therefore, the answer is 2.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
A word is considered valid if:
\n\nYou are given a string word
.
Return true
if word
is valid, otherwise, return false
.
Notes:
\n\n'a'
, 'e'
, 'i'
, 'o'
, 'u'
, and their uppercases are vowels.\n
Example 1:
\n\nInput: word = "234Adas"
\n\nOutput: true
\n\nExplanation:
\n\nThis word satisfies the conditions.
\nExample 2:
\n\nInput: word = "b3"
\n\nOutput: false
\n\nExplanation:
\n\nThe length of this word is fewer than 3, and does not have a vowel.
\nExample 3:
\n\nInput: word = "a3$e"
\n\nOutput: false
\n\nExplanation:
\n\nThis word contains a '$'
character and does not have a consonant.
\n
Constraints:
\n\n1 <= word.length <= 20
word
consists of English uppercase and lowercase letters, digits, '@'
, '#'
, and '$'
.You are given a string word
of size n
, and an integer k
such that k
divides n
.
In one operation, you can pick any two indices i
and j
, that are divisible by k
, then replace the substring of length k
starting at i
with the substring of length k
starting at j
. That is, replace the substring word[i..i + k - 1]
with the substring word[j..j + k - 1]
.
Return the minimum number of operations required to make word
k-periodic.
We say that word
is k-periodic if there is some string s
of length k
such that word
can be obtained by concatenating s
an arbitrary number of times. For example, if word == “ababab”
, then word
is 2-periodic for s = "ab"
.
\n
Example 1:
\n\nInput: word = "leetcodeleet", k = 4
\n\nOutput: 1
\n\nExplanation:
\n\nWe can obtain a 4-periodic string by picking i = 4 and j = 0. After this operation, word becomes equal to "leetleetleet".
\nExample 2:
\n\nInput: word = "leetcoleet", k = 2
\n\nOutput: 3
\n\nExplanation:
\n\nWe can obtain a 2-periodic string by applying the operations in the table below.
\n\ni | \n\t\t\tj | \n\t\t\tword | \n\t\t
---|---|---|
0 | \n\t\t\t2 | \n\t\t\tetetcoleet | \n\t\t
4 | \n\t\t\t0 | \n\t\t\tetetetleet | \n\t\t
6 | \n\t\t\t0 | \n\t\t\tetetetetet | \n\t\t
\n
Constraints:
\n\n1 <= n == word.length <= 105
1 <= k <= word.length
k
divides word.length
.word
consists only of lowercase English letters.You are given a string s
, which is known to be a concatenation of anagrams of some string t
.
Return the minimum possible length of the string t
.
An anagram is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".
\n\n\n
Example 1:
\n\nInput: s = "abba"
\n\nOutput: 2
\n\nExplanation:
\n\nOne possible string t
could be "ba"
.
Example 2:
\n\nInput: s = "cdef"
\n\nOutput: 4
\n\nExplanation:
\n\nOne possible string t
could be "cdef"
, notice that t
can be equal to s
.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consist only of lowercase English letters.You are given a string s
, which is known to be a concatenation of anagrams of some string t
.
Return the minimum possible length of the string t
.
An anagram is formed by rearranging the letters of a string. For example, "aab", "aba", and, "baa" are anagrams of "aab".
\n\n\n
Example 1:
\n\nInput: s = "abba"
\n\nOutput: 2
\n\nExplanation:
\n\nOne possible string t
could be "ba"
.
Example 2:
\n\nInput: s = "cdef"
\n\nOutput: 4
\n\nExplanation:
\n\nOne possible string t
could be "cdef"
, notice that t
can be equal to s
.
Example 2:
\n\nInput: s = "abcbcacabbaccba"
\n\nOutput: 3
\n\n
Constraints:
\n\n1 <= s.length <= 105
s
consist only of lowercase English letters.You are given an integer array nums
and two integers cost1
and cost2
. You are allowed to perform either of the following operations any number of times:
i
from nums
and increase nums[i]
by 1
for a cost of cost1
.i
, j
, from nums
and increase nums[i]
and nums[j]
by 1
for a cost of cost2
.Return the minimum cost required to make all elements in the array equal.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [4,1], cost1 = 5, cost2 = 2
\n\nOutput: 15
\n\nExplanation:
\n\nThe following operations can be performed to make the values equal:
\n\nnums[1]
by 1 for a cost of 5. nums
becomes [4,2]
.nums[1]
by 1 for a cost of 5. nums
becomes [4,3]
.nums[1]
by 1 for a cost of 5. nums
becomes [4,4]
.The total cost is 15.
\nExample 2:
\n\nInput: nums = [2,3,3,3,5], cost1 = 2, cost2 = 1
\n\nOutput: 6
\n\nExplanation:
\n\nThe following operations can be performed to make the values equal:
\n\nnums[0]
and nums[1]
by 1 for a cost of 1. nums
becomes [3,4,3,3,5]
.nums[0]
and nums[2]
by 1 for a cost of 1. nums
becomes [4,4,4,3,5]
.nums[0]
and nums[3]
by 1 for a cost of 1. nums
becomes [5,4,4,4,5]
.nums[1]
and nums[2]
by 1 for a cost of 1. nums
becomes [5,5,5,4,5]
.nums[3]
by 1 for a cost of 2. nums
becomes [5,5,5,5,5]
.The total cost is 6.
\nExample 3:
\n\nInput: nums = [3,5,3], cost1 = 1, cost2 = 3
\n\nOutput: 4
\n\nExplanation:
\n\nThe following operations can be performed to make the values equal:
\n\nnums[0]
by 1 for a cost of 1. nums
becomes [4,5,3]
.nums[0]
by 1 for a cost of 1. nums
becomes [5,5,3]
.nums[2]
by 1 for a cost of 1. nums
becomes [5,5,4]
.nums[2]
by 1 for a cost of 1. nums
becomes [5,5,5]
.The total cost is 4.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
1 <= cost1 <= 106
1 <= cost2 <= 106
You are given a 2D matrix grid
of size m x n
. You need to check if each cell grid[i][j]
is:
grid[i][j] == grid[i + 1][j]
(if it exists).grid[i][j] != grid[i][j + 1]
(if it exists).Return true
if all the cells satisfy these conditions, otherwise, return false
.
\n
Example 1:
\n\nInput: grid = [[1,0,2],[1,0,2]]
\n\nOutput: true
\n\nExplanation:
\n\nAll the cells in the grid satisfy the conditions.
\nExample 2:
\n\nInput: grid = [[1,1,1],[0,0,0]]
\n\nOutput: false
\n\nExplanation:
\n\nAll cells in the first row are equal.
\nExample 3:
\n\nInput: grid = [[1],[2],[3]]
\n\nOutput: false
\n\nExplanation:
\n\nCells in the first column have different values.
\n\n
Constraints:
\n\n1 <= n, m <= 10
0 <= grid[i][j] <= 9
You are given a 2D array points
and a string s
where, points[i]
represents the coordinates of point i
, and s[i]
represents the tag of point i
.
A valid square is a square centered at the origin (0, 0)
, has edges parallel to the axes, and does not contain two points with the same tag.
Return the maximum number of points contained in a valid square.
\n\nNote:
\n\n\n
Example 1:
\n\nInput: points = [[2,2],[-1,-2],[-4,4],[-3,1],[3,-3]], s = "abdca"
\n\nOutput: 2
\n\nExplanation:
\n\nThe square of side length 4 covers two points points[0]
and points[1]
.
Example 2:
\n\nInput: points = [[1,1],[-2,-2],[-2,2]], s = "abb"
\n\nOutput: 1
\n\nExplanation:
\n\nThe square of side length 2 covers one point, which is points[0]
.
Example 3:
\n\nInput: points = [[1,1],[-1,-1],[2,-2]], s = "ccd"
\n\nOutput: 0
\n\nExplanation:
\n\nIt's impossible to make any valid squares centered at the origin such that it covers only one point among points[0]
and points[1]
.
\n
Constraints:
\n\n1 <= s.length, points.length <= 105
points[i].length == 2
-109 <= points[i][0], points[i][1] <= 109
s.length == points.length
points
consists of distinct coordinates.s
consists only of lowercase English letters.(x, y)
is max(abs(x), abs(y)) * 2
.",
@@ -118326,9 +118631,9 @@
"questionFrontendId": "3144",
"title": "Minimum Substring Partition of Equal Character Frequency",
"content": "Given a string s
, you need to partition it into one or more balanced substrings. For example, if s == "ababcc"
then ("abab", "c", "c")
, ("ab", "abc", "c")
, and ("ababcc")
are all valid partitions, but ("a", "bab", "cc")
, ("aba", "bc", "c")
, and ("ab", "abcc")
are not. The unbalanced substrings are bolded.
Return the minimum number of substrings that you can partition s
into.
Note: A balanced string is a string where each character in the string occurs the same number of times.
\n\n\n
Example 1:
\n\nInput: s = "fabccddg"
\n\nOutput: 3
\n\nExplanation:
\n\nWe can partition the string s
into 3 substrings in one of the following ways: ("fab, "ccdd", "g")
, or ("fabc", "cd", "dg")
.
Example 2:
\n\nInput: s = "abababaccddb"
\n\nOutput: 2
\n\nExplanation:
\n\nWe can partition the string s
into 2 substrings like so: ("abab", "abaccddb")
.
\n
Constraints:
\n\n1 <= s.length <= 1000
s
consists only of English lowercase letters.The powerful array of a non-negative integer x
is defined as the shortest sorted array of powers of two that sum up to x
. The table below illustrates examples of how the powerful array is determined. It can be proven that the powerful array of x
is unique.
num | \n\t\t\tBinary Representation | \n\t\t\tpowerful array | \n\t\t
---|---|---|
1 | \n\t\t\t00001 | \n\t\t\t[1] | \n\t\t
8 | \n\t\t\t01000 | \n\t\t\t[8] | \n\t\t
10 | \n\t\t\t01010 | \n\t\t\t[2, 8] | \n\t\t
13 | \n\t\t\t01101 | \n\t\t\t[1, 4, 8] | \n\t\t
23 | \n\t\t\t10111 | \n\t\t\t[1, 2, 4, 16] | \n\t\t
The array big_nums
is created by concatenating the powerful arrays for every positive integer i
in ascending order: 1, 2, 3, and so on. Thus, big_nums
begins as [1, 2, 1, 2, 4, 1, 4, 2, 4, 1, 2, 4, 8, ...]
.
You are given a 2D integer matrix queries
, where for queries[i] = [fromi, toi, modi]
you should calculate (big_nums[fromi] * big_nums[fromi + 1] * ... * big_nums[toi]) % modi
.
Return an integer array answer
such that answer[i]
is the answer to the ith
query.
\n
Example 1:
\n\nInput: queries = [[1,3,7]]
\n\nOutput: [4]
\n\nExplanation:
\n\nThere is one query.
\n\nbig_nums[1..3] = [2,1,2]
. The product of them is 4. The result is 4 % 7 = 4.
Example 2:
\n\nInput: queries = [[2,5,3],[7,7,4]]
\n\nOutput: [2,2]
\n\nExplanation:
\n\nThere are two queries.
\n\nFirst query: big_nums[2..5] = [1,2,4,1]
. The product of them is 8. The result is 8 % 3 = 2
.
Second query: big_nums[7] = 2
. The result is 2 % 4 = 2
.
\n
Constraints:
\n\n1 <= queries.length <= 500
queries[i].length == 3
0 <= queries[i][0] <= queries[i][1] <= 1015
1 <= queries[i][2] <= 105
You are given two strings s
and t
such that every character occurs at most once in s
and t
is a permutation of s
.
The permutation difference between s
and t
is defined as the sum of the absolute difference between the index of the occurrence of each character in s
and the index of the occurrence of the same character in t
.
Return the permutation difference between s
and t
.
\n
Example 1:
\n\nInput: s = "abc", t = "bac"
\n\nOutput: 2
\n\nExplanation:
\n\nFor s = "abc"
and t = "bac"
, the permutation difference of s
and t
is equal to the sum of:
"a"
in s
and the index of the occurrence of "a"
in t
."b"
in s
and the index of the occurrence of "b"
in t
."c"
in s
and the index of the occurrence of "c"
in t
.That is, the permutation difference between s
and t
is equal to |0 - 1| + |1 - 0| + |2 - 2| = 2
.
Example 2:
\n\nInput: s = "abcde", t = "edbac"
\n\nOutput: 12
\n\nExplanation: The permutation difference between s
and t
is equal to |0 - 3| + |1 - 2| + |2 - 4| + |3 - 1| + |4 - 0| = 12
.
\n
Constraints:
\n\n1 <= s.length <= 26
s
.t
is a permutation of s
.s
consists only of lowercase English letters.In a mystic dungeon, n
magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.
You have been cursed in such a way that after absorbing energy from magician i
, you will be instantly transported to magician (i + k)
. This process will be repeated until you reach the magician where (i + k)
does not exist.
In other words, you will choose a starting point and then teleport with k
jumps until you reach the end of the magicians' sequence, absorbing all the energy during the journey.
You are given an array energy
and an integer k
. Return the maximum possible energy you can gain.
\n
Example 1:
\n\nInput: energy = [5,2,-10,-5,1], k = 3
\n\nOutput: 3
\n\nExplanation: We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.
\nExample 2:
\n\nInput: energy = [-2,-3,-1], k = 2
\n\nOutput: -1
\n\nExplanation: We can gain a total energy of -1 by starting from magician 2.
\n\n
Constraints:
\n\n1 <= energy.length <= 105
-1000 <= energy[i] <= 1000
1 <= k <= energy.length - 1
\n\u200b\u200b\u200b\u200b\u200b\u200b", - "likes": 155, - "dislikes": 14, - "stats": "{\"totalAccepted\": \"31.1K\", \"totalSubmission\": \"76.1K\", \"totalAcceptedRaw\": 31121, \"totalSubmissionRaw\": 76057, \"acRate\": \"40.9%\"}", + "content": "
In a mystic dungeon, n
magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.
You have been cursed in such a way that after absorbing energy from magician i
, you will be instantly transported to magician (i + k)
. This process will be repeated until you reach the magician where (i + k)
does not exist.
In other words, you will choose a starting point and then teleport with k
jumps until you reach the end of the magicians' sequence, absorbing all the energy during the journey.
You are given an array energy
and an integer k
. Return the maximum possible energy you can gain.
Note that when you are reach a magician, you must take energy from them, whether it is negative or positive energy.
\n\n\n
Example 1:
\n\nInput: energy = [5,2,-10,-5,1], k = 3
\n\nOutput: 3
\n\nExplanation: We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.
\nExample 2:
\n\nInput: energy = [-2,-3,-1], k = 2
\n\nOutput: -1
\n\nExplanation: We can gain a total energy of -1 by starting from magician 2.
\n\n
Constraints:
\n\n1 <= energy.length <= 105
-1000 <= energy[i] <= 1000
1 <= k <= energy.length - 1
\n\u200b\u200b\u200b\u200b\u200b\u200b", + "likes": 158, + "dislikes": 15, + "stats": "{\"totalAccepted\": \"32.3K\", \"totalSubmission\": \"78.6K\", \"totalAcceptedRaw\": 32300, \"totalSubmissionRaw\": 78551, \"acRate\": \"41.1%\"}", "similarQuestions": "[]", "categoryTitle": "Algorithms", "hints": [ @@ -118471,9 +118776,9 @@ "questionFrontendId": "3148", "title": "Maximum Difference Score in a Grid", "content": "
You are given an m x n
matrix grid
consisting of positive integers. You can move from a cell in the matrix to any other cell that is either to the bottom or to the right (not necessarily adjacent). The score of a move from a cell with the value c1
to a cell with the value c2
is c2 - c1
.
You can start at any cell, and you have to make at least one move.
\n\nReturn the maximum total score you can achieve.
\n\n\n
Example 1:
\nInput: grid = [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]
\n\nOutput: 9
\n\nExplanation: We start at the cell (0, 1)
, and we perform the following moves:
\n- Move from the cell (0, 1)
to (2, 1)
with a score of 7 - 5 = 2
.
\n- Move from the cell (2, 1)
to (2, 2)
with a score of 14 - 7 = 7
.
\nThe total score is 2 + 7 = 9
.
Example 2:
\n\nInput: grid = [[4,3,2],[3,2,1]]
\n\nOutput: -1
\n\nExplanation: We start at the cell (0, 0)
, and we perform one move: (0, 0)
to (0, 1)
. The score is 3 - 4 = -1
.
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
2 <= m, n <= 1000
4 <= m * n <= 105
1 <= grid[i][j] <= 105
You are given an array nums
which is a permutation of [0, 1, 2, ..., n - 1]
. The score of any permutation of [0, 1, 2, ..., n - 1]
named perm
is defined as:
score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|
Return the permutation perm
which has the minimum possible score. If multiple permutations exist with this score, return the one that is lexicographically smallest among them.
\n
Example 1:
\n\nInput: nums = [1,0,2]
\n\nOutput: [0,1,2]
\n\nExplanation:
\n\nThe lexicographically smallest permutation with minimum cost is [0,1,2]
. The cost of this permutation is |0 - 0| + |1 - 2| + |2 - 1| = 2
.
Example 2:
\n\nInput: nums = [0,2,1]
\n\nOutput: [0,2,1]
\n\nExplanation:
\n\nThe lexicographically smallest permutation with minimum cost is [0,2,1]
. The cost of this permutation is |0 - 1| + |2 - 2| + |1 - 0| = 2
.
\n
Constraints:
\n\n2 <= n == nums.length <= 14
nums
is a permutation of [0, 1, 2, ..., n - 1]
.An array is considered special if every pair of its adjacent elements contains two numbers with different parity.
\n\nYou are given an array of integers nums
. Return true
if nums
is a special array, otherwise, return false
.
\n
Example 1:
\n\nInput: nums = [1]
\n\nOutput: true
\n\nExplanation:
\n\nThere is only one element. So the answer is true
.
Example 2:
\n\nInput: nums = [2,1,4]
\n\nOutput: true
\n\nExplanation:
\n\nThere is only two pairs: (2,1)
and (1,4)
, and both of them contain numbers with different parity. So the answer is true
.
Example 3:
\n\nInput: nums = [4,3,1,6]
\n\nOutput: false
\n\nExplanation:
\n\nnums[1]
and nums[2]
are both odd. So the answer is false
.
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
An array is considered special if the parity of every pair of adjacent elements is different. In other words, one element in each pair must be even, and the other must be odd.
\n\nYou are given an array of integers nums
. Return true
if nums
is a special array, otherwise, return false
.
\n
Example 1:
\n\nInput: nums = [1]
\n\nOutput: true
\n\nExplanation:
\n\nThere is only one element. So the answer is true
.
Example 2:
\n\nInput: nums = [2,1,4]
\n\nOutput: true
\n\nExplanation:
\n\nThere is only two pairs: (2,1)
and (1,4)
, and both of them contain numbers with different parity. So the answer is true
.
Example 3:
\n\nInput: nums = [4,3,1,6]
\n\nOutput: false
\n\nExplanation:
\n\nnums[1]
and nums[2]
are both odd. So the answer is false
.
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
An array is considered special if every pair of its adjacent elements contains two numbers with different parity.
\n\nYou are given an array of integer nums
and a 2D integer matrix queries
, where for queries[i] = [fromi, toi]
your task is to check that subarray nums[fromi..toi]
is special or not.
Return an array of booleans answer
such that answer[i]
is true
if nums[fromi..toi]
is special.
\n
Example 1:
\n\nInput: nums = [3,4,1,2,6], queries = [[0,4]]
\n\nOutput: [false]
\n\nExplanation:
\n\nThe subarray is [3,4,1,2,6]
. 2 and 6 are both even.
Example 2:
\n\nInput: nums = [4,3,1,6], queries = [[0,2],[2,3]]
\n\nOutput: [false,true]
\n\nExplanation:
\n\n[4,3,1]
. 3 and 1 are both odd. So the answer to this query is false
.[1,6]
. There is only one pair: (1,6)
and it contains numbers with different parity. So the answer to this query is true
.\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] <= nums.length - 1
You are given an array nums
consisting of positive integers where all integers have the same number of digits.
The digit difference between two integers is the count of different digits that are in the same position in the two integers.
\n\nReturn the sum of the digit differences between all pairs of integers in nums
.
\n
Example 1:
\n\nInput: nums = [13,23,12]
\n\nOutput: 4
\n\nExplanation:
\nWe have the following:
\n- The digit difference between 13 and 23 is 1.
\n- The digit difference between 13 and 12 is 1.
\n- The digit difference between 23 and 12 is 2.
\nSo the total sum of digit differences between all pairs of integers is 1 + 1 + 2 = 4
.
Example 2:
\n\nInput: nums = [10,10,10,10]
\n\nOutput: 0
\n\nExplanation:
\nAll the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.
\n
Constraints:
\n\n2 <= nums.length <= 105
1 <= nums[i] < 109
nums
have the same number of digits.You are given a non-negative integer k
. There exists a staircase with an infinite number of stairs, with the lowest stair numbered 0.
Alice has an integer jump
, with an initial value of 0. She starts on stair 1 and wants to reach stair k
using any number of operations. If she is on stair i
, in one operation she can:
i - 1
. This operation cannot be used consecutively or on stair 0.i + 2jump
. And then, jump
becomes jump + 1
.Return the total number of ways Alice can reach stair k
.
Note that it is possible that Alice reaches the stair k
, and performs some operations to reach the stair k
again.
\n
Example 1:
\n\nInput: k = 0
\n\nOutput: 2
\n\nExplanation:
\n\nThe 2 possible ways of reaching stair 0 are:
\n\nExample 2:
\n\nInput: k = 1
\n\nOutput: 4
\n\nExplanation:
\n\nThe 4 possible ways of reaching stair 1 are:
\n\n\n
Constraints:
\n\n0 <= k <= 109
You are given an array nums
, where each number in the array appears either once or twice.
Return the bitwise XOR
of all the numbers that appear twice in the array, or 0 if no number appears twice.
\n
Example 1:
\n\nInput: nums = [1,2,1,3]
\n\nOutput: 1
\n\nExplanation:
\n\nThe only number that appears twice in nums
is 1.
Example 2:
\n\nInput: nums = [1,2,3]
\n\nOutput: 0
\n\nExplanation:
\n\nNo number appears twice in nums
.
Example 3:
\n\nInput: nums = [1,2,2,1]
\n\nOutput: 3
\n\nExplanation:
\n\nNumbers 1 and 2 appeared twice. 1 XOR 2 == 3
.
\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 50
nums
appears either once or twice.You are given an integer array nums
, an integer array queries
, and an integer x
.
For each queries[i]
, you need to find the index of the queries[i]th
occurrence of x
in the nums
array. If there are fewer than queries[i]
occurrences of x
, the answer should be -1 for that query.
Return an integer array answer
containing the answers to all queries.
\n
Example 1:
\n\nInput: nums = [1,3,1,7], queries = [1,3,2,4], x = 1
\n\nOutput: [0,-1,2,-1]
\n\nExplanation:
\n\nnums
, so the answer is -1.nums
, so the answer is -1.Example 2:
\n\nInput: nums = [1,2,3], queries = [10], x = 5
\n\nOutput: [-1]
\n\nExplanation:
\n\nnums
, so the answer is -1.\n
Constraints:
\n\n1 <= nums.length, queries.length <= 105
1 <= queries[i] <= 105
1 <= nums[i], x <= 104
You are given an integer limit
and a 2D array queries
of size n x 2
.
There are limit + 1
balls with distinct labels in the range [0, limit]
. Initially, all balls are uncolored. For every query in queries
that is of the form [x, y]
, you mark ball x
with the color y
. After each query, you need to find the number of distinct colors among the balls.
Return an array result
of length n
, where result[i]
denotes the number of distinct colors after ith
query.
Note that when answering a query, lack of a color will not be considered as a color.
\n\n\n
Example 1:
\n\nInput: limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]
\n\nOutput: [1,2,2,3]
\n\nExplanation:
\n\nExample 2:
\n\nInput: limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]
\n\nOutput: [1,2,2,3,4]
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= limit <= 109
1 <= n == queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= limit
1 <= queries[i][1] <= 109
You are given an integer limit
and a 2D array queries
of size n x 2
.
There are limit + 1
balls with distinct labels in the range [0, limit]
. Initially, all balls are uncolored. For every query in queries
that is of the form [x, y]
, you mark ball x
with the color y
. After each query, you need to find the number of colors among the balls.
Return an array result
of length n
, where result[i]
denotes the number of colors after ith
query.
Note that when answering a query, lack of a color will not be considered as a color.
\n\n\n
Example 1:
\n\nInput: limit = 4, queries = [[1,4],[2,5],[1,3],[3,4]]
\n\nOutput: [1,2,2,3]
\n\nExplanation:
\n\nExample 2:
\n\nInput: limit = 4, queries = [[0,1],[1,2],[2,2],[3,4],[4,5]]
\n\nOutput: [1,2,2,3,4]
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= limit <= 109
1 <= n == queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= limit
1 <= queries[i][1] <= 109
There exists an infinite number line, with its origin at 0 and extending towards the positive x-axis.
\n\nYou are given a 2D array queries
, which contains two types of queries:
queries[i] = [1, x]
. Build an obstacle at distance x
from the origin. It is guaranteed that there is no obstacle at distance x
when the query is asked.queries[i] = [2, x, sz]
. Check if it is possible to place a block of size sz
anywhere in the range [0, x]
on the line, such that the block entirely lies in the range [0, x]
. A block cannot be placed if it intersects with any obstacle, but it may touch it. Note that you do not actually place the block. Queries are separate.Return a boolean array results
, where results[i]
is true
if you can place the block specified in the ith
query of type 2, and false
otherwise.
\n
Example 1:
\n\nInput: queries = [[1,2],[2,3,3],[2,3,1],[2,2,2]]
\n\nOutput: [false,true,true]
\n\nExplanation:
\n\nFor query 0, place an obstacle at x = 2
. A block of size at most 2 can be placed before x = 3
.
Example 2:
\n\nInput: queries = [[1,7],[2,7,6],[1,2],[2,7,5],[2,7,6]]
\n\nOutput: [true,true,false]
\n\nExplanation:
\n\nx = 7
for query 0. A block of size at most 7 can be placed before x = 7
.x = 2
for query 2. Now, a block of size at most 5 can be placed before x = 7
, and a block of size at most 2 before x = 2
.\n
Constraints:
\n\n1 <= queries.length <= 15 * 104
2 <= queries[i].length <= 3
1 <= queries[i][0] <= 2
1 <= x, sz <= min(5 * 104, 3 * queries.length)
x
when the query is asked.d[x]
be the distance of the next obstacle after x
.",
@@ -118988,9 +119293,9 @@
"questionFrontendId": "3162",
"title": "Find the Number of Good Pairs I",
"content": "You are given 2 integer arrays nums1
and nums2
of lengths n
and m
respectively. You are also given a positive integer k
.
A pair (i, j)
is called good if nums1[i]
is divisible by nums2[j] * k
(0 <= i <= n - 1
, 0 <= j <= m - 1
).
Return the total number of good pairs.
\n\n\n
Example 1:
\n\nInput: nums1 = [1,3,4], nums2 = [1,3,4], k = 1
\n\nOutput: 5
\n\nExplanation:
\nThe 5 good pairs are(0, 0)
, (1, 0)
, (1, 1)
, (2, 0)
, and (2, 2)
.Example 2:
\n\nInput: nums1 = [1,2,4,12], nums2 = [2,4], k = 3
\n\nOutput: 2
\n\nExplanation:
\n\nThe 2 good pairs are (3, 0)
and (3, 1)
.
\n
Constraints:
\n\n1 <= n, m <= 50
1 <= nums1[i], nums2[j] <= 50
1 <= k <= 50
Given a string word
, compress it using the following algorithm:
comp
. While word
is not empty, use the following operation:\n\n\tword
made of a single character c
repeating at most 9 times.c
to comp
.Return the string comp
.
\n
Example 1:
\n\nInput: word = "abcde"
\n\nOutput: "1a1b1c1d1e"
\n\nExplanation:
\n\nInitially, comp = ""
. Apply the operation 5 times, choosing "a"
, "b"
, "c"
, "d"
, and "e"
as the prefix in each operation.
For each prefix, append "1"
followed by the character to comp
.
Example 2:
\n\nInput: word = "aaaaaaaaaaaaaabb"
\n\nOutput: "9a5a2b"
\n\nExplanation:
\n\nInitially, comp = ""
. Apply the operation 3 times, choosing "aaaaaaaaa"
, "aaaaa"
, and "bb"
as the prefix in each operation.
"aaaaaaaaa"
, append "9"
followed by "a"
to comp
."aaaaa"
, append "5"
followed by "a"
to comp
."bb"
, append "2"
followed by "b"
to comp
.\n
Constraints:
\n\n1 <= word.length <= 2 * 105
word
consists only of lowercase English letters.You are given 2 integer arrays nums1
and nums2
of lengths n
and m
respectively. You are also given a positive integer k
.
A pair (i, j)
is called good if nums1[i]
is divisible by nums2[j] * k
(0 <= i <= n - 1
, 0 <= j <= m - 1
).
Return the total number of good pairs.
\n\n\n
Example 1:
\n\nInput: nums1 = [1,3,4], nums2 = [1,3,4], k = 1
\n\nOutput: 5
\n\nExplanation:
\nThe 5 good pairs are(0, 0)
, (1, 0)
, (1, 1)
, (2, 0)
, and (2, 2)
.Example 2:
\n\nInput: nums1 = [1,2,4,12], nums2 = [2,4], k = 3
\n\nOutput: 2
\n\nExplanation:
\n\nThe 2 good pairs are (3, 0)
and (3, 1)
.
\n
Constraints:
\n\n1 <= n, m <= 105
1 <= nums1[i], nums2[j] <= 106
1 <= k <= 103
You are given an array nums
consisting of integers. You are also given a 2D array queries
, where queries[i] = [posi, xi]
.
For query i
, we first set nums[posi]
equal to xi
, then we calculate the answer to query i
which is the maximum sum of a subsequence of nums
where no two adjacent elements are selected.
Return the sum of the answers to all queries.
\n\nSince the final answer may be very large, return it modulo 109 + 7
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\nInput: nums = [3,5,9], queries = [[1,-2],[0,-3]]
\n\nOutput: 21
\n\nExplanation:
\nAfter the 1st query, nums = [3,-2,9]
and the maximum sum of a subsequence with non-adjacent elements is 3 + 9 = 12
.
\nAfter the 2nd query, nums = [-3,-2,9]
and the maximum sum of a subsequence with non-adjacent elements is 9.
Example 2:
\n\nInput: nums = [0,-1], queries = [[0,-5]]
\n\nOutput: 0
\n\nExplanation:
\nAfter the 1st query, nums = [-5,-1]
and the maximum sum of a subsequence with non-adjacent elements is 0 (choosing an empty subsequence).
\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
-105 <= nums[i] <= 105
1 <= queries.length <= 5 * 104
queries[i] == [posi, xi]
0 <= posi <= nums.length - 1
-105 <= xi <= 105
You are given a string s
. Simulate events at each second i
:
s[i] == 'E'
, a person enters the waiting room and takes one of the chairs in it.s[i] == 'L'
, a person leaves the waiting room, freeing up a chair.Return the minimum number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially empty.
\n\n\n
Example 1:
\n\nInput: s = "EEEEEEE"
\n\nOutput: 7
\n\nExplanation:
\n\nAfter each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.
\nExample 2:
\n\nInput: s = "ELELEEL"
\n\nOutput: 2
\n\nExplanation:
\n\nLet's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.
\nSecond | \n\t\t\tEvent | \n\t\t\tPeople in the Waiting Room | \n\t\t\tAvailable Chairs | \n\t\t
---|---|---|---|
0 | \n\t\t\tEnter | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
1 | \n\t\t\tLeave | \n\t\t\t0 | \n\t\t\t2 | \n\t\t
2 | \n\t\t\tEnter | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
3 | \n\t\t\tLeave | \n\t\t\t0 | \n\t\t\t2 | \n\t\t
4 | \n\t\t\tEnter | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
5 | \n\t\t\tEnter | \n\t\t\t2 | \n\t\t\t0 | \n\t\t
6 | \n\t\t\tLeave | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
Example 3:
\n\nInput: s = "ELEELEELLL"
\n\nOutput: 3
\n\nExplanation:
\n\nLet's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.
\nSecond | \n\t\t\tEvent | \n\t\t\tPeople in the Waiting Room | \n\t\t\tAvailable Chairs | \n\t\t
---|---|---|---|
0 | \n\t\t\tEnter | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
1 | \n\t\t\tLeave | \n\t\t\t0 | \n\t\t\t3 | \n\t\t
2 | \n\t\t\tEnter | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
3 | \n\t\t\tEnter | \n\t\t\t2 | \n\t\t\t1 | \n\t\t
4 | \n\t\t\tLeave | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
5 | \n\t\t\tEnter | \n\t\t\t2 | \n\t\t\t1 | \n\t\t
6 | \n\t\t\tEnter | \n\t\t\t3 | \n\t\t\t0 | \n\t\t
7 | \n\t\t\tLeave | \n\t\t\t2 | \n\t\t\t1 | \n\t\t
8 | \n\t\t\tLeave | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
9 | \n\t\t\tLeave | \n\t\t\t0 | \n\t\t\t3 | \n\t\t
\n
Constraints:
\n\n1 <= s.length <= 50
s
consists only of the letters 'E'
and 'L'
.s
represents a valid sequence of entries and exits.You are given a positive integer days
representing the total number of days an employee is available for work (starting from day 1). You are also given a 2D array meetings
of size n
where, meetings[i] = [start_i, end_i]
represents the starting and ending days of meeting i
(inclusive).
Return the count of days when the employee is available for work but no meetings are scheduled.
\n\nNote: The meetings may overlap.
\n\n\n
Example 1:
\n\nInput: days = 10, meetings = [[5,7],[1,3],[9,10]]
\n\nOutput: 2
\n\nExplanation:
\n\nThere is no meeting scheduled on the 4th and 8th days.
\nExample 2:
\n\nInput: days = 5, meetings = [[2,4],[1,3]]
\n\nOutput: 1
\n\nExplanation:
\n\nThere is no meeting scheduled on the 5th day.
\nExample 3:
\n\nInput: days = 6, meetings = [[1,6]]
\n\nOutput: 0
\n\nExplanation:
\n\nMeetings are scheduled for all working days.
\n\n
Constraints:
\n\n1 <= days <= 109
1 <= meetings.length <= 105
meetings[i].length == 2
1 <= meetings[i][0] <= meetings[i][1] <= days
You are given a string s
. It may contain any number of '*'
characters. Your task is to remove all '*'
characters.
While there is a '*'
, do the following operation:
'*'
and the smallest non-'*'
character to its left. If there are several smallest characters, you can delete any of them.Return the lexicographically smallest resulting string after removing all '*'
characters.
\n
Example 1:
\n\nInput: s = "aaba*"
\n\nOutput: "aab"
\n\nExplanation:
\n\nWe should delete one of the 'a'
characters with '*'
. If we choose s[3]
, s
becomes the lexicographically smallest.
Example 2:
\n\nInput: s = "abc"
\n\nOutput: "abc"
\n\nExplanation:
\n\nThere is no '*'
in the string.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters and '*'
.'*'
characters.You are given an array nums
and an integer k
. You need to find a subarray of nums
such that the absolute difference between k
and the bitwise OR
of the subarray elements is as small as possible. In other words, select a subarray nums[l..r]
such that |k - (nums[l] OR nums[l + 1] ... OR nums[r])|
is minimum.
Return the minimum possible value of the absolute difference.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,4,5], k = 3
\n\nOutput: 0
\n\nExplanation:
\n\nThe subarray nums[0..1]
has OR
value 3, which gives the minimum absolute difference |3 - 3| = 0
.
Example 2:
\n\nInput: nums = [1,3,1,3], k = 2
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarray nums[1..1]
has OR
value 3, which gives the minimum absolute difference |3 - 2| = 1
.
Example 3:
\n\nInput: nums = [1], k = 10
\n\nOutput: 9
\n\nExplanation:
\n\nThere is a single subarray with OR
value 1, which gives the minimum absolute difference |10 - 1| = 9
.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
You are given a string s
.
Your task is to remove all digits by doing this operation repeatedly:
\n\nReturn the resulting string after removing all digits.
\n\n\n
Example 1:
\n\nInput: s = "abc"
\n\nOutput: "abc"
\n\nExplanation:
\n\nThere is no digit in the string.
\nExample 2:
\n\nInput: s = "cb34"
\n\nOutput: ""
\n\nExplanation:
\n\nFirst, we apply the operation on s[2]
, and s
becomes "c4"
.
Then we apply the operation on s[1]
, and s
becomes ""
.
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of lowercase English letters and digits.You are given a string s
.
Your task is to remove all digits by doing this operation repeatedly:
\n\nReturn the resulting string after removing all digits.
\n\nNote that the operation cannot be performed on a digit that does not have any non-digit character to its left.
\n\n\n
Example 1:
\n\nInput: s = "abc"
\n\nOutput: "abc"
\n\nExplanation:
\n\nThere is no digit in the string.
\nExample 2:
\n\nInput: s = "cb34"
\n\nOutput: ""
\n\nExplanation:
\n\nFirst, we apply the operation on s[2]
, and s
becomes "c4"
.
Then we apply the operation on s[1]
, and s
becomes ""
.
\n
Constraints:
\n\n1 <= s.length <= 100
s
consists only of lowercase English letters and digits.A competition consists of n
players numbered from 0
to n - 1
.
You are given an integer array skills
of size n
and a positive integer k
, where skills[i]
is the skill level of player i
. All integers in skills
are unique.
All players are standing in a queue in order from player 0
to player n - 1
.
The competition process is as follows:
\n\nThe winner of the competition is the first player who wins k
games in a row.
Return the initial index of the winning player.
\n\n\n
Example 1:
\n\nInput: skills = [4,2,6,3,9], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nInitially, the queue of players is [0,1,2,3,4]
. The following process happens:
[0,2,3,4,1]
.[2,3,4,1,0]
.[2,4,1,0,3]
.Player 2 won k = 2
games in a row, so the winner is player 2.
Example 2:
\n\nInput: skills = [2,5,4], k = 3
\n\nOutput: 1
\n\nExplanation:
\n\nInitially, the queue of players is [0,1,2]
. The following process happens:
[1,2,0]
.[1,0,2]
.[1,2,0]
.Player 1 won k = 3
games in a row, so the winner is player 1.
\n
Constraints:
\n\nn == skills.length
2 <= n <= 105
1 <= k <= 109
1 <= skills[i] <= 106
skills
are unique.You are given an integer array nums
and a non-negative integer k
. A sequence of integers seq
is called good if there are at most k
indices i
in the range [0, seq.length - 2]
such that seq[i] != seq[i + 1]
.
Return the maximum possible length of a good subsequence of nums
.
\n
Example 1:
\n\nInput: nums = [1,2,1,1,3], k = 2
\n\nOutput: 4
\n\nExplanation:
\n\nThe maximum length subsequence is [1,2,1,1,3]
.
Example 2:
\n\nInput: nums = [1,2,3,4,5,1], k = 0
\n\nOutput: 2
\n\nExplanation:
\n\nThe maximum length subsequence is [1,2,3,4,5,1]
.
\n
Constraints:
\n\n1 <= nums.length <= 500
1 <= nums[i] <= 109
0 <= k <= min(nums.length, 25)
You are given an integer array nums
and a non-negative integer k
. A sequence of integers seq
is called good if there are at most k
indices i
in the range [0, seq.length - 2]
such that seq[i] != seq[i + 1]
.
Return the maximum possible length of a good subsequence of nums
.
\n
Example 1:
\n\nInput: nums = [1,2,1,1,3], k = 2
\n\nOutput: 4
\n\nExplanation:
\n\nThe maximum length subsequence is [1,2,1,1,3]
.
Example 2:
\n\nInput: nums = [1,2,3,4,5,1], k = 0
\n\nOutput: 2
\n\nExplanation:
\n\nThe maximum length subsequence is [1,2,3,4,5,1]
.
\n
Constraints:
\n\n1 <= nums.length <= 5 * 103
1 <= nums[i] <= 109
0 <= k <= min(50, nums.length)
You are given two positive integers n
and k
. There are n
children numbered from 0
to n - 1
standing in a queue in order from left to right.
Initially, child 0 holds a ball and the direction of passing the ball is towards the right direction. After each second, the child holding the ball passes it to the child next to them. Once the ball reaches either end of the line, i.e. child 0 or child n - 1
, the direction of passing is reversed.
Return the number of the child who receives the ball after k
seconds.
\n
Example 1:
\n\nInput: n = 3, k = 5
\n\nOutput: 1
\n\nExplanation:
\n\nTime elapsed | \n\t\t\tChildren | \n\t\t
---|---|
0 | \n\t\t\t[0, 1, 2] | \n\t\t
1 | \n\t\t\t[0, 1, 2] | \n\t\t
2 | \n\t\t\t[0, 1, 2] | \n\t\t
3 | \n\t\t\t[0, 1, 2] | \n\t\t
4 | \n\t\t\t[0, 1, 2] | \n\t\t
5 | \n\t\t\t[0, 1, 2] | \n\t\t
Example 2:
\n\nInput: n = 5, k = 6
\n\nOutput: 2
\n\nExplanation:
\n\nTime elapsed | \n\t\t\tChildren | \n\t\t
---|---|
0 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
1 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
2 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
3 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
4 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
5 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
6 | \n\t\t\t[0, 1, 2, 3, 4] | \n\t\t
Example 3:
\n\nInput: n = 4, k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nTime elapsed | \n\t\t\tChildren | \n\t\t
---|---|
0 | \n\t\t\t[0, 1, 2, 3] | \n\t\t
1 | \n\t\t\t[0, 1, 2, 3] | \n\t\t
2 | \n\t\t\t[0, 1, 2, 3] | \n\t\t
\n
Constraints:
\n\n2 <= n <= 50
1 <= k <= 50
\n
Note: This question is the same as 2582: Pass the Pillow.
\n", - "likes": 151, - "dislikes": 9, - "stats": "{\"totalAccepted\": \"51.4K\", \"totalSubmission\": \"83.1K\", \"totalAcceptedRaw\": 51414, \"totalSubmissionRaw\": 83074, \"acRate\": \"61.9%\"}", + "likes": 161, + "dislikes": 10, + "stats": "{\"totalAccepted\": \"54.1K\", \"totalSubmission\": \"88K\", \"totalAcceptedRaw\": 54145, \"totalSubmissionRaw\": 87986, \"acRate\": \"61.5%\"}", "similarQuestions": "[{\"title\": \"Find the Losers of the Circular Game\", \"titleSlug\": \"find-the-losers-of-the-circular-game\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "categoryTitle": "Algorithms", "hints": [ @@ -119593,9 +119904,9 @@ "questionFrontendId": "3179", "title": "Find the N-th Value After K Seconds", "content": "You are given two integers n
and k
.
Initially, you start with an array a
of n
integers where a[i] = 1
for all 0 <= i <= n - 1
. After each second, you simultaneously update each element to be the sum of all its preceding elements plus the element itself. For example, after one second, a[0]
remains the same, a[1]
becomes a[0] + a[1]
, a[2]
becomes a[0] + a[1] + a[2]
, and so on.
Return the value of a[n - 1]
after k
seconds.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 4, k = 5
\n\nOutput: 56
\n\nExplanation:
\n\nSecond | \n\t\t\tState After | \n\t\t
---|---|
0 | \n\t\t\t[1,1,1,1] | \n\t\t
1 | \n\t\t\t[1,2,3,4] | \n\t\t
2 | \n\t\t\t[1,3,6,10] | \n\t\t
3 | \n\t\t\t[1,4,10,20] | \n\t\t
4 | \n\t\t\t[1,5,15,35] | \n\t\t
5 | \n\t\t\t[1,6,21,56] | \n\t\t
Example 2:
\n\nInput: n = 5, k = 3
\n\nOutput: 35
\n\nExplanation:
\n\nSecond | \n\t\t\tState After | \n\t\t
---|---|
0 | \n\t\t\t[1,1,1,1,1] | \n\t\t
1 | \n\t\t\t[1,2,3,4,5] | \n\t\t
2 | \n\t\t\t[1,3,6,10,15] | \n\t\t
3 | \n\t\t\t[1,4,10,20,35] | \n\t\t
\n
Constraints:
\n\n1 <= n, k <= 1000
You are given an integer array rewardValues
of length n
, representing the values of rewards.
Initially, your total reward x
is 0, and all indices are unmarked. You are allowed to perform the following operation any number of times:
i
from the range [0, n - 1]
.rewardValues[i]
is greater than your current total reward x
, then add rewardValues[i]
to x
(i.e., x = x + rewardValues[i]
), and mark the index i
.Return an integer denoting the maximum total reward you can collect by performing the operations optimally.
\n\n\n
Example 1:
\n\nInput: rewardValues = [1,1,3,3]
\n\nOutput: 4
\n\nExplanation:
\n\nDuring the operations, we can choose to mark the indices 0 and 2 in order, and the total reward will be 4, which is the maximum.
\nExample 2:
\n\nInput: rewardValues = [1,6,4,3,2]
\n\nOutput: 11
\n\nExplanation:
\n\nMark the indices 0, 2, and 1 in order. The total reward will then be 11, which is the maximum.
\n\n
Constraints:
\n\n1 <= rewardValues.length <= 2000
1 <= rewardValues[i] <= 2000
You are given an integer array rewardValues
of length n
, representing the values of rewards.
Initially, your total reward x
is 0, and all indices are unmarked. You are allowed to perform the following operation any number of times:
i
from the range [0, n - 1]
.rewardValues[i]
is greater than your current total reward x
, then add rewardValues[i]
to x
(i.e., x = x + rewardValues[i]
), and mark the index i
.Return an integer denoting the maximum total reward you can collect by performing the operations optimally.
\n\n\n
Example 1:
\n\nInput: rewardValues = [1,1,3,3]
\n\nOutput: 4
\n\nExplanation:
\n\nDuring the operations, we can choose to mark the indices 0 and 2 in order, and the total reward will be 4, which is the maximum.
\nExample 2:
\n\nInput: rewardValues = [1,6,4,3,2]
\n\nOutput: 11
\n\nExplanation:
\n\nMark the indices 0, 2, and 1 in order. The total reward will then be 11, which is the maximum.
\n\n
Constraints:
\n\n1 <= rewardValues.length <= 5 * 104
1 <= rewardValues[i] <= 5 * 104
Given an integer array hours
representing times in hours, return an integer denoting the number of pairs i
, j
where i < j
and hours[i] + hours[j]
forms a complete day.
A complete day is defined as a time duration that is an exact multiple of 24 hours.
\n\nFor example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
\n\n\n
Example 1:
\n\nInput: hours = [12,12,30,24,24]
\n\nOutput: 2
\n\nExplanation:
\n\nThe pairs of indices that form a complete day are (0, 1)
and (3, 4)
.
Example 2:
\n\nInput: hours = [72,48,24,3]
\n\nOutput: 3
\n\nExplanation:
\n\nThe pairs of indices that form a complete day are (0, 1)
, (0, 2)
, and (1, 2)
.
\n
Constraints:
\n\n1 <= hours.length <= 100
1 <= hours[i] <= 109
Given an integer array hours
representing times in hours, return an integer denoting the number of pairs i
, j
where i < j
and hours[i] + hours[j]
forms a complete day.
A complete day is defined as a time duration that is an exact multiple of 24 hours.
\n\nFor example, 1 day is 24 hours, 2 days is 48 hours, 3 days is 72 hours, and so on.
\n\n\n
Example 1:
\n\nInput: hours = [12,12,30,24,24]
\n\nOutput: 2
\n\nExplanation: The pairs of indices that form a complete day are (0, 1)
and (3, 4)
.
Example 2:
\n\nInput: hours = [72,48,24,3]
\n\nOutput: 3
\n\nExplanation: The pairs of indices that form a complete day are (0, 1)
, (0, 2)
, and (1, 2)
.
\n
Constraints:
\n\n1 <= hours.length <= 5 * 105
1 <= hours[i] <= 109
A magician has various spells.
\n\nYou are given an array power
, where each element represents the damage of a spell. Multiple spells can have the same damage value.
It is a known fact that if a magician decides to cast a spell with a damage of power[i]
, they cannot cast any spell with a damage of power[i] - 2
, power[i] - 1
, power[i] + 1
, or power[i] + 2
.
Each spell can be cast only once.
\n\nReturn the maximum possible total damage that a magician can cast.
\n\n\n
Example 1:
\n\nInput: power = [1,1,3,4]
\n\nOutput: 6
\n\nExplanation:
\n\nThe maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.
\nExample 2:
\n\nInput: power = [7,1,6,6]
\n\nOutput: 13
\n\nExplanation:
\n\nThe maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.
\n\n
Constraints:
\n\n1 <= power.length <= 105
1 <= power[i] <= 109
A peak in an array arr
is an element that is greater than its previous and next element in arr
.
You are given an integer array nums
and a 2D integer array queries
.
You have to process queries of two types:
\n\nqueries[i] = [1, li, ri]
, determine the count of peak elements in the subarray nums[li..ri]
.queries[i] = [2, indexi, vali]
, change nums[indexi]
to vali
.Return an array answer
containing the results of the queries of the first type in order.
Notes:
\n\n\n
Example 1:
\n\nInput: nums = [3,1,4,2,5], queries = [[2,3,4],[1,0,4]]
\n\nOutput: [0]
\n\nExplanation:
\n\nFirst query: We change nums[3]
to 4 and nums
becomes [3,1,4,4,5]
.
Second query: The number of peaks in the [3,1,4,4,5]
is 0.
Example 2:
\n\nInput: nums = [4,1,4,2,1,5], queries = [[2,2,4],[1,0,2],[1,0,4]]
\n\nOutput: [0,1]
\n\nExplanation:
\n\nFirst query: nums[2]
should become 4, but it is already set to 4.
Second query: The number of peaks in the [4,1,4]
is 0.
Third query: The second 4 is a peak in the [4,1,4,2,1]
.
\n
Constraints:
\n\n3 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i][0] == 1
or queries[i][0] == 2
i
that:\n\tqueries[i][0] == 1
: 0 <= queries[i][1] <= queries[i][2] <= nums.length - 1
queries[i][0] == 2
: 0 <= queries[i][1] <= nums.length - 1
, 1 <= queries[i][2] <= 105
You are given an integer array nums
. In one operation, you can add or subtract 1 from any element of nums
.
Return the minimum number of operations to make all elements of nums
divisible by 3.
\n
Example 1:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 3
\n\nExplanation:
\n\nAll array elements can be made divisible by 3 using 3 operations:
\n\nExample 2:
\n\nInput: nums = [3,6,9]
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= nums.length <= 50
1 <= nums[i] <= 50
You are given a binary array nums
.
You can do the following operation on the array any number of times (possibly zero):
\n\nFlipping an element means changing its value from 0 to 1, and from 1 to 0.
\n\nReturn the minimum number of operations required to make all elements in nums
equal to 1. If it is impossible, return -1.
\n
Example 1:
\n\nInput: nums = [0,1,1,1,0,0]
\n\nOutput: 3
\n\nExplanation:
\nWe can do the following operations:
nums = [1,0,0,1,0,0]
.nums = [1,1,1,0,0,0]
.nums = [1,1,1,1,1,1]
.Example 2:
\n\nInput: nums = [0,1,1,1]
\n\nOutput: -1
\n\nExplanation:
\nIt is impossible to make all elements equal to 1.
\n
Constraints:
\n\n3 <= nums.length <= 105
0 <= nums[i] <= 1
You are given a binary array nums
.
You can do the following operation on the array any number of times (possibly zero):
\n\ni
from the array and flip all the elements from index i
to the end of the array.Flipping an element means changing its value from 0 to 1, and from 1 to 0.
\n\nReturn the minimum number of operations required to make all elements in nums
equal to 1.
\n
Example 1:
\n\nInput: nums = [0,1,1,0,1]
\n\nOutput: 4
\n\nExplanation:
\nWe can do the following operations:
i = 1
. The resulting array will be nums = [0,0,0,1,0]
.i = 0
. The resulting array will be nums = [1,1,1,0,1]
.i = 4
. The resulting array will be nums = [1,1,1,0,0]
.i = 3
. The resulting array will be nums = [1,1,1,1,1]
.Example 2:
\n\nInput: nums = [1,0,0,0]
\n\nOutput: 1
\n\nExplanation:
\nWe can do the following operation:
i = 1
. The resulting array will be nums = [1,1,1,1]
.\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 1
You are given an integer n
and a 2D array requirements
, where requirements[i] = [endi, cnti]
represents the end index and the inversion count of each requirement.
A pair of indices (i, j)
from an integer array nums
is called an inversion if:
i < j
and nums[i] > nums[j]
Return the number of permutations perm
of [0, 1, 2, ..., n - 1]
such that for all requirements[i]
, perm[0..endi]
has exactly cnti
inversions.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 3, requirements = [[2,2],[0,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nThe two permutations are:
\n\n[2, 0, 1]
\n\n\t[2, 0, 1]
has inversions (0, 1)
and (0, 2)
.[2]
has 0 inversions.[1, 2, 0]
\n\t[1, 2, 0]
has inversions (0, 2)
and (1, 2)
.[1]
has 0 inversions.Example 2:
\n\nInput: n = 3, requirements = [[2,2],[1,1],[0,0]]
\n\nOutput: 1
\n\nExplanation:
\n\nThe only satisfying permutation is [2, 0, 1]
:
[2, 0, 1]
has inversions (0, 1)
and (0, 2)
.[2, 0]
has an inversion (0, 1)
.[2]
has 0 inversions.Example 3:
\n\nInput: n = 2, requirements = [[0,0],[1,0]]
\n\nOutput: 1
\n\nExplanation:
\n\nThe only satisfying permutation is [0, 1]
:
[0]
has 0 inversions.[0, 1]
has an inversion (0, 1)
.\n
Constraints:
\n\n2 <= n <= 300
1 <= requirements.length <= n
requirements[i] = [endi, cnti]
0 <= endi <= n - 1
0 <= cnti <= 400
i
such that endi == n - 1
.endi
are unique.You have an array of floating point numbers averages
which is initially empty. You are given an array nums
of n
integers where n
is even.
You repeat the following procedure n / 2
times:
minElement
, and the largest element maxElement
, from nums
.(minElement + maxElement) / 2
to averages
.Return the minimum element in averages
.
\n
Example 1:
\n\nInput: nums = [7,8,3,4,15,13,4,1]
\n\nOutput: 5.5
\n\nExplanation:
\n\nstep | \n\t\t\tnums | \n\t\t\taverages | \n\t\t
---|---|---|
0 | \n\t\t\t[7,8,3,4,15,13,4,1] | \n\t\t\t[] | \n\t\t
1 | \n\t\t\t[7,8,3,4,13,4] | \n\t\t\t[8] | \n\t\t
2 | \n\t\t\t[7,8,4,4] | \n\t\t\t[8,8] | \n\t\t
3 | \n\t\t\t[7,4] | \n\t\t\t[8,8,6] | \n\t\t
4 | \n\t\t\t[] | \n\t\t\t[8,8,6,5.5] | \n\t\t
Example 2:
\n\nInput: nums = [1,9,8,3,10,5]
\n\nOutput: 5.5
\n\nExplanation:
\n\nstep | \n\t\t\tnums | \n\t\t\taverages | \n\t\t
---|---|---|
0 | \n\t\t\t[1,9,8,3,10,5] | \n\t\t\t[] | \n\t\t
1 | \n\t\t\t[9,8,3,5] | \n\t\t\t[5.5] | \n\t\t
2 | \n\t\t\t[8,5] | \n\t\t\t[5.5,6] | \n\t\t
3 | \n\t\t\t[] | \n\t\t\t[5.5,6,6.5] | \n\t\t
Example 3:
\n\nInput: nums = [1,2,3,7,8,9]
\n\nOutput: 5.0
\n\nExplanation:
\n\nstep | \n\t\t\tnums | \n\t\t\taverages | \n\t\t
---|---|---|
0 | \n\t\t\t[1,2,3,7,8,9] | \n\t\t\t[] | \n\t\t
1 | \n\t\t\t[2,3,7,8] | \n\t\t\t[5] | \n\t\t
2 | \n\t\t\t[3,7] | \n\t\t\t[5,5] | \n\t\t
3 | \n\t\t\t[] | \n\t\t\t[5,5,5] | \n\t\t
\n
Constraints:
\n\n2 <= n == nums.length <= 50
n
is even.1 <= nums[i] <= 50
You are given a 2D binary array grid
. Find a rectangle with horizontal and vertical sides with the smallest area, such that all the 1's in grid
lie inside this rectangle.
Return the minimum possible area of the rectangle.
\n\n\n
Example 1:
\n\nInput: grid = [[0,1,0],[1,0,1]]
\n\nOutput: 6
\n\nExplanation:
\n\nThe smallest rectangle has a height of 2 and a width of 3, so it has an area of 2 * 3 = 6
.
Example 2:
\n\nInput: grid = [[1,0],[0,0]]
\n\nOutput: 1
\n\nExplanation:
\n\nThe smallest rectangle has both height and width 1, so its area is 1 * 1 = 1
.
\n
Constraints:
\n\n1 <= grid.length, grid[i].length <= 1000
grid[i][j]
is either 0 or 1.grid
.You are given an integer array nums
with length n
.
The cost of a subarray nums[l..r]
, where 0 <= l <= r < n
, is defined as:
cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (−1)r − l
Your task is to split nums
into subarrays such that the total cost of the subarrays is maximized, ensuring each element belongs to exactly one subarray.
Formally, if nums
is split into k
subarrays, where k > 1
, at indices i1, i2, ..., ik − 1
, where 0 <= i1 < i2 < ... < ik - 1 < n - 1
, then the total cost will be:
cost(0, i1) + cost(i1 + 1, i2) + ... + cost(ik − 1 + 1, n − 1)
Return an integer denoting the maximum total cost of the subarrays after splitting the array optimally.
\n\nNote: If nums
is not split into subarrays, i.e. k = 1
, the total cost is simply cost(0, n - 1)
.
\n
Example 1:
\n\nInput: nums = [1,-2,3,4]
\n\nOutput: 10
\n\nExplanation:
\n\nOne way to maximize the total cost is by splitting [1, -2, 3, 4]
into subarrays [1, -2, 3]
and [4]
. The total cost will be (1 + 2 + 3) + 4 = 10
.
Example 2:
\n\nInput: nums = [1,-1,1,-1]
\n\nOutput: 4
\n\nExplanation:
\n\nOne way to maximize the total cost is by splitting [1, -1, 1, -1]
into subarrays [1, -1]
and [1, -1]
. The total cost will be (1 + 1) + (1 + 1) = 4
.
Example 3:
\n\nInput: nums = [0]
\n\nOutput: 0
\n\nExplanation:
\n\nWe cannot split the array further, so the answer is 0.
\nExample 4:
\n\nInput: nums = [1,-1]
\n\nOutput: 2
\n\nExplanation:
\n\nSelecting the whole array gives a total cost of 1 + 1 = 2
, which is the maximum.
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
You are given a 2D binary array grid
. You need to find 3 non-overlapping rectangles having non-zero areas with horizontal and vertical sides such that all the 1's in grid
lie inside these rectangles.
Return the minimum possible sum of the area of these rectangles.
\n\nNote that the rectangles are allowed to touch.
\n\n\n
Example 1:
\n\nInput: grid = [[1,0,1],[1,1,1]]
\n\nOutput: 5
\n\nExplanation:
\n\n(0, 0)
and (1, 0)
are covered by a rectangle of area 2.(0, 2)
and (1, 2)
are covered by a rectangle of area 2.(1, 1)
is covered by a rectangle of area 1.Example 2:
\n\nInput: grid = [[1,0,1,0],[0,1,0,1]]
\n\nOutput: 5
\n\nExplanation:
\n\n(0, 0)
and (0, 2)
are covered by a rectangle of area 3.(1, 1)
is covered by a rectangle of area 1.(1, 3)
is covered by a rectangle of area 1.\n
Constraints:
\n\n1 <= grid.length, grid[i].length <= 30
grid[i][j]
is either 0 or 1.grid
.You are given two integers red
and blue
representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1st row will have 1 ball, the 2nd row will have 2 balls, the 3rd row will have 3 balls, and so on.
All the balls in a particular row should be the same color, and adjacent rows should have different colors.
\n\nReturn the maximum height of the triangle that can be achieved.
\n\n\n
Example 1:
\n\nInput: red = 2, blue = 4
\n\nOutput: 3
\n\nExplanation:
\n\nThe only possible arrangement is shown above.
\nExample 2:
\n\nInput: red = 2, blue = 1
\n\nOutput: 2
\n\nExplanation:
\n\n
\nThe only possible arrangement is shown above.
Example 3:
\n\nInput: red = 1, blue = 1
\n\nOutput: 1
\nExample 4:
\n\nInput: red = 10, blue = 1
\n\nOutput: 2
\n\nExplanation:
\n\n
\nThe only possible arrangement is shown above.
\n
Constraints:
\n\n1 <= red, blue <= 100
nums
.\nA subsequence sub
of nums
with length x
is called valid if it satisfies:
(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.
Return the length of the longest valid subsequence of nums
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 4
\n\nExplanation:
\n\nThe longest valid subsequence is [1, 2, 3, 4]
.
Example 2:
\n\nInput: nums = [1,2,1,1,2,1,2]
\n\nOutput: 6
\n\nExplanation:
\n\nThe longest valid subsequence is [1, 2, 1, 2, 1, 2]
.
Example 3:
\n\nInput: nums = [1,3]
\n\nOutput: 2
\n\nExplanation:
\n\nThe longest valid subsequence is [1, 3]
.
\n
Constraints:
\n\n2 <= nums.length <= 2 * 105
1 <= nums[i] <= 107
nums
and a positive integer k
.\nA subsequence sub
of nums
with length x
is called valid if it satisfies:
(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.
nums
.\n\n
Example 1:
\n\nInput: nums = [1,2,3,4,5], k = 2
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest valid subsequence is [1, 2, 3, 4, 5]
.
Example 2:
\n\nInput: nums = [1,4,2,3,1,4], k = 3
\n\nOutput: 4
\n\nExplanation:
\n\nThe longest valid subsequence is [1, 4, 1, 4]
.
\n
Constraints:
\n\n2 <= nums.length <= 103
1 <= nums[i] <= 107
1 <= k <= 103
There exist two undirected trees with n
and m
nodes, numbered from 0
to n - 1
and from 0
to m - 1
, respectively. You are given two 2D integer arrays edges1
and edges2
of lengths n - 1
and m - 1
, respectively, where edges1[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the first tree and edges2[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the second tree.
You must connect one node from the first tree with another node from the second tree with an edge.
\n\nReturn the minimum possible diameter of the resulting tree.
\n\nThe diameter of a tree is the length of the longest path between any two nodes in the tree.
\n\n\n
Example 1:
Input: edges1 = [[0,1],[0,2],[0,3]], edges2 = [[0,1]]
\n\nOutput: 3
\n\nExplanation:
\n\nWe can obtain a tree of diameter 3 by connecting node 0 from the first tree with any node from the second tree.
\nExample 2:
\nInput: edges1 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]], edges2 = [[0,1],[0,2],[0,3],[2,4],[2,5],[3,6],[2,7]]
\n\nOutput: 5
\n\nExplanation:
\n\nWe can obtain a tree of diameter 5 by connecting node 0 from the first tree with node 0 from the second tree.
\n\n
Constraints:
\n\n1 <= n, m <= 105
edges1.length == n - 1
edges2.length == m - 1
edges1[i].length == edges2[i].length == 2
edges1[i] = [ai, bi]
0 <= ai, bi < n
edges2[i] = [ui, vi]
0 <= ui, vi < m
edges1
and edges2
represent valid trees.There is a circle of red and blue tiles. You are given an array of integers colors
. The color of tile i
is represented by colors[i]
:
colors[i] == 0
means that tile i
is red.colors[i] == 1
means that tile i
is blue.Every 3 contiguous tiles in the circle with alternating colors (the middle tile has a different color from its left and right tiles) is called an alternating group.
\n\nReturn the number of alternating groups.
\n\nNote that since colors
represents a circle, the first and the last tiles are considered to be next to each other.
\n
Example 1:
\n\nInput: colors = [1,1,1]
\n\nOutput: 0
\n\nExplanation:
\n\nExample 2:
\n\nInput: colors = [0,1,0,0,1]
\n\nOutput: 3
\n\nExplanation:
\n\nAlternating groups:
\n\n\n
Constraints:
\n\n3 <= colors.length <= 100
0 <= colors[i] <= 1
You are given an integer array enemyEnergies
denoting the energy values of various enemies.
You are also given an integer currentEnergy
denoting the amount of energy you have initially.
You start with 0 points, and all the enemies are unmarked initially.
\n\nYou can perform either of the following operations zero or multiple times to gain points:
\n\ni
, such that currentEnergy >= enemyEnergies[i]
. By choosing this option:\n\n\tcurrentEnergy = currentEnergy - enemyEnergies[i]
.i
. By choosing this option:\n\tcurrentEnergy = currentEnergy + enemyEnergies[i]
.i
is marked.Return an integer denoting the maximum points you can get in the end by optimally performing operations.
\n\n\n
Example 1:
\n\nInput: enemyEnergies = [3,2,2], currentEnergy = 2
\n\nOutput: 3
\n\nExplanation:
\n\nThe following operations can be performed to get 3 points, which is the maximum:
\n\npoints
increases by 1, and currentEnergy
decreases by 2. So, points = 1
, and currentEnergy = 0
.currentEnergy
increases by 3, and enemy 0 is marked. So, points = 1
, currentEnergy = 3
, and marked enemies = [0]
.points
increases by 1, and currentEnergy
decreases by 2. So, points = 2
, currentEnergy = 1
, and marked enemies = [0]
.currentEnergy
increases by 2, and enemy 2 is marked. So, points = 2
, currentEnergy = 3
, and marked enemies = [0, 2]
.points
increases by 1, and currentEnergy
decreases by 2. So, points = 3
, currentEnergy = 1
, and marked enemies = [0, 2]
.Example 2:
\n\nInput: enemyEnergies = [2], currentEnergy = 10
\n\nOutput: 5
\n\nExplanation:
\n\nPerforming the first operation 5 times on enemy 0 results in the maximum number of points.
\n\n
Constraints:
\n\n1 <= enemyEnergies.length <= 105
1 <= enemyEnergies[i] <= 109
0 <= currentEnergy <= 109
There is a circle of red and blue tiles. You are given an array of integers colors
and an integer k
. The color of tile i
is represented by colors[i]
:
colors[i] == 0
means that tile i
is red.colors[i] == 1
means that tile i
is blue.An alternating group is every k
contiguous tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its left and right tiles).
Return the number of alternating groups.
\n\nNote that since colors
represents a circle, the first and the last tiles are considered to be next to each other.
\n
Example 1:
\n\nInput: colors = [0,1,0,1,0], k = 3
\n\nOutput: 3
\n\nExplanation:
\n\nAlternating groups:
\n\nExample 2:
\n\nInput: colors = [0,1,0,0,1,0,1], k = 6
\n\nOutput: 2
\n\nExplanation:
\n\nAlternating groups:
\n\nExample 3:
\n\nInput: colors = [1,1,0,1], k = 4
\n\nOutput: 0
\n\nExplanation:
\n\n\n
Constraints:
\n\n3 <= colors.length <= 105
0 <= colors[i] <= 1
3 <= k <= colors.length
Given an array of integers nums
and an integer k
, return the number of subarrays of nums
where the bitwise AND
of the elements of the subarray equals k
.
\n
Example 1:
\n\nInput: nums = [1,1,1], k = 1
\n\nOutput: 6
\n\nExplanation:
\n\nAll subarrays contain only 1's.
\nExample 2:
\n\nInput: nums = [1,1,2], k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nSubarrays having an AND
value of 1 are: [1,1,2]
, [1,1,2]
, [1,1,2]
.
Example 3:
\n\nInput: nums = [1,2,3], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nSubarrays having an AND
value of 2 are: [1,2,3]
, [1,2,3]
.
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i], k <= 109
You are given a string s
and an integer k
. Encrypt the string using the following algorithm:
c
in s
, replace c
with the kth
character after c
in the string (in a cyclic manner).Return the encrypted string.
\n\n\n
Example 1:
\n\nInput: s = "dart", k = 3
\n\nOutput: "tdar"
\n\nExplanation:
\n\ni = 0
, the 3rd character after 'd'
is 't'
.i = 1
, the 3rd character after 'a'
is 'd'
.i = 2
, the 3rd character after 'r'
is 'a'
.i = 3
, the 3rd character after 't'
is 'r'
.Example 2:
\n\nInput: s = "aaa", k = 1
\n\nOutput: "aaa"
\n\nExplanation:
\n\nAs all the characters are the same, the encrypted string will also be the same.
\n\n
Constraints:
\n\n1 <= s.length <= 100
1 <= k <= 104
s
consists only of lowercase English letters.You are given a positive integer n
.
A binary string x
is valid if all substrings of x
of length 2 contain at least one "1"
.
Return all valid strings with length n
, in any order.
\n
Example 1:
\n\nInput: n = 3
\n\nOutput: ["010","011","101","110","111"]
\n\nExplanation:
\n\nThe valid strings of length 3 are: "010"
, "011"
, "101"
, "110"
, and "111"
.
Example 2:
\n\nInput: n = 1
\n\nOutput: ["0","1"]
\n\nExplanation:
\n\nThe valid strings of length 1 are: "0"
and "1"
.
\n
Constraints:
\n\n1 <= n <= 18
Given a 2D character matrix grid
, where grid[i][j]
is either 'X'
, 'Y'
, or '.'
, return the number of submatrices that contain:
grid[0][0]
'X'
and 'Y'
.'X'
.\n
Example 1:
\n\nInput: grid = [["X","Y","."],["Y",".","."]]
\n\nOutput: 3
\n\nExplanation:
\n\nExample 2:
\n\nInput: grid = [["X","X"],["X","Y"]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo submatrix has an equal frequency of 'X'
and 'Y'
.
Example 3:
\n\nInput: grid = [[".","."],[".","."]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo submatrix has at least one 'X'
.
\n
Constraints:
\n\n1 <= grid.length, grid[i].length <= 1000
grid[i][j]
is either 'X'
, 'Y'
, or '.'
.You are given a string target
, an array of strings words
, and an integer array costs
, both arrays of the same length.
Imagine an empty string s
.
You can perform the following operation any number of times (including zero):
\n\ni
in the range [0, words.length - 1]
.words[i]
to s
.costs[i]
.Return the minimum cost to make s
equal to target
. If it's not possible, return -1
.
\n
Example 1:
\n\nInput: target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]
\n\nOutput: 7
\n\nExplanation:
\n\nThe minimum cost can be achieved by performing the following operations:
\n\n"abc"
to s
at a cost of 1, resulting in s = "abc"
."d"
to s
at a cost of 1, resulting in s = "abcd"
."ef"
to s
at a cost of 5, resulting in s = "abcdef"
.Example 2:
\n\nInput: target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]
\n\nOutput: -1
\n\nExplanation:
\n\nIt is impossible to make s
equal to target
, so we return -1.
\n
Constraints:
\n\n1 <= target.length <= 5 * 104
1 <= words.length == costs.length <= 5 * 104
1 <= words[i].length <= target.length
words[i].length
is less than or equal to 5 * 104
.target
and words[i]
consist only of lowercase English letters.1 <= costs[i] <= 104
Given a string s
containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s
with the same parity at most once.
Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.
\n\n\n
Example 1:
\n\nInput: s = "45320"
\n\nOutput: "43520"
\n\nExplanation:
\n\ns[1] == '5'
and s[2] == '3'
both have the same parity, and swapping them results in the lexicographically smallest string.
Example 2:
\n\nInput: s = "001"
\n\nOutput: "001"
\n\nExplanation:
\n\nThere is no need to perform a swap because s
is already the lexicographically smallest.
\n
Constraints:
\n\n2 <= s.length <= 100
s
consists only of digits.You are given an array of integers nums
and the head
of a linked list. Return the head
of the modified linked list after removing all nodes from the linked list that have a value that exists in nums
.
\n
Example 1:
\n\nInput: nums = [1,2,3], head = [1,2,3,4,5]
\n\nOutput: [4,5]
\n\nExplanation:
\n\nRemove the nodes with values 1, 2, and 3.
\nExample 2:
\n\nInput: nums = [1], head = [1,2,1,2,1,2]
\n\nOutput: [2,2,2]
\n\nExplanation:
\n\nRemove the nodes with value 1.
\nExample 3:
\n\nInput: nums = [5], head = [1,2,3,4]
\n\nOutput: [1,2,3,4]
\n\nExplanation:
\n\nNo node has value 5.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
nums
are unique.[1, 105]
.1 <= Node.val <= 105
nums
.There is an m x n
cake that needs to be cut into 1 x 1
pieces.
You are given integers m
, n
, and two arrays:
horizontalCut
of size m - 1
, where horizontalCut[i]
represents the cost to cut along the horizontal line i
.verticalCut
of size n - 1
, where verticalCut[j]
represents the cost to cut along the vertical line j
.In one operation, you can choose any piece of cake that is not yet a 1 x 1
square and perform one of the following cuts:
i
at a cost of horizontalCut[i]
.j
at a cost of verticalCut[j]
.After the cut, the piece of cake is divided into two distinct pieces.
\n\nThe cost of a cut depends only on the initial cost of the line and does not change.
\n\nReturn the minimum total cost to cut the entire cake into 1 x 1
pieces.
\n
Example 1:
\n\nInput: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]
\n\nOutput: 13
\n\nExplanation:
\n\n3 x 1
subgrid with cost 1.3 x 1
subgrid with cost 1.2 x 1
subgrid with cost 3.2 x 1
subgrid with cost 3.The total cost is 5 + 1 + 1 + 3 + 3 = 13
.
Example 2:
\n\nInput: m = 2, n = 2, horizontalCut = [7], verticalCut = [4]
\n\nOutput: 15
\n\nExplanation:
\n\n1 x 2
subgrid with cost 4.1 x 2
subgrid with cost 4.The total cost is 7 + 4 + 4 = 15
.
\n
Constraints:
\n\n1 <= m, n <= 20
horizontalCut.length == m - 1
verticalCut.length == n - 1
1 <= horizontalCut[i], verticalCut[i] <= 103
There is an m x n
cake that needs to be cut into 1 x 1
pieces.
You are given integers m
, n
, and two arrays:
horizontalCut
of size m - 1
, where horizontalCut[i]
represents the cost to cut along the horizontal line i
.verticalCut
of size n - 1
, where verticalCut[j]
represents the cost to cut along the vertical line j
.In one operation, you can choose any piece of cake that is not yet a 1 x 1
square and perform one of the following cuts:
i
at a cost of horizontalCut[i]
.j
at a cost of verticalCut[j]
.After the cut, the piece of cake is divided into two distinct pieces.
\n\nThe cost of a cut depends only on the initial cost of the line and does not change.
\n\nReturn the minimum total cost to cut the entire cake into 1 x 1
pieces.
\n
Example 1:
\n\nInput: m = 3, n = 2, horizontalCut = [1,3], verticalCut = [5]
\n\nOutput: 13
\n\nExplanation:
\n\n3 x 1
subgrid with cost 1.3 x 1
subgrid with cost 1.2 x 1
subgrid with cost 3.2 x 1
subgrid with cost 3.The total cost is 5 + 1 + 1 + 3 + 3 = 13
.
Example 2:
\n\nInput: m = 2, n = 2, horizontalCut = [7], verticalCut = [4]
\n\nOutput: 15
\n\nExplanation:
\n\n1 x 2
subgrid with cost 4.1 x 2
subgrid with cost 4.The total cost is 7 + 4 + 4 = 15
.
\n
Constraints:
\n\n1 <= m, n <= 105
horizontalCut.length == m - 1
verticalCut.length == n - 1
1 <= horizontalCut[i], verticalCut[i] <= 103
Table: transactions
\n+------------------+------+\n| Column Name | Type | \n+------------------+------+\n| transaction_id | int |\n| amount | int |\n| transaction_date | date |\n+------------------+------+\nThe transactions_id column uniquely identifies each row in this table.\nEach row of this table contains the transaction id, amount and transaction date.\n\n\n
Write a solution to find the sum of amounts for odd and even transactions for each day. If there are no odd or even transactions for a specific date, display as 0
.
Return the result table ordered by transaction_date
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\ntransactions
table:
\n+----------------+--------+------------------+\n| transaction_id | amount | transaction_date |\n+----------------+--------+------------------+\n| 1 | 150 | 2024-07-01 |\n| 2 | 200 | 2024-07-01 |\n| 3 | 75 | 2024-07-01 |\n| 4 | 300 | 2024-07-02 |\n| 5 | 50 | 2024-07-02 |\n| 6 | 120 | 2024-07-03 |\n+----------------+--------+------------------+\n\n\n
Output:
\n\n\n+------------------+---------+----------+\n| transaction_date | odd_sum | even_sum |\n+------------------+---------+----------+\n| 2024-07-01 | 75 | 350 |\n| 2024-07-02 | 0 | 350 |\n| 2024-07-03 | 0 | 120 |\n+------------------+---------+----------+\n\n\n
Explanation:
\n\nNote: The output table is ordered by transaction_date
in ascending order.
You are given two positive integers x
and y
, denoting the number of coins with values 75 and 10 respectively.
Alice and Bob are playing a game. Each turn, starting with Alice, the player must pick up coins with a total value 115. If the player is unable to do so, they lose the game.
\n\nReturn the name of the player who wins the game if both players play optimally.
\n\n\n
Example 1:
\n\nInput: x = 2, y = 7
\n\nOutput: "Alice"
\n\nExplanation:
\n\nThe game ends in a single turn:
\n\nExample 2:
\n\nInput: x = 4, y = 11
\n\nOutput: "Bob"
\n\nExplanation:
\n\nThe game ends in 2 turns:
\n\n\n
Constraints:
\n\n1 <= x, y <= 100
You are given a string s
.
You can perform the following process on s
any number of times:
i
in the string such that there is at least one character to the left of index i
that is equal to s[i]
, and at least one character to the right that is also equal to s[i]
.i
that is equal to s[i]
.i
that is equal to s[i]
.Return the minimum length of the final string s
that you can achieve.
\n
Example 1:
\n\nInput: s = "abaacbcbb"
\n\nOutput: 5
\n\nExplanation:
\nWe do the following operations:
s = "bacbcbb"
.s = "acbcb"
.Example 2:
\n\nInput: s = "aa"
\n\nOutput: 2
\n\nExplanation:
\nWe cannot perform any operations, so we return the length of the original string.
\n
Constraints:
\n\n1 <= s.length <= 2 * 105
s
consists only of lowercase English letters.You are given a string s
.
You can perform the following process on s
any number of times:
i
in the string such that there is at least one character to the left of index i
that is equal to s[i]
, and at least one character to the right that is also equal to s[i]
.s[i]
located to the left of i
.s[i]
located to the right of i
.Return the minimum length of the final string s
that you can achieve.
\n
Example 1:
\n\nInput: s = "abaacbcbb"
\n\nOutput: 5
\n\nExplanation:
\nWe do the following operations:
s = "bacbcbb"
.s = "acbcb"
.Example 2:
\n\nInput: s = "aa"
\n\nOutput: 2
\n\nExplanation:
\nWe cannot perform any operations, so we return the length of the original string.
\n
Constraints:
\n\n1 <= s.length <= 2 * 105
s
consists only of lowercase English letters.You are given an integer array nums
of size n
where n
is even, and an integer k
.
You can perform some changes on the array, where in one change you can replace any element in the array with any integer in the range from 0
to k
.
You need to perform some changes (possibly none) such that the final array satisfies the following condition:
\n\nX
such that abs(a[i] - a[n - i - 1]) = X
for all (0 <= i < n)
.Return the minimum number of changes required to satisfy the above condition.
\n\n\n
Example 1:
\n\nInput: nums = [1,0,1,2,4,3], k = 4
\n\nOutput: 2
\n\nExplanation:
\nWe can perform the following changes:
nums[1]
by 2. The resulting array is nums = [1,2,1,2,4,3]
.nums[3]
by 3. The resulting array is nums = [1,2,1,3,4,3]
.The integer X
will be 2.
Example 2:
\n\nInput: nums = [0,1,2,3,3,6,5,4], k = 6
\n\nOutput: 2
\n\nExplanation:
\nWe can perform the following operations:
nums[3]
by 0. The resulting array is nums = [0,1,2,0,3,6,5,4]
.nums[4]
by 4. The resulting array is nums = [0,1,2,0,4,6,5,4]
.The integer X
will be 4.
\n
Constraints:
\n\n2 <= n == nums.length <= 105
n
is even.0 <= nums[i] <= k <= 105
You are given a 2D matrix grid
of size n x n
. Initially, all cells of the grid are colored white. In one operation, you can select any cell of indices (i, j)
, and color black all the cells of the jth
column starting from the top row down to the ith
row.
The grid score is the sum of all grid[i][j]
such that cell (i, j)
is white and it has a horizontally adjacent black cell.
Return the maximum score that can be achieved after some number of operations.
\n\n\n
Example 1:
\n\nInput: grid = [[0,0,0,0,0],[0,0,3,0,0],[0,1,0,0,0],[5,0,0,3,0],[0,0,0,0,2]]
\n\nOutput: 11
\n\nExplanation:
\nIn the first operation, we color all cells in column 1 down to row 3, and in the second operation, we color all cells in column 4 down to the last row. The score of the resulting grid is grid[3][0] + grid[1][2] + grid[3][3]
which is equal to 11.
Example 2:
\n\nInput: grid = [[10,9,0,0,15],[7,1,0,8,0],[5,20,0,11,0],[0,0,0,1,2],[8,12,1,10,3]]
\n\nOutput: 94
\n\nExplanation:
\nWe perform operations on 1, 2, and 3 down to rows 1, 4, and 0, respectively. The score of the resulting grid is grid[0][0] + grid[1][0] + grid[2][1] + grid[4][1] + grid[1][3] + grid[2][3] + grid[3][3] + grid[4][3] + grid[0][4]
which is equal to 94.
\n
Constraints:
\n\n1 <= n == grid.length <= 100
n == grid[i].length
0 <= grid[i][j] <= 109
You are given two positive integers n
and k
.
You can choose any bit in the binary representation of n
that is equal to 1 and change it to 0.
Return the number of changes needed to make n
equal to k
. If it is impossible, return -1.
\n
Example 1:
\n\nInput: n = 13, k = 4
\n\nOutput: 2
\n\nExplanation:
\nInitially, the binary representations of n
and k
are n = (1101)2
and k = (0100)2
.
\nWe can change the first and fourth bits of n
. The resulting integer is n = (0100)2 = k
.
Example 2:
\n\nInput: n = 21, k = 21
\n\nOutput: 0
\n\nExplanation:
\nn
and k
are already equal, so no changes are needed.
Example 3:
\n\nInput: n = 14, k = 13
\n\nOutput: -1
\n\nExplanation:
\nIt is not possible to make n
equal to k
.
\n
Constraints:
\n\n1 <= n, k <= 106
Alice and Bob are playing a game on a string.
\n\nYou are given a string s
, Alice and Bob will take turns playing the following game where Alice starts first:
s
that contains an odd number of vowels.s
that contains an even number of vowels.The first player who cannot make a move on their turn loses the game. We assume that both Alice and Bob play optimally.
\n\nReturn true
if Alice wins the game, and false
otherwise.
The English vowels are: a
, e
, i
, o
, and u
.
\n
Example 1:
\n\nInput: s = "leetcoder"
\n\nOutput: true
\n\nExplanation:
\nAlice can win the game as follows:
s = "leetcoder"
which contains 3 vowels. The resulting string is s = "der"
.s = "der"
which contains 0 vowels. The resulting string is s = "er"
.s = "er"
which contains 1 vowel.Example 2:
\n\nInput: s = "bbcd"
\n\nOutput: false
\n\nExplanation:
\nThere is no valid play for Alice in her first turn, so Alice loses the game.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.You are given a binary string s
.
You can perform the following operation on the string any number of times:
\n\ni
from the string where i + 1 < s.length
such that s[i] == '1'
and s[i + 1] == '0'
.s[i]
to the right until it reaches the end of the string or another '1'
. For example, for s = "010010"
, if we choose i = 1
, the resulting string will be s = "000110"
.Return the maximum number of operations that you can perform.
\n\n\n
Example 1:
\n\nInput: s = "1001101"
\n\nOutput: 4
\n\nExplanation:
\n\nWe can perform the following operations:
\n\ni = 0
. The resulting string is s = "0011101"
.i = 4
. The resulting string is s = "0011011"
.i = 3
. The resulting string is s = "0010111"
.i = 2
. The resulting string is s = "0001111"
.Example 2:
\n\nInput: s = "00111"
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.You are given two positive integer arrays nums
and target
, of the same length.
In a single operation, you can select any subarray of nums
and increment each element within that subarray by 1 or decrement each element within that subarray by 1.
Return the minimum number of operations required to make nums
equal to the array target
.
\n
Example 1:
\n\nInput: nums = [3,5,1,2], target = [4,6,2,4]
\n\nOutput: 2
\n\nExplanation:
\n\nWe will perform the following operations to make nums
equal to target
:
\n- Increment nums[0..3]
by 1, nums = [4,6,2,3]
.
\n- Increment nums[3..3]
by 1, nums = [4,6,2,4]
.
Example 2:
\n\nInput: nums = [1,3,2], target = [2,1,4]
\n\nOutput: 5
\n\nExplanation:
\n\nWe will perform the following operations to make nums
equal to target
:
\n- Increment nums[0..0]
by 1, nums = [2,3,2]
.
\n- Decrement nums[1..1]
by 1, nums = [2,2,2]
.
\n- Decrement nums[1..1]
by 1, nums = [2,1,2]
.
\n- Increment nums[2..2]
by 1, nums = [2,1,3]
.
\n- Increment nums[2..2]
by 1, nums = [2,1,4]
.
\n
Constraints:
\n\n1 <= nums.length == target.length <= 105
1 <= nums[i], target[i] <= 108
You are given an array of positive integers nums
.
Alice and Bob are playing a game. In the game, Alice can choose either all single-digit numbers or all double-digit numbers from nums
, and the rest of the numbers are given to Bob. Alice wins if the sum of her numbers is strictly greater than the sum of Bob's numbers.
Return true
if Alice can win this game, otherwise, return false
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,10]
\n\nOutput: false
\n\nExplanation:
\n\nAlice cannot win by choosing either single-digit or double-digit numbers.
\nExample 2:
\n\nInput: nums = [1,2,3,4,5,14]
\n\nOutput: true
\n\nExplanation:
\n\nAlice can win by choosing single-digit numbers which have a sum equal to 15.
\nExample 3:
\n\nInput: nums = [5,5,5,25]
\n\nOutput: true
\n\nExplanation:
\n\nAlice can win by choosing double-digit numbers which have a sum equal to 25.
\n\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 99
You are given 2 positive integers l
and r
. For any number x
, all positive divisors of x
except x
are called the proper divisors of x
.
A number is called special if it has exactly 2 proper divisors. For example:
\n\nReturn the count of numbers in the range [l, r]
that are not special.
\n
Example 1:
\n\nInput: l = 5, r = 7
\n\nOutput: 3
\n\nExplanation:
\n\nThere are no special numbers in the range [5, 7]
.
Example 2:
\n\nInput: l = 4, r = 16
\n\nOutput: 11
\n\nExplanation:
\n\nThe special numbers in the range [4, 16]
are 4 and 9.
\n
Constraints:
\n\n1 <= l <= r <= 109
You are given a binary string s
.
Return the number of substrings with dominant ones.
\n\nA string has dominant ones if the number of ones in the string is greater than or equal to the square of the number of zeros in the string.
\n\n\n
Example 1:
\n\nInput: s = "00011"
\n\nOutput: 5
\n\nExplanation:
\n\nThe substrings with dominant ones are shown in the table below.
\ni | \n\t\t\tj | \n\t\t\ts[i..j] | \n\t\t\tNumber of Zeros | \n\t\t\tNumber of Ones | \n\t\t
---|---|---|---|---|
3 | \n\t\t\t3 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
4 | \n\t\t\t4 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t3 | \n\t\t\t01 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t11 | \n\t\t\t0 | \n\t\t\t2 | \n\t\t
2 | \n\t\t\t4 | \n\t\t\t011 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
Example 2:
\n\nInput: s = "101101"
\n\nOutput: 16
\n\nExplanation:
\n\nThe substrings with non-dominant ones are shown in the table below.
\n\nSince there are 21 substrings total and 5 of them have non-dominant ones, it follows that there are 16 substrings with dominant ones.
\ni | \n\t\t\tj | \n\t\t\ts[i..j] | \n\t\t\tNumber of Zeros | \n\t\t\tNumber of Ones | \n\t\t
---|---|---|---|---|
1 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
4 | \n\t\t\t4 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t\t0 | \n\t\t
1 | \n\t\t\t4 | \n\t\t\t0110 | \n\t\t\t2 | \n\t\t\t2 | \n\t\t
0 | \n\t\t\t4 | \n\t\t\t10110 | \n\t\t\t2 | \n\t\t\t3 | \n\t\t
1 | \n\t\t\t5 | \n\t\t\t01101 | \n\t\t\t2 | \n\t\t\t3 | \n\t\t
\n
Constraints:
\n\n1 <= s.length <= 4 * 104
s
consists only of characters '0'
and '1'
.You are given two positive integers xCorner
and yCorner
, and a 2D array circles
, where circles[i] = [xi, yi, ri]
denotes a circle with center at (xi, yi)
and radius ri
.
There is a rectangle in the coordinate plane with its bottom left corner at the origin and top right corner at the coordinate (xCorner, yCorner)
. You need to check whether there is a path from the bottom left corner to the top right corner such that the entire path lies inside the rectangle, does not touch or lie inside any circle, and touches the rectangle only at the two corners.
Return true
if such a path exists, and false
otherwise.
\n
Example 1:
\n\nInput: xCorner = 3, yCorner = 4, circles = [[2,1,1]]
\n\nOutput: true
\n\nExplanation:
\n\nThe black curve shows a possible path between (0, 0)
and (3, 4)
.
Example 2:
\n\nInput: xCorner = 3, yCorner = 3, circles = [[1,1,2]]
\n\nOutput: false
\n\nExplanation:
\n\nNo path exists from (0, 0)
to (3, 3)
.
Example 3:
\n\nInput: xCorner = 3, yCorner = 3, circles = [[2,1,1],[1,2,1]]
\n\nOutput: false
\n\nExplanation:
\n\nNo path exists from (0, 0)
to (3, 3)
.
Example 4:
\n\nInput: xCorner = 4, yCorner = 4, circles = [[5,5,1]]
\n\nOutput: true
\n\nExplanation:
\n\n\n
Constraints:
\n\n3 <= xCorner, yCorner <= 109
1 <= circles.length <= 1000
circles[i].length == 3
1 <= xi, yi, ri <= 109
You are given an integer n
representing the number of players in a game and a 2D array pick
where pick[i] = [xi, yi]
represents that the player xi
picked a ball of color yi
.
Player i
wins the game if they pick strictly more than i
balls of the same color. In other words,
i
wins if they pick at leasti + 1
balls of the same color.Return the number of players who win the game.
\n\nNote that multiple players can win the game.
\n\n\n
Example 1:
\n\nInput: n = 4, pick = [[0,0],[1,0],[1,0],[2,1],[2,1],[2,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nPlayer 0 and player 1 win the game, while players 2 and 3 do not win.
\nExample 2:
\n\nInput: n = 5, pick = [[1,1],[1,2],[1,3],[1,4]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo player wins the game.
\nExample 3:
\n\nInput: n = 5, pick = [[1,1],[2,4],[2,4],[2,4]]
\n\nOutput: 1
\n\nExplanation:
\n\nPlayer 2 wins the game by picking 3 balls with color 4.
\n\n
Constraints:
\n\n2 <= n <= 10
1 <= pick.length <= 100
pick[i].length == 2
0 <= xi <= n - 1
0 <= yi <= 10
You are given an integer n
representing the number of players in a game and a 2D array pick
where pick[i] = [xi, yi]
represents that the player xi
picked a ball of color yi
.
Player i
wins the game if they pick strictly more than i
balls of the same color. In other words,
i
wins if they pick at least i + 1
balls of the same color.Return the number of players who win the game.
\n\nNote that multiple players can win the game.
\n\n\n
Example 1:
\n\nInput: n = 4, pick = [[0,0],[1,0],[1,0],[2,1],[2,1],[2,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nPlayer 0 and player 1 win the game, while players 2 and 3 do not win.
\nExample 2:
\n\nInput: n = 5, pick = [[1,1],[1,2],[1,3],[1,4]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo player wins the game.
\nExample 3:
\n\nInput: n = 5, pick = [[1,1],[2,4],[2,4],[2,4]]
\n\nOutput: 1
\n\nExplanation:
\n\nPlayer 2 wins the game by picking 3 balls with color 4.
\n\n
Constraints:
\n\n2 <= n <= 10
1 <= pick.length <= 100
pick[i].length == 2
0 <= xi <= n - 1
0 <= yi <= 10
You are given an m x n
binary matrix grid
.
A row or column is considered palindromic if its values read the same forward and backward.
\n\nYou can flip any number of cells in grid
from 0
to 1
, or from 1
to 0
.
Return the minimum number of cells that need to be flipped to make either all rows palindromic or all columns palindromic.
\n\n\n
Example 1:
\n\nInput: grid = [[1,0,0],[0,0,0],[0,0,1]]
\n\nOutput: 2
\n\nExplanation:
\n\nFlipping the highlighted cells makes all the rows palindromic.
\nExample 2:
\n\nInput: grid = [[0,1],[0,1],[0,0]]
\n\nOutput: 1
\n\nExplanation:
\n\nFlipping the highlighted cell makes all the columns palindromic.
\nExample 3:
\n\nInput: grid = [[1],[0]]
\n\nOutput: 0
\n\nExplanation:
\n\nAll rows are already palindromic.
\n\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m * n <= 2 * 105
0 <= grid[i][j] <= 1
You are given an m x n
binary matrix grid
.
A row or column is considered palindromic if its values read the same forward and backward.
\n\nYou can flip any number of cells in grid
from 0
to 1
, or from 1
to 0
.
Return the minimum number of cells that need to be flipped to make all rows and columns palindromic, and the total number of 1
's in grid
divisible by 4
.
\n
Example 1:
\n\nInput: grid = [[1,0,0],[0,1,0],[0,0,1]]
\n\nOutput: 3
\n\nExplanation:
\n\nExample 2:
\n\nInput: grid = [[0,1],[0,1],[0,0]]
\n\nOutput: 2
\n\nExplanation:
\n\nExample 3:
\n\nInput: grid = [[1],[1]]
\n\nOutput: 2
\n\nExplanation:
\n\n\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m * n <= 2 * 105
0 <= grid[i][j] <= 1
There exists an undirected tree with n
nodes numbered 0
to n - 1
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the tree.
Initially, all nodes are unmarked. For each node i
:
i
is odd, the node will get marked at time x
if there is at least one node adjacent to it which was marked at time x - 1
.i
is even, the node will get marked at time x
if there is at least one node adjacent to it which was marked at time x - 2
.Return an array times
where times[i]
is the time when all nodes get marked in the tree, if you mark node i
at time t = 0
.
Note that the answer for each times[i]
is independent, i.e. when you mark node i
all other nodes are unmarked.
\n
Example 1:
\n\nInput: edges = [[0,1],[0,2]]
\n\nOutput: [2,4,3]
\n\nExplanation:
\n\ni = 0
:\n\n\tt = 1
, and Node 2 at t = 2
.i = 1
:\n\tt = 2
, and Node 2 at t = 4
.i = 2
:\n\tt = 2
, and Node 1 at t = 3
.Example 2:
\n\nInput: edges = [[0,1]]
\n\nOutput: [1,2]
\n\nExplanation:
\n\ni = 0
:\n\n\tt = 1
.i = 1
:\n\tt = 2
.Example 3:
\n\nInput: edges = [[2,4],[0,1],[2,3],[0,2]]
\n\nOutput: [4,6,3,5,5]
\n\nExplanation:
\n\n\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= edges[i][0], edges[i][1] <= n - 1
edges
represents a valid tree.You are given a n x n
2D array grid
containing distinct elements in the range [0, n2 - 1]
.
Implement the NeighborSum
class:
NeighborSum(int [][]grid)
initializes the object.int adjacentSum(int value)
returns the sum of elements which are adjacent neighbors of value
, that is either to the top, left, right, or bottom of value
in grid
.int diagonalSum(int value)
returns the sum of elements which are diagonal neighbors of value
, that is either to the top-left, top-right, bottom-left, or bottom-right of value
in grid
.\n
Example 1:
\n\nInput:
\n\n["NeighborSum", "adjacentSum", "adjacentSum", "diagonalSum", "diagonalSum"]
\n\n[[[[0, 1, 2], [3, 4, 5], [6, 7, 8]]], [1], [4], [4], [8]]
\n\nOutput: [null, 6, 16, 16, 4]
\n\nExplanation:
\n\nExample 2:
\n\nInput:
\n\n["NeighborSum", "adjacentSum", "diagonalSum"]
\n\n[[[[1, 2, 0, 3], [4, 7, 15, 6], [8, 9, 10, 11], [12, 13, 14, 5]]], [15], [9]]
\n\nOutput: [null, 23, 45]
\n\nExplanation:
\n\n\n
Constraints:
\n\n3 <= n == grid.length == grid[0].length <= 10
0 <= grid[i][j] <= n2 - 1
grid[i][j]
are distinct.value
in adjacentSum
and diagonalSum
will be in the range [0, n2 - 1]
.2 * n2
calls will be made to adjacentSum
and diagonalSum
.You are given an integer n
and a 2D integer array queries
.
There are n
cities numbered from 0
to n - 1
. Initially, there is a unidirectional road from city i
to city i + 1
for all 0 <= i < n - 1
.
queries[i] = [ui, vi]
represents the addition of a new unidirectional road from city ui
to city vi
. After each query, you need to find the length of the shortest path from city 0
to city n - 1
.
Return an array answer
where for each i
in the range [0, queries.length - 1]
, answer[i]
is the length of the shortest path from city 0
to city n - 1
after processing the first i + 1
queries.
\n
Example 1:
\n\nInput: n = 5, queries = [[2,4],[0,2],[0,4]]
\n\nOutput: [3,2,1]
\n\nExplanation:
\n\nAfter the addition of the road from 2 to 4, the length of the shortest path from 0 to 4 is 3.
\n\nAfter the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2.
\n\nAfter the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1.
\nExample 2:
\n\nInput: n = 4, queries = [[0,3],[0,2]]
\n\nOutput: [1,1]
\n\nExplanation:
\n\nAfter the addition of the road from 0 to 3, the length of the shortest path from 0 to 3 is 1.
\n\nAfter the addition of the road from 0 to 2, the length of the shortest path remains 1.
\n\n
Constraints:
\n\n3 <= n <= 500
1 <= queries.length <= 500
queries[i].length == 2
0 <= queries[i][0] < queries[i][1] < n
1 < queries[i][1] - queries[i][0]
You are given an integer n
and a 2D integer array queries
.
There are n
cities numbered from 0
to n - 1
. Initially, there is a unidirectional road from city i
to city i + 1
for all 0 <= i < n - 1
.
queries[i] = [ui, vi]
represents the addition of a new unidirectional road from city ui
to city vi
. After each query, you need to find the length of the shortest path from city 0
to city n - 1
.
There are no two queries such that queries[i][0] < queries[j][0] < queries[i][1] < queries[j][1]
.
Return an array answer
where for each i
in the range [0, queries.length - 1]
, answer[i]
is the length of the shortest path from city 0
to city n - 1
after processing the first i + 1
queries.
\n
Example 1:
\n\nInput: n = 5, queries = [[2,4],[0,2],[0,4]]
\n\nOutput: [3,2,1]
\n\nExplanation:
\n\nAfter the addition of the road from 2 to 4, the length of the shortest path from 0 to 4 is 3.
\n\nAfter the addition of the road from 0 to 2, the length of the shortest path from 0 to 4 is 2.
\n\nAfter the addition of the road from 0 to 4, the length of the shortest path from 0 to 4 is 1.
\nExample 2:
\n\nInput: n = 4, queries = [[0,3],[0,2]]
\n\nOutput: [1,1]
\n\nExplanation:
\n\nAfter the addition of the road from 0 to 3, the length of the shortest path from 0 to 3 is 1.
\n\nAfter the addition of the road from 0 to 2, the length of the shortest path remains 1.
\n\n
Constraints:
\n\n3 <= n <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] < queries[i][1] < n
1 < queries[i][1] - queries[i][0]
i != j
and queries[i][0] < queries[j][0] < queries[i][1] < queries[j][1]
.There are some red and blue tiles arranged circularly. You are given an array of integers colors
and a 2D integers array queries
.
The color of tile i
is represented by colors[i]
:
colors[i] == 0
means that tile i
is red.colors[i] == 1
means that tile i
is blue.An alternating group is a contiguous subset of tiles in the circle with alternating colors (each tile in the group except the first and last one has a different color from its adjacent tiles in the group).
\n\nYou have to process queries of two types:
\n\nqueries[i] = [1, sizei]
, determine the count of alternating groups with size sizei
.queries[i] = [2, indexi, colori]
, change colors[indexi]
to colori
.Return an array answer
containing the results of the queries of the first type in order.
Note that since colors
represents a circle, the first and the last tiles are considered to be next to each other.
\n
Example 1:
\n\nInput: colors = [0,1,1,0,1], queries = [[2,1,0],[1,4]]
\n\nOutput: [2]
\n\nExplanation:
\n\nFirst query:
\n\nChange colors[1]
to 0.
Second query:
\n\nCount of the alternating groups with size 4:
\n\nExample 2:
\n\nInput: colors = [0,0,1,0,1,1], queries = [[1,3],[2,3,0],[1,5]]
\n\nOutput: [2,0]
\n\nExplanation:
\n\nFirst query:
\n\nCount of the alternating groups with size 3:
\n\nSecond query: colors
will not change.
Third query: There is no alternating group with size 5.
\n\n
Constraints:
\n\n4 <= colors.length <= 5 * 104
0 <= colors[i] <= 1
1 <= queries.length <= 5 * 104
queries[i][0] == 1
or queries[i][0] == 2
i
that:\n\tqueries[i][0] == 1
: queries[i].length == 2
, 3 <= queries[i][1] <= colors.length - 1
queries[i][0] == 2
: queries[i].length == 3
, 0 <= queries[i][1] <= colors.length - 1
, 0 <= queries[i][2] <= 1
There is a snake in an n x n
matrix grid
and can move in four possible directions. Each cell in the grid
is identified by the position: grid[i][j] = (i * n) + j
.
The snake starts at cell 0 and follows a sequence of commands.
\n\nYou are given an integer n
representing the size of the grid
and an array of strings commands
where each command[i]
is either "UP"
, "RIGHT"
, "DOWN"
, and "LEFT"
. It's guaranteed that the snake will remain within the grid
boundaries throughout its movement.
Return the position of the final cell where the snake ends up after executing commands
.
\n
Example 1:
\n\nInput: n = 2, commands = ["RIGHT","DOWN"]
\n\nOutput: 3
\n\nExplanation:
\n\n0 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t3 | \n\t\t
0 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t3 | \n\t\t
0 | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t3 | \n\t\t
Example 2:
\n\nInput: n = 3, commands = ["DOWN","RIGHT","UP"]
\n\nOutput: 1
\n\nExplanation:
\n\n0 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t5 | \n\t\t
6 | \n\t\t\t7 | \n\t\t\t8 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t5 | \n\t\t
6 | \n\t\t\t7 | \n\t\t\t8 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t5 | \n\t\t
6 | \n\t\t\t7 | \n\t\t\t8 | \n\t\t
0 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t5 | \n\t\t
6 | \n\t\t\t7 | \n\t\t\t8 | \n\t\t
\n
Constraints:
\n\n2 <= n <= 10
1 <= commands.length <= 100
commands
consists only of "UP"
, "RIGHT"
, "DOWN"
, and "LEFT"
.There is an undirected tree with n
nodes labeled from 0
to n - 1
, and rooted at node 0
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the tree.
A node is good if all the subtrees rooted at its children have the same size.
\n\nReturn the number of good nodes in the given tree.
\n\nA subtree of treeName
is a tree consisting of a node in treeName
and all of its descendants.
\n
Example 1:
\n\nInput: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
\n\nOutput: 7
\n\nExplanation:
\nAll of the nodes of the given tree are good.
\nExample 2:
\n\nInput: edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]]
\n\nOutput: 6
\n\nExplanation:
\nThere are 6 good nodes in the given tree. They are colored in the image above.
\n\nExample 3:
\n\nInput: edges = [[0,1],[1,2],[1,3],[1,4],[0,5],[5,6],[6,7],[7,8],[0,9],[9,10],[9,12],[10,11]]
\n\nOutput: 12
\n\nExplanation:
\nAll nodes except node 9 are good.
\n\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i].length == 2
0 <= ai, bi < n
edges
represents a valid tree.You are given an array of positive integers nums
of length n
.
We call a pair of non-negative integer arrays (arr1, arr2)
monotonic if:
n
.arr1
is monotonically non-decreasing, in other words, arr1[0] <= arr1[1] <= ... <= arr1[n - 1]
.arr2
is monotonically non-increasing, in other words, arr2[0] >= arr2[1] >= ... >= arr2[n - 1]
.arr1[i] + arr2[i] == nums[i]
for all 0 <= i <= n - 1
.Return the count of monotonic pairs.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [2,3,2]
\n\nOutput: 4
\n\nExplanation:
\n\nThe good pairs are:
\n\n([0, 1, 1], [2, 2, 1])
([0, 1, 2], [2, 2, 0])
([0, 2, 2], [2, 1, 0])
([1, 2, 2], [1, 1, 0])
Example 2:
\n\nInput: nums = [5,5,5,5]
\n\nOutput: 126
\n\n
Constraints:
\n\n1 <= n == nums.length <= 2000
1 <= nums[i] <= 50
You are given an array of positive integers nums
of length n
.
We call a pair of non-negative integer arrays (arr1, arr2)
monotonic if:
n
.arr1
is monotonically non-decreasing, in other words, arr1[0] <= arr1[1] <= ... <= arr1[n - 1]
.arr2
is monotonically non-increasing, in other words, arr2[0] >= arr2[1] >= ... >= arr2[n - 1]
.arr1[i] + arr2[i] == nums[i]
for all 0 <= i <= n - 1
.Return the count of monotonic pairs.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [2,3,2]
\n\nOutput: 4
\n\nExplanation:
\n\nThe good pairs are:
\n\n([0, 1, 1], [2, 2, 1])
([0, 1, 2], [2, 2, 0])
([0, 2, 2], [2, 1, 0])
([1, 2, 2], [1, 1, 0])
Example 2:
\n\nInput: nums = [5,5,5,5]
\n\nOutput: 126
\n\n
Constraints:
\n\n1 <= n == nums.length <= 2000
1 <= nums[i] <= 1000
You are given an array of integers nums
of length n
and a positive integer k
.
The power of an array is defined as:
\n\nYou need to find the power of all subarrays of nums
of size k
.
Return an integer array results
of size n - k + 1
, where results[i]
is the power of nums[i..(i + k - 1)]
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,3,2,5], k = 3
\n\nOutput: [3,4,-1,-1,-1]
\n\nExplanation:
\n\nThere are 5 subarrays of nums
of size 3:
[1, 2, 3]
with the maximum element 3.[2, 3, 4]
with the maximum element 4.[3, 4, 3]
whose elements are not consecutive.[4, 3, 2]
whose elements are not sorted.[3, 2, 5]
whose elements are not consecutive.Example 2:
\n\nInput: nums = [2,2,2,2,2], k = 4
\n\nOutput: [-1,-1]
\nExample 3:
\n\nInput: nums = [3,2,3,2,3,2], k = 2
\n\nOutput: [-1,3,-1,3,-1]
\n\n
Constraints:
\n\n1 <= n == nums.length <= 500
1 <= nums[i] <= 105
1 <= k <= n
You are given an array of integers nums
of length n
and a positive integer k
.
The power of an array is defined as:
\n\nYou need to find the power of all subarrays of nums
of size k
.
Return an integer array results
of size n - k + 1
, where results[i]
is the power of nums[i..(i + k - 1)]
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,3,2,5], k = 3
\n\nOutput: [3,4,-1,-1,-1]
\n\nExplanation:
\n\nThere are 5 subarrays of nums
of size 3:
[1, 2, 3]
with the maximum element 3.[2, 3, 4]
with the maximum element 4.[3, 4, 3]
whose elements are not consecutive.[4, 3, 2]
whose elements are not sorted.[3, 2, 5]
whose elements are not consecutive.Example 2:
\n\nInput: nums = [2,2,2,2,2], k = 4
\n\nOutput: [-1,-1]
\nExample 3:
\n\nInput: nums = [3,2,3,2,3,2], k = 2
\n\nOutput: [-1,3,-1,3,-1]
\n\n
Constraints:
\n\n1 <= n == nums.length <= 105
1 <= nums[i] <= 106
1 <= k <= n
You are given a m x n
2D array board
representing a chessboard, where board[i][j]
represents the value of the cell (i, j)
.
Rooks in the same row or column attack each other. You need to place three rooks on the chessboard such that the rooks do not attack each other.
\n\nReturn the maximum sum of the cell values on which the rooks are placed.
\n\n\n
Example 1:
\n\nInput: board = [[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
\n\nOutput: 4
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 2)
, (1, 3)
, and (2, 1)
for a sum of 1 + 1 + 2 = 4
.
Example 2:
\n\nInput: board = [[1,2,3],[4,5,6],[7,8,9]]
\n\nOutput: 15
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 0)
, (1, 1)
, and (2, 2)
for a sum of 1 + 5 + 9 = 15
.
Example 3:
\n\nInput: board = [[1,1,1],[1,1,1],[1,1,1]]
\n\nOutput: 3
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 2)
, (1, 1)
, and (2, 0)
for a sum of 1 + 1 + 1 = 3
.
\n
Constraints:
\n\n3 <= m == board.length <= 100
3 <= n == board[i].length <= 100
-109 <= board[i][j] <= 109
You are given a m x n
2D array board
representing a chessboard, where board[i][j]
represents the value of the cell (i, j)
.
Rooks in the same row or column attack each other. You need to place three rooks on the chessboard such that the rooks do not attack each other.
\n\nReturn the maximum sum of the cell values on which the rooks are placed.
\n\n\n
Example 1:
\n\nInput: board = [[-3,1,1,1],[-3,1,-3,1],[-3,2,1,1]]
\n\nOutput: 4
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 2)
, (1, 3)
, and (2, 1)
for a sum of 1 + 1 + 2 = 4
.
Example 2:
\n\nInput: board = [[1,2,3],[4,5,6],[7,8,9]]
\n\nOutput: 15
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 0)
, (1, 1)
, and (2, 2)
for a sum of 1 + 5 + 9 = 15
.
Example 3:
\n\nInput: board = [[1,1,1],[1,1,1],[1,1,1]]
\n\nOutput: 3
\n\nExplanation:
\n\nWe can place the rooks in the cells (0, 2)
, (1, 1)
, and (2, 0)
for a sum of 1 + 1 + 1 = 3
.
\n
Constraints:
\n\n3 <= m == board.length <= 500
3 <= n == board[i].length <= 500
-109 <= board[i][j] <= 109
You are given a binary string s
and an integer k
.
A binary string satisfies the k-constraint if either of the following conditions holds:
\n\n0
's in the string is at most k
.1
's in the string is at most k
.Return an integer denoting the number of substrings of s
that satisfy the k-constraint.
\n
Example 1:
\n\nInput: s = "10101", k = 1
\n\nOutput: 12
\n\nExplanation:
\n\nEvery substring of s
except the substrings "1010"
, "10101"
, and "0101"
satisfies the k-constraint.
Example 2:
\n\nInput: s = "1010101", k = 2
\n\nOutput: 25
\n\nExplanation:
\n\nEvery substring of s
except the substrings with a length greater than 5 satisfies the k-constraint.
Example 3:
\n\nInput: s = "11111", k = 1
\n\nOutput: 15
\n\nExplanation:
\n\nAll substrings of s
satisfy the k-constraint.
\n
Constraints:
\n\n1 <= s.length <= 50
1 <= k <= s.length
s[i]
is either '0'
or '1'
.You are given two integer arrays energyDrinkA
and energyDrinkB
of the same length n
by a futuristic sports scientist. These arrays represent the energy boosts per hour provided by two different energy drinks, A and B, respectively.
You want to maximize your total energy boost by drinking one energy drink per hour. However, if you want to switch from consuming one energy drink to the other, you need to wait for one hour to cleanse your system (meaning you won't get any energy boost in that hour).
\n\nReturn the maximum total energy boost you can gain in the next n
hours.
Note that you can start consuming either of the two energy drinks.
\n\n\n
Example 1:
\n\nInput: energyDrinkA = [1,3,1], energyDrinkB = [3,1,1]
\n\nOutput: 5
\n\nExplanation:
\n\nTo gain an energy boost of 5, drink only the energy drink A (or only B).
\nExample 2:
\n\nInput: energyDrinkA = [4,1,1], energyDrinkB = [1,1,3]
\n\nOutput: 7
\n\nExplanation:
\n\nTo gain an energy boost of 7:
\n\n\n
Constraints:
\n\nn == energyDrinkA.length == energyDrinkB.length
3 <= n <= 105
1 <= energyDrinkA[i], energyDrinkB[i] <= 105
You are given two positive integers n
and k
.
An integer x
is called k-palindromic if:
x
is a palindrome.x
is divisible by k
.Return the largest integer having n
digits (as a string) that is k-palindromic.
Note that the integer must not have leading zeros.
\n\n\n
Example 1:
\n\nInput: n = 3, k = 5
\n\nOutput: "595"
\n\nExplanation:
\n\n595 is the largest k-palindromic integer with 3 digits.
\nExample 2:
\n\nInput: n = 1, k = 4
\n\nOutput: "8"
\n\nExplanation:
\n\n4 and 8 are the only k-palindromic integers with 1 digit.
\nExample 3:
\n\nInput: n = 5, k = 6
\n\nOutput: "89898"
\n\n
Constraints:
\n\n1 <= n <= 105
1 <= k <= 9
You are given a binary string s
and an integer k
.
You are also given a 2D integer array queries
, where queries[i] = [li, ri]
.
A binary string satisfies the k-constraint if either of the following conditions holds:
\n\n0
's in the string is at most k
.1
's in the string is at most k
.Return an integer array answer
, where answer[i]
is the number of substrings of s[li..ri]
that satisfy the k-constraint.
\n
Example 1:
\n\nInput: s = "0001111", k = 2, queries = [[0,6]]
\n\nOutput: [26]
\n\nExplanation:
\n\nFor the query [0, 6]
, all substrings of s[0..6] = "0001111"
satisfy the k-constraint except for the substrings s[0..5] = "000111"
and s[0..6] = "0001111"
.
Example 2:
\n\nInput: s = "010101", k = 1, queries = [[0,5],[1,4],[2,3]]
\n\nOutput: [15,9,3]
\n\nExplanation:
\n\nThe substrings of s
with a length greater than 3 do not satisfy the k-constraint.
\n
Constraints:
\n\n1 <= s.length <= 105
s[i]
is either '0'
or '1'
.1 <= k <= s.length
1 <= queries.length <= 105
queries[i] == [li, ri]
0 <= li <= ri < s.length
You are given an integer array nums
, an integer k
, and an integer multiplier
.
You need to perform k
operations on nums
. In each operation:
x
in nums
. If there are multiple occurrences of the minimum value, select the one that appears first.x
with x * multiplier
.Return an integer array denoting the final state of nums
after performing all k
operations.
\n
Example 1:
\n\nInput: nums = [2,1,3,5,6], k = 5, multiplier = 2
\n\nOutput: [8,4,6,5,6]
\n\nExplanation:
\n\nOperation | \n\t\t\tResult | \n\t\t
---|---|
After operation 1 | \n\t\t\t[2, 2, 3, 5, 6] | \n\t\t
After operation 2 | \n\t\t\t[4, 2, 3, 5, 6] | \n\t\t
After operation 3 | \n\t\t\t[4, 4, 3, 5, 6] | \n\t\t
After operation 4 | \n\t\t\t[4, 4, 6, 5, 6] | \n\t\t
After operation 5 | \n\t\t\t[8, 4, 6, 5, 6] | \n\t\t
Example 2:
\n\nInput: nums = [1,2], k = 3, multiplier = 4
\n\nOutput: [16,8]
\n\nExplanation:
\n\nOperation | \n\t\t\tResult | \n\t\t
---|---|
After operation 1 | \n\t\t\t[4, 2] | \n\t\t
After operation 2 | \n\t\t\t[4, 8] | \n\t\t
After operation 3 | \n\t\t\t[16, 8] | \n\t\t
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 10
1 <= multiplier <= 5
You are given an array nums
consisting of positive integers.
We call two integers x
and y
in this problem almost equal if both integers can become equal after performing the following operation at most once:
x
or y
and swap any two digits within the chosen number.Return the number of indices i
and j
in nums
where i < j
such that nums[i]
and nums[j]
are almost equal.
Note that it is allowed for an integer to have leading zeros after performing an operation.
\n\n\n
Example 1:
\n\nInput: nums = [3,12,30,17,21]
\n\nOutput: 2
\n\nExplanation:
\n\nThe almost equal pairs of elements are:
\n\nExample 2:
\n\nInput: nums = [1,1,1,1,1]
\n\nOutput: 10
\n\nExplanation:
\n\nEvery two elements in the array are almost equal.
\nExample 3:
\n\nInput: nums = [123,231]
\n\nOutput: 0
\n\nExplanation:
\n\nWe cannot swap any two digits of 123 or 231 to reach the other.
\n\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 106
You are given an integer array nums
, an integer k
, and an integer multiplier
.
You need to perform k
operations on nums
. In each operation:
x
in nums
. If there are multiple occurrences of the minimum value, select the one that appears first.x
with x * multiplier
.After the k
operations, apply modulo 109 + 7
to every value in nums
.
Return an integer array denoting the final state of nums
after performing all k
operations and then applying the modulo.
\n
Example 1:
\n\nInput: nums = [2,1,3,5,6], k = 5, multiplier = 2
\n\nOutput: [8,4,6,5,6]
\n\nExplanation:
\n\nOperation | \n\t\t\tResult | \n\t\t
---|---|
After operation 1 | \n\t\t\t[2, 2, 3, 5, 6] | \n\t\t
After operation 2 | \n\t\t\t[4, 2, 3, 5, 6] | \n\t\t
After operation 3 | \n\t\t\t[4, 4, 3, 5, 6] | \n\t\t
After operation 4 | \n\t\t\t[4, 4, 6, 5, 6] | \n\t\t
After operation 5 | \n\t\t\t[8, 4, 6, 5, 6] | \n\t\t
After applying modulo | \n\t\t\t[8, 4, 6, 5, 6] | \n\t\t
Example 2:
\n\nInput: nums = [100000,2000], k = 2, multiplier = 1000000
\n\nOutput: [999999307,999999993]
\n\nExplanation:
\n\nOperation | \n\t\t\tResult | \n\t\t
---|---|
After operation 1 | \n\t\t\t[100000, 2000000000] | \n\t\t
After operation 2 | \n\t\t\t[100000000000, 2000000000] | \n\t\t
After applying modulo | \n\t\t\t[999999307, 999999993] | \n\t\t
\n
Constraints:
\n\n1 <= nums.length <= 104
1 <= nums[i] <= 109
1 <= k <= 109
1 <= multiplier <= 106
Attention: In this version, the number of operations that can be performed, has been increased to twice.
\n\nYou are given an array nums
consisting of positive integers.
We call two integers x
and y
almost equal if both integers can become equal after performing the following operation at most twice:
x
or y
and swap any two digits within the chosen number.Return the number of indices i
and j
in nums
where i < j
such that nums[i]
and nums[j]
are almost equal.
Note that it is allowed for an integer to have leading zeros after performing an operation.
\n\n\n
Example 1:
\n\nInput: nums = [1023,2310,2130,213]
\n\nOutput: 4
\n\nExplanation:
\n\nThe almost equal pairs of elements are:
\n\nExample 2:
\n\nInput: nums = [1,10,100]
\n\nOutput: 3
\n\nExplanation:
\n\nThe almost equal pairs of elements are:
\n\n\n
Constraints:
\n\n2 <= nums.length <= 5000
1 <= nums[i] < 107
You are given three positive integers num1
, num2
, and num3
.
The key
of num1
, num2
, and num3
is defined as a four-digit number such that:
ith
digit (1 <= i <= 4
) of the key
is generated by taking the smallest digit among the ith
digits of num1
, num2
, and num3
.Return the key
of the three numbers without leading zeros (if any).
\n
Example 1:
\n\nInput: num1 = 1, num2 = 10, num3 = 1000
\n\nOutput: 0
\n\nExplanation:
\n\nOn padding, num1
becomes "0001"
, num2
becomes "0010"
, and num3
remains "1000"
.
1st
digit of the key
is min(0, 0, 1)
.2nd
digit of the key
is min(0, 0, 0)
.3rd
digit of the key
is min(0, 1, 0)
.4th
digit of the key
is min(1, 0, 0)
.Hence, the key
is "0000"
, i.e. 0.
Example 2:
\n\nInput: num1 = 987, num2 = 879, num3 = 798
\n\nOutput: 777
\nExample 3:
\n\nInput: num1 = 1, num2 = 2, num3 = 3
\n\nOutput: 1
\n\n
Constraints:
\n\n1 <= num1, num2, num3 <= 9999
You are given a string s
of length n
and an integer k
, where n
is a multiple of k
. Your task is to hash the string s
into a new string called result
, which has a length of n / k
.
First, divide s
into n / k
substrings, each with a length of k
. Then, initialize result
as an empty string.
For each substring in order from the beginning:
\n\n'a' → 0
, 'b' → 1
, ..., 'z' → 25
).hashedChar
.hashedChar
.result
.Return result
.
\n
Example 1:
\n\nInput: s = "abcd", k = 2
\n\nOutput: "bf"
\n\nExplanation:
\n\nFirst substring: "ab"
, 0 + 1 = 1
, 1 % 26 = 1
, result[0] = 'b'
.
Second substring: "cd"
, 2 + 3 = 5
, 5 % 26 = 5
, result[1] = 'f'
.
Example 2:
\n\nInput: s = "mxz", k = 3
\n\nOutput: "i"
\n\nExplanation:
\n\nThe only substring: "mxz"
, 12 + 23 + 25 = 60
, 60 % 26 = 8
, result[0] = 'i'
.
\n
Constraints:
\n\n1 <= k <= 100
k <= s.length <= 1000
s.length
is divisible by k
.s
consists only of lowercase English letters.You are given two positive integers n
and k
.
An integer x
is called k-palindromic if:
x
is a palindrome.x
is divisible by k
.An integer is called good if its digits can be rearranged to form a k-palindromic integer. For example, for k = 2
, 2020 can be rearranged to form the k-palindromic integer 2002, whereas 1010 cannot be rearranged to form a k-palindromic integer.
Return the count of good integers containing n
digits.
Note that any integer must not have leading zeros, neither before nor after rearrangement. For example, 1010 cannot be rearranged to form 101.
\n\n\n
Example 1:
\n\nInput: n = 3, k = 5
\n\nOutput: 27
\n\nExplanation:
\n\nSome of the good integers are:
\n\nExample 2:
\n\nInput: n = 1, k = 4
\n\nOutput: 2
\n\nExplanation:
\n\nThe two good integers are 4 and 8.
\nExample 3:
\n\nInput: n = 5, k = 6
\n\nOutput: 2468
\n\n
Constraints:
\n\n1 <= n <= 10
1 <= k <= 9
You are given an integer power
and two integer arrays damage
and health
, both having length n
.
Bob has n
enemies, where enemy i
will deal Bob damage[i]
points of damage per second while they are alive (i.e. health[i] > 0
).
Every second, after the enemies deal damage to Bob, he chooses one of the enemies that is still alive and deals power
points of damage to them.
Determine the minimum total amount of damage points that will be dealt to Bob before all n
enemies are dead.
\n
Example 1:
\n\nInput: power = 4, damage = [1,2,3,4], health = [4,5,6,8]
\n\nOutput: 39
\n\nExplanation:
\n\n10 + 10 = 20
points.6 + 6 = 12
points.3
points.2 + 2 = 4
points.Example 2:
\n\nInput: power = 1, damage = [1,1,1,1], health = [1,2,3,4]
\n\nOutput: 20
\n\nExplanation:
\n\n4
points.3 + 3 = 6
points.2 + 2 + 2 = 6
points.1 + 1 + 1 + 1 = 4
points.Example 3:
\n\nInput: power = 8, damage = [40], health = [59]
\n\nOutput: 320
\n\n
Constraints:
\n\n1 <= power <= 104
1 <= n == damage.length == health.length <= 105
1 <= damage[i], health[i] <= 104
You are given two strings, coordinate1
and coordinate2
, representing the coordinates of a square on an 8 x 8
chessboard.
Below is the chessboard for reference.
\n\nReturn true
if these two squares have the same color and false
otherwise.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first (indicating its column), and the number second (indicating its row).
\n\n\n
Example 1:
\n\nInput: coordinate1 = "a1", coordinate2 = "c3"
\n\nOutput: true
\n\nExplanation:
\n\nBoth squares are black.
\nExample 2:
\n\nInput: coordinate1 = "a1", coordinate2 = "h3"
\n\nOutput: false
\n\nExplanation:
\n\nSquare "a1"
is black and "h3"
is white.
\n
Constraints:
\n\ncoordinate1.length == coordinate2.length == 2
'a' <= coordinate1[0], coordinate2[0] <= 'h'
'1' <= coordinate1[1], coordinate2[1] <= '8'
There is an infinite 2D plane.
\n\nYou are given a positive integer k
. You are also given a 2D array queries
, which contains the following queries:
queries[i] = [x, y]
: Build an obstacle at coordinate (x, y)
in the plane. It is guaranteed that there is no obstacle at this coordinate when this query is made.After each query, you need to find the distance of the kth
nearest obstacle from the origin.
Return an integer array results
where results[i]
denotes the kth
nearest obstacle after query i
, or results[i] == -1
if there are less than k
obstacles.
Note that initially there are no obstacles anywhere.
\n\nThe distance of an obstacle at coordinate (x, y)
from the origin is given by |x| + |y|
.
\n
Example 1:
\n\nInput: queries = [[1,2],[3,4],[2,3],[-3,0]], k = 2
\n\nOutput: [-1,7,5,3]
\n\nExplanation:
\n\nqueries[0]
, there are less than 2 obstacles.queries[1]
, there are obstacles at distances 3 and 7.queries[2]
, there are obstacles at distances 3, 5, and 7.queries[3]
, there are obstacles at distances 3, 3, 5, and 7.Example 2:
\n\nInput: queries = [[5,5],[4,4],[3,3]], k = 1
\n\nOutput: [10,8,6]
\n\nExplanation:
\n\nqueries[0]
, there is an obstacle at distance 10.queries[1]
, there are obstacles at distances 8 and 10.queries[2]
, there are obstacles at distances 6, 8, and 10.\n
Constraints:
\n\n1 <= queries.length <= 2 * 105
queries[i]
are unique.-109 <= queries[i][0], queries[i][1] <= 109
1 <= k <= 105
You are given a 2D matrix grid
consisting of positive integers.
You have to select one or more cells from the matrix such that the following conditions are satisfied:
\n\nYour score will be the sum of the values of the selected cells.
\n\nReturn the maximum score you can achieve.
\n\n\n
Example 1:
\n\nInput: grid = [[1,2,3],[4,3,2],[1,1,1]]
\n\nOutput: 8
\n\nExplanation:
\n\nWe can select the cells with values 1, 3, and 4 that are colored above.
\nExample 2:
\n\nInput: grid = [[8,7,6],[8,3,2]]
\n\nOutput: 15
\n\nExplanation:
\n\nWe can select the cells with values 7 and 8 that are colored above.
\n\n
Constraints:
\n\n1 <= grid.length, grid[i].length <= 10
1 <= grid[i][j] <= 100
You are given an array nums
of n
integers, and a 2D integer array queries
of size q
, where queries[i] = [li, ri]
.
For each query, you must find the maximum XOR score of any subarray of nums[li..ri]
.
The XOR score of an array a
is found by repeatedly applying the following operations on a
so that only one element remains, that is the score:
a[i]
with a[i] XOR a[i + 1]
for all indices i
except the last one.a
.Return an array answer
of size q
where answer[i]
is the answer to query i
.
\n
Example 1:
\n\nInput: nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]
\n\nOutput: [12,60,60]
\n\nExplanation:
\n\nIn the first query, nums[0..2]
has 6 subarrays [2]
, [8]
, [4]
, [2, 8]
, [8, 4]
, and [2, 8, 4]
each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.
In the second query, the subarray of nums[1..4]
with the largest XOR score is nums[1..4]
with a score of 60.
In the third query, the subarray of nums[0..5]
with the largest XOR score is nums[1..4]
with a score of 60.
Example 2:
\n\nInput: nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]
\n\nOutput: [7,14,11,14,5]
\n\nExplanation:
\n\nIndex | \n\t\t\tnums[li..ri] | \n\t\t\tMaximum XOR Score Subarray | \n\t\t\tMaximum Subarray XOR Score | \n\t\t
---|---|---|---|
0 | \n\t\t\t[0, 7, 3, 2] | \n\t\t\t[7] | \n\t\t\t7 | \n\t\t
1 | \n\t\t\t[7, 3, 2, 8, 5] | \n\t\t\t[7, 3, 2, 8] | \n\t\t\t14 | \n\t\t
2 | \n\t\t\t[3, 2, 8] | \n\t\t\t[3, 2, 8] | \n\t\t\t11 | \n\t\t
3 | \n\t\t\t[3, 2, 8, 5, 1] | \n\t\t\t[2, 8, 5, 1] | \n\t\t\t14 | \n\t\t
4 | \n\t\t\t[5, 1] | \n\t\t\t[5] | \n\t\t\t5 | \n\t\t
\n
Constraints:
\n\n1 <= n == nums.length <= 2000
0 <= nums[i] <= 231 - 1
1 <= q == queries.length <= 105
queries[i].length == 2
queries[i] = [li, ri]
0 <= li <= ri <= n - 1
You are given a string date
representing a Gregorian calendar date in the yyyy-mm-dd
format.
date
can be written in its binary representation obtained by converting year, month, and day to their binary representations without any leading zeroes and writing them down in year-month-day
format.
Return the binary representation of date
.
\n
Example 1:
\n\nInput: date = "2080-02-29"
\n\nOutput: "100000100000-10-11101"
\n\nExplanation:
\n\n100000100000, 10, and 11101 are the binary representations of 2080, 02, and 29 respectively.
\nExample 2:
\n\nInput: date = "1900-01-01"
\n\nOutput: "11101101100-1-1"
\n\nExplanation:
\n\n11101101100, 1, and 1 are the binary representations of 1900, 1, and 1 respectively.
\n\n
Constraints:
\n\ndate.length == 10
date[4] == date[7] == '-'
, and all other date[i]
's are digits.date
represents a valid Gregorian calendar date between Jan 1st, 1900 and Dec 31st, 2100 (both inclusive).You are given an array of integers start
and an integer d
, representing n
intervals [start[i], start[i] + d]
.
You are asked to choose n
integers where the ith
integer must belong to the ith
interval. The score of the chosen integers is defined as the minimum absolute difference between any two integers that have been chosen.
Return the maximum possible score of the chosen integers.
\n\n\n
Example 1:
\n\nInput: start = [6,0,3], d = 2
\n\nOutput: 4
\n\nExplanation:
\n\nThe maximum possible score can be obtained by choosing integers: 8, 0, and 4. The score of these chosen integers is min(|8 - 0|, |8 - 4|, |0 - 4|)
which equals 4.
Example 2:
\n\nInput: start = [2,6,13,13], d = 5
\n\nOutput: 5
\n\nExplanation:
\n\nThe maximum possible score can be obtained by choosing integers: 2, 7, 13, and 18. The score of these chosen integers is min(|2 - 7|, |2 - 13|, |2 - 18|, |7 - 13|, |7 - 18|, |13 - 18|)
which equals 5.
\n
Constraints:
\n\n2 <= start.length <= 105
0 <= start[i] <= 109
0 <= d <= 109
You are given an integer array nums
of length n
.
Your goal is to start at index 0
and reach index n - 1
. You can only jump to indices greater than your current index.
The score for a jump from index i
to index j
is calculated as (j - i) * nums[i]
.
Return the maximum possible total score by the time you reach the last index.
\n\n\n
Example 1:
\n\nInput: nums = [1,3,1,5]
\n\nOutput: 7
\n\nExplanation:
\n\nFirst, jump to index 1 and then jump to the last index. The final score is 1 * 1 + 2 * 3 = 7
.
Example 2:
\n\nInput: nums = [4,3,1,3,2]
\n\nOutput: 16
\n\nExplanation:
\n\nJump directly to the last index. The final score is 4 * 4 = 16
.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
There is a 50 x 50
chessboard with one knight and some pawns on it. You are given two integers kx
and ky
where (kx, ky)
denotes the position of the knight, and a 2D array positions
where positions[i] = [xi, yi]
denotes the position of the pawns on the chessboard.
Alice and Bob play a turn-based game, where Alice goes first. In each player's turn:
\n\nAlice is trying to maximize the sum of the number of moves made by both players until there are no more pawns on the board, whereas Bob tries to minimize them.
\n\nReturn the maximum total number of moves made during the game that Alice can achieve, assuming both players play optimally.
\n\nNote that in one move, a chess knight has eight possible positions it can move to, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
\n\n\n
Example 1:
\n\nInput: kx = 1, ky = 1, positions = [[0,0]]
\n\nOutput: 4
\n\nExplanation:
\n\nThe knight takes 4 moves to reach the pawn at (0, 0)
.
Example 2:
\n\nInput: kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]]
\n\nOutput: 8
\n\nExplanation:
\n\n(2, 2)
and captures it in two moves: (0, 2) -> (1, 4) -> (2, 2)
.(3, 3)
and captures it in two moves: (2, 2) -> (4, 1) -> (3, 3)
.(1, 1)
and captures it in four moves: (3, 3) -> (4, 1) -> (2, 2) -> (0, 3) -> (1, 1)
.Example 3:
\n\nInput: kx = 0, ky = 0, positions = [[1,2],[2,4]]
\n\nOutput: 3
\n\nExplanation:
\n\n(2, 4)
and captures it in two moves: (0, 0) -> (1, 2) -> (2, 4)
. Note that the pawn at (1, 2)
is not captured.(1, 2)
and captures it in one move: (2, 4) -> (1, 2)
.\n
Constraints:
\n\n0 <= kx, ky <= 49
1 <= positions.length <= 15
positions[i].length == 2
0 <= positions[i][0], positions[i][1] <= 49
positions[i]
are unique.positions[i] != [kx, ky]
for all 0 <= i < positions.length
.There are n
mountains in a row, and each mountain has a height. You are given an integer array height
where height[i]
represents the height of mountain i
, and an integer threshold
.
A mountain is called stable if the mountain just before it (if it exists) has a height strictly greater than threshold
. Note that mountain 0 is not stable.
Return an array containing the indices of all stable mountains in any order.
\n\n\n
Example 1:
\n\nInput: height = [1,2,3,4,5], threshold = 2
\n\nOutput: [3,4]
\n\nExplanation:
\n\nheight[2] == 3
is greater than threshold == 2
.height[3] == 4
is greater than threshold == 2
.Example 2:
\n\nInput: height = [10,1,10,1,10], threshold = 3
\n\nOutput: [1,3]
\nExample 3:
\n\nInput: height = [10,1,10,1,10], threshold = 10
\n\nOutput: []
\n\n
Constraints:
\n\n2 <= n == height.length <= 100
1 <= height[i] <= 100
1 <= threshold <= 100
You are given an m x n
binary matrix grid
and an integer health
.
You start on the upper-left corner (0, 0)
and would like to get to the lower-right corner (m - 1, n - 1)
.
You can move up, down, left, or right from one cell to another adjacent cell as long as your health remains positive.
\n\nCells (i, j)
with grid[i][j] = 1
are considered unsafe and reduce your health by 1.
Return true
if you can reach the final cell with a health value of 1 or more, and false
otherwise.
\n
Example 1:
\n\nInput: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1
\n\nOutput: true
\n\nExplanation:
\n\nThe final cell can be reached safely by walking along the gray cells below.
\nExample 2:
\n\nInput: grid = [[0,1,1,0,0,0],[1,0,1,0,0,0],[0,1,1,1,0,1],[0,0,1,0,1,0]], health = 3
\n\nOutput: false
\n\nExplanation:
\n\nA minimum of 4 health points is needed to reach the final cell safely.
\nExample 3:
\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]], health = 5
\n\nOutput: true
\n\nExplanation:
\n\nThe final cell can be reached safely by walking along the gray cells below.
\n\nAny path that does not go through the cell (1, 1)
is unsafe since your health will drop to 0 when reaching the final cell.
\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
2 <= m * n
1 <= health <= m + n
grid[i][j]
is either 0 or 1.You are given an integer array nums
and a positive integer k
.
The value of a sequence seq
of size 2 * x
is defined as:
(seq[0] OR seq[1] OR ... OR seq[x - 1]) XOR (seq[x] OR seq[x + 1] OR ... OR seq[2 * x - 1])
.Return the maximum value of any subsequence of nums
having size 2 * k
.
\n
Example 1:
\n\nInput: nums = [2,6,7], k = 1
\n\nOutput: 5
\n\nExplanation:
\n\nThe subsequence [2, 7]
has the maximum value of 2 XOR 7 = 5
.
Example 2:
\n\nInput: nums = [4,2,5,6,7], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nThe subsequence [4, 5, 6, 7]
has the maximum value of (4 OR 5) XOR (6 OR 7) = 2
.
\n
Constraints:
\n\n2 <= nums.length <= 400
1 <= nums[i] < 27
1 <= k <= nums.length / 2
You are given a 2D array of integers coordinates
of length n
and an integer k
, where 0 <= k < n
.
coordinates[i] = [xi, yi]
indicates the point (xi, yi)
in a 2D plane.
An increasing path of length m
is defined as a list of points (x1, y1)
, (x2, y2)
, (x3, y3)
, ..., (xm, ym)
such that:
xi < xi + 1
and yi < yi + 1
for all i
where 1 <= i < m
.(xi, yi)
is in the given coordinates for all i
where 1 <= i <= m
.Return the maximum length of an increasing path that contains coordinates[k]
.
\n
Example 1:
\n\nInput: coordinates = [[3,1],[2,2],[4,1],[0,0],[5,3]], k = 1
\n\nOutput: 3
\n\nExplanation:
\n\n(0, 0)
, (2, 2)
, (5, 3)
is the longest increasing path that contains (2, 2)
.
Example 2:
\n\nInput: coordinates = [[2,1],[7,0],[5,6]], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\n(2, 1)
, (5, 6)
is the longest increasing path that contains (5, 6)
.
\n
Constraints:
\n\n1 <= n == coordinates.length <= 105
coordinates[i].length == 2
0 <= coordinates[i][0], coordinates[i][1] <= 109
coordinates
are distinct.0 <= k <= n - 1
In the town of Digitville, there was a list of numbers called nums
containing integers from 0
to n - 1
. Each number was supposed to appear exactly once in the list, however, two mischievous numbers sneaked in an additional time, making the list longer than usual.
As the town detective, your task is to find these two sneaky numbers. Return an array of size two containing the two numbers (in any order), so peace can return to Digitville.
\n\n\n
Example 1:
\n\nInput: nums = [0,1,1,0]
\n\nOutput: [0,1]
\n\nExplanation:
\n\nThe numbers 0 and 1 each appear twice in the array.
\nExample 2:
\n\nInput: nums = [0,3,2,1,3,2]
\n\nOutput: [2,3]
\n\nExplanation:
\n\nThe numbers 2 and 3 each appear twice in the array.
\nExample 3:
\n\nInput: nums = [7,1,5,4,3,4,6,0,9,5,8,2]
\n\nOutput: [4,5]
\n\nExplanation:
\n\nThe numbers 4 and 5 each appear twice in the array.
\n\n
Constraints:
\n\n2 <= n <= 100
nums.length == n + 2
0 <= nums[i] < n
nums
contains exactly two repeated elements.You are given an integer array a
of size 4 and another integer array b
of size at least 4.
You need to choose 4 indices i0
, i1
, i2
, and i3
from the array b
such that i0 < i1 < i2 < i3
. Your score will be equal to the value a[0] * b[i0] + a[1] * b[i1] + a[2] * b[i2] + a[3] * b[i3]
.
Return the maximum score you can achieve.
\n\n\n
Example 1:
\n\nInput: a = [3,2,5,6], b = [2,-6,4,-5,-3,2,-7]
\n\nOutput: 26
\n\nExplanation:
\nWe can choose the indices 0, 1, 2, and 5. The score will be 3 * 2 + 2 * (-6) + 5 * 4 + 6 * 2 = 26
.
Example 2:
\n\nInput: a = [-1,4,5,-2], b = [-5,-1,-3,-2,-4]
\n\nOutput: -1
\n\nExplanation:
\nWe can choose the indices 0, 1, 3, and 4. The score will be (-1) * (-5) + 4 * (-1) + 5 * (-2) + (-2) * (-4) = -1
.
\n
Constraints:
\n\na.length == 4
4 <= b.length <= 105
-105 <= a[i], b[i] <= 105
You are given an array of strings words
and a string target
.
A string x
is called valid if x
is a prefix of any string in words
.
Return the minimum number of valid strings that can be concatenated to form target
. If it is not possible to form target
, return -1
.
\n
Example 1:
\n\nInput: words = ["abc","aaaaa","bcdef"], target = "aabcdabc"
\n\nOutput: 3
\n\nExplanation:
\n\nThe target string can be formed by concatenating:
\n\nwords[1]
, i.e. "aa"
.words[2]
, i.e. "bcd"
.words[0]
, i.e. "abc"
.Example 2:
\n\nInput: words = ["abababab","ab"], target = "ababaababa"
\n\nOutput: 2
\n\nExplanation:
\n\nThe target string can be formed by concatenating:
\n\nwords[0]
, i.e. "ababa"
.words[0]
, i.e. "ababa"
.Example 3:
\n\nInput: words = ["abcdef"], target = "xyz"
\n\nOutput: -1
\n\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 5 * 103
sum(words[i].length) <= 105
.words[i]
consists only of lowercase English letters.1 <= target.length <= 5 * 103
target
consists only of lowercase English letters.You are given an array of strings words
and a string target
.
A string x
is called valid if x
is a prefix of any string in words
.
Return the minimum number of valid strings that can be concatenated to form target
. If it is not possible to form target
, return -1
.
\n
Example 1:
\n\nInput: words = ["abc","aaaaa","bcdef"], target = "aabcdabc"
\n\nOutput: 3
\n\nExplanation:
\n\nThe target string can be formed by concatenating:
\n\nwords[1]
, i.e. "aa"
.words[2]
, i.e. "bcd"
.words[0]
, i.e. "abc"
.Example 2:
\n\nInput: words = ["abababab","ab"], target = "ababaababa"
\n\nOutput: 2
\n\nExplanation:
\n\nThe target string can be formed by concatenating:
\n\nwords[0]
, i.e. "ababa"
.words[0]
, i.e. "ababa"
.Example 3:
\n\nInput: words = ["abcdef"], target = "xyz"
\n\nOutput: -1
\n\n
Constraints:
\n\n1 <= words.length <= 100
1 <= words[i].length <= 5 * 104
sum(words[i].length) <= 105
.words[i]
consists only of lowercase English letters.1 <= target.length <= 5 * 104
target
consists only of lowercase English letters.You are given an array of strings message
and an array of strings bannedWords
.
An array of words is considered spam if there are at least two words in it that exactly match any word in bannedWords
.
Return true
if the array message
is spam, and false
otherwise.
\n
Example 1:
\n\nInput: message = ["hello","world","leetcode"], bannedWords = ["world","hello"]
\n\nOutput: true
\n\nExplanation:
\n\nThe words "hello"
and "world"
from the message
array both appear in the bannedWords
array.
Example 2:
\n\nInput: message = ["hello","programming","fun"], bannedWords = ["world","programming","leetcode"]
\n\nOutput: false
\n\nExplanation:
\n\nOnly one word from the message
array ("programming"
) appears in the bannedWords
array.
\n
Constraints:
\n\n1 <= message.length, bannedWords.length <= 105
1 <= message[i].length, bannedWords[i].length <= 15
message[i]
and bannedWords[i]
consist only of lowercase English letters.You are given an integer mountainHeight
denoting the height of a mountain.
You are also given an integer array workerTimes
representing the work time of workers in seconds.
The workers work simultaneously to reduce the height of the mountain. For worker i
:
x
, it takes workerTimes[i] + workerTimes[i] * 2 + ... + workerTimes[i] * x
seconds. For example:\n\n\tworkerTimes[i]
seconds.workerTimes[i] + workerTimes[i] * 2
seconds, and so on.Return an integer representing the minimum number of seconds required for the workers to make the height of the mountain 0.
\n\n\n
Example 1:
\n\nInput: mountainHeight = 4, workerTimes = [2,1,1]
\n\nOutput: 3
\n\nExplanation:
\n\nOne way the height of the mountain can be reduced to 0 is:
\n\nworkerTimes[0] = 2
seconds.workerTimes[1] + workerTimes[1] * 2 = 3
seconds.workerTimes[2] = 1
second.Since they work simultaneously, the minimum time needed is max(2, 3, 1) = 3
seconds.
Example 2:
\n\nInput: mountainHeight = 10, workerTimes = [3,2,2,4]
\n\nOutput: 12
\n\nExplanation:
\n\nworkerTimes[0] + workerTimes[0] * 2 = 9
seconds.workerTimes[1] + workerTimes[1] * 2 + workerTimes[1] * 3 = 12
seconds.workerTimes[2] + workerTimes[2] * 2 + workerTimes[2] * 3 = 12
seconds.workerTimes[3] + workerTimes[3] * 2 = 12
seconds.The number of seconds needed is max(9, 12, 12, 12) = 12
seconds.
Example 3:
\n\nInput: mountainHeight = 5, workerTimes = [1]
\n\nOutput: 15
\n\nExplanation:
\n\nThere is only one worker in this example, so the answer is workerTimes[0] + workerTimes[0] * 2 + workerTimes[0] * 3 + workerTimes[0] * 4 + workerTimes[0] * 5 = 15
.
\n
Constraints:
\n\n1 <= mountainHeight <= 105
1 <= workerTimes.length <= 104
1 <= workerTimes[i] <= 106
You are given two strings word1
and word2
.
A string x
is called valid if x
can be rearranged to have word2
as a prefix.
Return the total number of valid substrings of word1
.
\n
Example 1:
\n\nInput: word1 = "bcca", word2 = "abc"
\n\nOutput: 1
\n\nExplanation:
\n\nThe only valid substring is "bcca"
which can be rearranged to "abcc"
having "abc"
as a prefix.
Example 2:
\n\nInput: word1 = "abcabc", word2 = "abc"
\n\nOutput: 10
\n\nExplanation:
\n\nAll the substrings except substrings of size 1 and size 2 are valid.
\nExample 3:
\n\nInput: word1 = "abcabc", word2 = "aaabc"
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= word1.length <= 105
1 <= word2.length <= 104
word1
and word2
consist only of lowercase English letters.You are given two strings word1
and word2
.
A string x
is called valid if x
can be rearranged to have word2
as a prefix.
Return the total number of valid substrings of word1
.
Note that the memory limits in this problem are smaller than usual, so you must implement a solution with a linear runtime complexity.
\n\n\n
Example 1:
\n\nInput: word1 = "bcca", word2 = "abc"
\n\nOutput: 1
\n\nExplanation:
\n\nThe only valid substring is "bcca"
which can be rearranged to "abcc"
having "abc"
as a prefix.
Example 2:
\n\nInput: word1 = "abcabc", word2 = "abc"
\n\nOutput: 10
\n\nExplanation:
\n\nAll the substrings except substrings of size 1 and size 2 are valid.
\nExample 3:
\n\nInput: word1 = "abcabc", word2 = "aaabc"
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= word1.length <= 106
1 <= word2.length <= 104
word1
and word2
consist only of lowercase English letters.You are given an integer array nums
.
You replace each element in nums
with the sum of its digits.
Return the minimum element in nums
after all replacements.
\n
Example 1:
\n\nInput: nums = [10,12,13,14]
\n\nOutput: 1
\n\nExplanation:
\n\nnums
becomes [1, 3, 4, 5]
after all replacements, with minimum element 1.
Example 2:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 1
\n\nExplanation:
\n\nnums
becomes [1, 2, 3, 4]
after all replacements, with minimum element 1.
Example 3:
\n\nInput: nums = [999,19,199]
\n\nOutput: 10
\n\nExplanation:
\n\nnums
becomes [27, 10, 19]
after all replacements, with minimum element 10.
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 104
You are given an array maximumHeight
, where maximumHeight[i]
denotes the maximum height the ith
tower can be assigned.
Your task is to assign a height to each tower so that:
\n\nith
tower is a positive integer and does not exceed maximumHeight[i]
.Return the maximum possible total sum of the tower heights. If it's not possible to assign heights, return -1
.
\n
Example 1:
\n\nInput: maximumHeight = [2,3,4,3]
\n\nOutput: 10
\n\nExplanation:
\n\nWe can assign heights in the following way: [1, 2, 4, 3]
.
Example 2:
\n\nInput: maximumHeight = [15,10]
\n\nOutput: 25
\n\nExplanation:
\n\nWe can assign heights in the following way: [15, 10]
.
Example 3:
\n\nInput: maximumHeight = [2,2,1]
\n\nOutput: -1
\n\nExplanation:
\n\nIt's impossible to assign positive heights to each index so that no two towers have the same height.
\n\n
Constraints:
\n\n1 <= maximumHeight.length <= 105
1 <= maximumHeight[i] <= 109
You are given two strings word1
and word2
.
A string x
is called almost equal to y
if you can change at most one character in x
to make it identical to y
.
A sequence of indices seq
is called valid if:
word1
in the same order results in a string that is almost equal to word2
.Return an array of size word2.length
representing the lexicographically smallest valid sequence of indices. If no such sequence of indices exists, return an empty array.
Note that the answer must represent the lexicographically smallest array, not the corresponding string formed by those indices.
\n\n\n
Example 1:
\n\nInput: word1 = "vbcca", word2 = "abc"
\n\nOutput: [0,1,2]
\n\nExplanation:
\n\nThe lexicographically smallest valid sequence of indices is [0, 1, 2]
:
word1[0]
to 'a'
.word1[1]
is already 'b'
.word1[2]
is already 'c'
.Example 2:
\n\nInput: word1 = "bacdc", word2 = "abc"
\n\nOutput: [1,2,4]
\n\nExplanation:
\n\nThe lexicographically smallest valid sequence of indices is [1, 2, 4]
:
word1[1]
is already 'a'
.word1[2]
to 'b'
.word1[4]
is already 'c'
.Example 3:
\n\nInput: word1 = "aaaaaa", word2 = "aaabc"
\n\nOutput: []
\n\nExplanation:
\n\nThere is no valid sequence of indices.
\nExample 4:
\n\nInput: word1 = "abc", word2 = "ab"
\n\nOutput: [0,1]
\n\n
Constraints:
\n\n1 <= word2.length < word1.length <= 3 * 105
word1
and word2
consist only of lowercase English letters.You are given two strings s
and pattern
.
A string x
is called almost equal to y
if you can change at most one character in x
to make it identical to y
.
Return the smallest starting index of a substring in s
that is almost equal to pattern
. If no such index exists, return -1
.
\n
Example 1:
\n\nInput: s = "abcdefg", pattern = "bcdffg"
\n\nOutput: 1
\n\nExplanation:
\n\nThe substring s[1..6] == "bcdefg"
can be converted to "bcdffg"
by changing s[4]
to "f"
.
Example 2:
\n\nInput: s = "ababbababa", pattern = "bacaba"
\n\nOutput: 4
\n\nExplanation:
\n\nThe substring s[4..9] == "bababa"
can be converted to "bacaba"
by changing s[6]
to "c"
.
Example 3:
\n\nInput: s = "abcd", pattern = "dba"
\n\nOutput: -1
\nExample 4:
\n\nInput: s = "dde", pattern = "d"
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= pattern.length < s.length <= 105
s
and pattern
consist only of lowercase English letters.\nFollow-up: Could you solve the problem if at most
k
consecutive characters can be changed?",
- "likes": 58,
- "dislikes": 6,
- "stats": "{\"totalAccepted\": \"3.7K\", \"totalSubmission\": \"29.1K\", \"totalAcceptedRaw\": 3710, \"totalSubmissionRaw\": 29129, \"acRate\": \"12.7%\"}",
+ "likes": 66,
+ "dislikes": 8,
+ "stats": "{\"totalAccepted\": \"4.6K\", \"totalSubmission\": \"32.9K\", \"totalAcceptedRaw\": 4567, \"totalSubmissionRaw\": 32863, \"acRate\": \"13.9%\"}",
"similarQuestions": "[{\"title\": \"Check Whether Two Strings are Almost Equivalent\", \"titleSlug\": \"check-whether-two-strings-are-almost-equivalent\", \"difficulty\": \"Easy\", \"translatedTitle\": null}, {\"title\": \"Count Almost Equal Pairs II\", \"titleSlug\": \"count-almost-equal-pairs-ii\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]",
"categoryTitle": "Algorithms",
"hints": [
@@ -124236,9 +124556,9 @@
"questionFrontendId": "3304",
"title": "Find the K-th Character in String Game I",
"content": "Alice and Bob are playing a game. Initially, Alice has a string word = "a"
.
You are given a positive integer k
.
Now Bob will ask Alice to perform the following operation forever:
\n\nword
to its next character in the English alphabet, and append it to the original word
.For example, performing the operation on "c"
generates "cd"
and performing the operation on "zb"
generates "zbac"
.
Return the value of the kth
character in word
, after enough operations have been done for word
to have at least k
characters.
Note that the character 'z'
can be changed to 'a'
in the operation.
\n
Example 1:
\n\nInput: k = 5
\n\nOutput: "b"
\n\nExplanation:
\n\nInitially, word = "a"
. We need to do the operation three times:
"b"
, word
becomes "ab"
."bc"
, word
becomes "abbc"
."bccd"
, word
becomes "abbcbccd"
.Example 2:
\n\nInput: k = 10
\n\nOutput: "c"
\n\n
Constraints:
\n\n1 <= k <= 500
You are given a string word
and a non-negative integer k
.
Return the total number of substrings of word
that contain every vowel ('a'
, 'e'
, 'i'
, 'o'
, and 'u'
) at least once and exactly k
consonants.
\n
Example 1:
\n\nInput: word = "aeioqq", k = 1
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no substring with every vowel.
\nExample 2:
\n\nInput: word = "aeiou", k = 0
\n\nOutput: 1
\n\nExplanation:
\n\nThe only substring with every vowel and zero consonants is word[0..4]
, which is "aeiou"
.
Example 3:
\n\nInput: word = "ieaouqqieaouqq", k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nThe substrings with every vowel and one consonant are:
\n\nword[0..5]
, which is "ieaouq"
.word[6..11]
, which is "qieaou"
.word[7..12]
, which is "ieaouq"
.\n
Constraints:
\n\n5 <= word.length <= 250
word
consists only of lowercase English letters.0 <= k <= word.length - 5
You are given a string word
and a non-negative integer k
.
Return the total number of substrings of word
that contain every vowel ('a'
, 'e'
, 'i'
, 'o'
, and 'u'
) at least once and exactly k
consonants.
\n
Example 1:
\n\nInput: word = "aeioqq", k = 1
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no substring with every vowel.
\nExample 2:
\n\nInput: word = "aeiou", k = 0
\n\nOutput: 1
\n\nExplanation:
\n\nThe only substring with every vowel and zero consonants is word[0..4]
, which is "aeiou"
.
Example 3:
\n\nInput: word = "ieaouqqieaouqq", k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nThe substrings with every vowel and one consonant are:
\n\nword[0..5]
, which is "ieaouq"
.word[6..11]
, which is "qieaou"
.word[7..12]
, which is "ieaouq"
.\n
Constraints:
\n\n5 <= word.length <= 2 * 105
word
consists only of lowercase English letters.0 <= k <= word.length - 5
Alice and Bob are playing a game. Initially, Alice has a string word = "a"
.
You are given a positive integer k
. You are also given an integer array operations
, where operations[i]
represents the type of the ith
operation.
Now Bob will ask Alice to perform all operations in sequence:
\n\noperations[i] == 0
, append a copy of word
to itself.operations[i] == 1
, generate a new string by changing each character in word
to its next character in the English alphabet, and append it to the original word
. For example, performing the operation on "c"
generates "cd"
and performing the operation on "zb"
generates "zbac"
.Return the value of the kth
character in word
after performing all the operations.
Note that the character 'z'
can be changed to 'a'
in the second type of operation.
\n
Example 1:
\n\nInput: k = 5, operations = [0,0,0]
\n\nOutput: "a"
\n\nExplanation:
\n\nInitially, word == "a"
. Alice performs the three operations as follows:
"a"
to "a"
, word
becomes "aa"
."aa"
to "aa"
, word
becomes "aaaa"
."aaaa"
to "aaaa"
, word
becomes "aaaaaaaa"
.Example 2:
\n\nInput: k = 10, operations = [0,1,0,1]
\n\nOutput: "b"
\n\nExplanation:
\n\nInitially, word == "a"
. Alice performs the four operations as follows:
"a"
to "a"
, word
becomes "aa"
."bb"
to "aa"
, word
becomes "aabb"
."aabb"
to "aabb"
, word
becomes "aabbaabb"
."bbccbbcc"
to "aabbaabb"
, word
becomes "aabbaabbbbccbbcc"
.\n
Constraints:
\n\n1 <= k <= 1014
1 <= operations.length <= 100
operations[i]
is either 0 or 1.word
has at least k
characters after all operations.You are given an array of integers nums
of size 3.
Return the maximum possible number whose binary representation can be formed by concatenating the binary representation of all elements in nums
in some order.
Note that the binary representation of any number does not contain leading zeros.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3]
\n\nOutput: 30
\n\nExplanation:
\n\nConcatenate the numbers in the order [3, 1, 2]
to get the result "11110"
, which is the binary representation of 30.
Example 2:
\n\nInput: nums = [2,8,16]
\n\nOutput: 1296
\n\nExplanation:
\n\nConcatenate the numbers in the order [2, 8, 16]
to get the result "10100010000"
, which is the binary representation of 1296.
\n
Constraints:
\n\nnums.length == 3
1 <= nums[i] <= 127
You are maintaining a project that has n
methods numbered from 0
to n - 1
.
You are given two integers n
and k
, and a 2D integer array invocations
, where invocations[i] = [ai, bi]
indicates that method ai
invokes method bi
.
There is a known bug in method k
. Method k
, along with any method invoked by it, either directly or indirectly, are considered suspicious and we aim to remove them.
A group of methods can only be removed if no method outside the group invokes any methods within it.
\n\nReturn an array containing all the remaining methods after removing all the suspicious methods. You may return the answer in any order. If it is not possible to remove all the suspicious methods, none should be removed.
\n\n\n
Example 1:
\n\nInput: n = 4, k = 1, invocations = [[1,2],[0,1],[3,2]]
\n\nOutput: [0,1,2,3]
\n\nExplanation:
\n\nMethod 2 and method 1 are suspicious, but they are directly invoked by methods 3 and 0, which are not suspicious. We return all elements without removing anything.
\nExample 2:
\n\nInput: n = 5, k = 0, invocations = [[1,2],[0,2],[0,1],[3,4]]
\n\nOutput: [3,4]
\n\nExplanation:
\n\nMethods 0, 1, and 2 are suspicious and they are not directly invoked by any other method. We can remove them.
\nExample 3:
\n\nInput: n = 3, k = 2, invocations = [[1,2],[0,1],[2,0]]
\n\nOutput: []
\n\nExplanation:
\n\nAll methods are suspicious. We can remove them.
\n\n
Constraints:
\n\n1 <= n <= 105
0 <= k <= n - 1
0 <= invocations.length <= 2 * 105
invocations[i] == [ai, bi]
0 <= ai, bi <= n - 1
ai != bi
invocations[i] != invocations[j]
You are given a 2D integer array edges
representing an undirected graph having n
nodes, where edges[i] = [ui, vi]
denotes an edge between nodes ui
and vi
.
Construct a 2D grid that satisfies these conditions:
\n\n0
to n - 1
in its cells, with each node appearing exactly once.edges
.It is guaranteed that edges
can form a 2D grid that satisfies the conditions.
Return a 2D integer array satisfying the conditions above. If there are multiple solutions, return any of them.
\n\n\n
Example 1:
\n\nInput: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]]
\n\nOutput: [[3,1],[2,0]]
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 5, edges = [[0,1],[1,3],[2,3],[2,4]]
\n\nOutput: [[4,2,3,1,0]]
\n\nExplanation:
\n\nExample 3:
\n\nInput: n = 9, edges = [[0,1],[0,4],[0,5],[1,7],[2,3],[2,4],[2,5],[3,6],[4,6],[4,7],[6,8],[7,8]]
\n\nOutput: [[8,6,3],[7,4,2],[1,0,5]]
\n\nExplanation:
\n\n\n
Constraints:
\n\n2 <= n <= 5 * 104
1 <= edges.length <= 105
edges[i] = [ui, vi]
0 <= ui < vi < n
edges
can form a 2D grid that satisfies the conditions.You are given an integer array nums
of length n
and an integer array queries
.
Let gcdPairs
denote an array obtained by calculating the GCD of all possible pairs (nums[i], nums[j])
, where 0 <= i < j < n
, and then sorting these values in ascending order.
For each query queries[i]
, you need to find the element at index queries[i]
in gcdPairs
.
Return an integer array answer
, where answer[i]
is the value at gcdPairs[queries[i]]
for each query.
The term gcd(a, b)
denotes the greatest common divisor of a
and b
.
\n
Example 1:
\n\nInput: nums = [2,3,4], queries = [0,2,2]
\n\nOutput: [1,2,2]
\n\nExplanation:
\n\ngcdPairs = [gcd(nums[0], nums[1]), gcd(nums[0], nums[2]), gcd(nums[1], nums[2])] = [1, 2, 1]
.
After sorting in ascending order, gcdPairs = [1, 1, 2]
.
So, the answer is [gcdPairs[queries[0]], gcdPairs[queries[1]], gcdPairs[queries[2]]] = [1, 2, 2]
.
Example 2:
\n\nInput: nums = [4,4,2,1], queries = [5,3,1,0]
\n\nOutput: [4,2,1,1]
\n\nExplanation:
\n\ngcdPairs
sorted in ascending order is [1, 1, 1, 2, 2, 4]
.
Example 3:
\n\nInput: nums = [2,2], queries = [0,0]
\n\nOutput: [2,2]
\n\nExplanation:
\n\ngcdPairs = [2]
.
\n
Constraints:
\n\n2 <= n == nums.length <= 105
1 <= nums[i] <= 5 * 104
1 <= queries.length <= 105
0 <= queries[i] < n * (n - 1) / 2
You are given an array nums
consisting of n
prime integers.
You need to construct an array ans
of length n
, such that, for each index i
, the bitwise OR
of ans[i]
and ans[i] + 1
is equal to nums[i]
, i.e. ans[i] OR (ans[i] + 1) == nums[i]
.
Additionally, you must minimize each value of ans[i]
in the resulting array.
If it is not possible to find such a value for ans[i]
that satisfies the condition, then set ans[i] = -1
.
\n
Example 1:
\n\nInput: nums = [2,3,5,7]
\n\nOutput: [-1,1,4,3]
\n\nExplanation:
\n\ni = 0
, as there is no value for ans[0]
that satisfies ans[0] OR (ans[0] + 1) = 2
, so ans[0] = -1
.i = 1
, the smallest ans[1]
that satisfies ans[1] OR (ans[1] + 1) = 3
is 1
, because 1 OR (1 + 1) = 3
.i = 2
, the smallest ans[2]
that satisfies ans[2] OR (ans[2] + 1) = 5
is 4
, because 4 OR (4 + 1) = 5
.i = 3
, the smallest ans[3]
that satisfies ans[3] OR (ans[3] + 1) = 7
is 3
, because 3 OR (3 + 1) = 7
.Example 2:
\n\nInput: nums = [11,13,31]
\n\nOutput: [9,12,15]
\n\nExplanation:
\n\ni = 0
, the smallest ans[0]
that satisfies ans[0] OR (ans[0] + 1) = 11
is 9
, because 9 OR (9 + 1) = 11
.i = 1
, the smallest ans[1]
that satisfies ans[1] OR (ans[1] + 1) = 13
is 12
, because 12 OR (12 + 1) = 13
.i = 2
, the smallest ans[2]
that satisfies ans[2] OR (ans[2] + 1) = 31
is 15
, because 15 OR (15 + 1) = 31
.\n
Constraints:
\n\n1 <= nums.length <= 100
2 <= nums[i] <= 1000
nums[i]
is a prime number.You are given an array nums
consisting of n
prime integers.
You need to construct an array ans
of length n
, such that, for each index i
, the bitwise OR
of ans[i]
and ans[i] + 1
is equal to nums[i]
, i.e. ans[i] OR (ans[i] + 1) == nums[i]
.
Additionally, you must minimize each value of ans[i]
in the resulting array.
If it is not possible to find such a value for ans[i]
that satisfies the condition, then set ans[i] = -1
.
\n
Example 1:
\n\nInput: nums = [2,3,5,7]
\n\nOutput: [-1,1,4,3]
\n\nExplanation:
\n\ni = 0
, as there is no value for ans[0]
that satisfies ans[0] OR (ans[0] + 1) = 2
, so ans[0] = -1
.i = 1
, the smallest ans[1]
that satisfies ans[1] OR (ans[1] + 1) = 3
is 1
, because 1 OR (1 + 1) = 3
.i = 2
, the smallest ans[2]
that satisfies ans[2] OR (ans[2] + 1) = 5
is 4
, because 4 OR (4 + 1) = 5
.i = 3
, the smallest ans[3]
that satisfies ans[3] OR (ans[3] + 1) = 7
is 3
, because 3 OR (3 + 1) = 7
.Example 2:
\n\nInput: nums = [11,13,31]
\n\nOutput: [9,12,15]
\n\nExplanation:
\n\ni = 0
, the smallest ans[0]
that satisfies ans[0] OR (ans[0] + 1) = 11
is 9
, because 9 OR (9 + 1) = 11
.i = 1
, the smallest ans[1]
that satisfies ans[1] OR (ans[1] + 1) = 13
is 12
, because 12 OR (12 + 1) = 13
.i = 2
, the smallest ans[2]
that satisfies ans[2] OR (ans[2] + 1) = 31
is 15
, because 15 OR (15 + 1) = 31
.\n
Constraints:
\n\n1 <= nums.length <= 100
2 <= nums[i] <= 109
nums[i]
is a prime number.You are given a string source
of size n
, a string pattern
that is a subsequence of source
, and a sorted integer array targetIndices
that contains distinct numbers in the range [0, n - 1]
.
We define an operation as removing a character at an index idx
from source
such that:
idx
is an element of targetIndices
.pattern
remains a subsequence of source
after removing the character.Performing an operation does not change the indices of the other characters in source
. For example, if you remove 'c'
from "acb"
, the character at index 2 would still be 'b'
.
Return the maximum number of operations that can be performed.
\n\n\n
Example 1:
\n\nInput: source = "abbaa", pattern = "aba", targetIndices = [0,1,2]
\n\nOutput: 1
\n\nExplanation:
\n\nWe can't remove source[0]
but we can do either of these two operations:
source[1]
, so that source
becomes "a_baa"
.source[2]
, so that source
becomes "ab_aa"
.Example 2:
\n\nInput: source = "bcda", pattern = "d", targetIndices = [0,3]
\n\nOutput: 2
\n\nExplanation:
\n\nWe can remove source[0]
and source[3]
in two operations.
Example 3:
\n\nInput: source = "dda", pattern = "dda", targetIndices = [0,1,2]
\n\nOutput: 0
\n\nExplanation:
\n\nWe can't remove any character from source
.
Example 4:
\n\nInput: source = "yeyeykyded", pattern = "yeyyd", targetIndices = [0,2,3,4]
\n\nOutput: 2
\n\nExplanation:
\n\nWe can remove source[2]
and source[3]
in two operations.
\n
Constraints:
\n\n1 <= n == source.length <= 3 * 103
1 <= pattern.length <= n
1 <= targetIndices.length <= n
targetIndices
is sorted in ascending order.targetIndices
contains distinct elements in the range [0, n - 1]
.source
and pattern
consist only of lowercase English letters.pattern
appears as a subsequence in source
.You are given three integers n
, x
, and y
.
An event is being held for n
performers. When a performer arrives, they are assigned to one of the x
stages. All performers assigned to the same stage will perform together as a band, though some stages might remain empty.
After all performances are completed, the jury will award each band a score in the range [1, y]
.
Return the total number of possible ways the event can take place.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
Note that two events are considered to have been held differently if either of the following conditions is satisfied:
\n\n\n
Example 1:
\n\nInput: n = 1, x = 2, y = 3
\n\nOutput: 6
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 5, x = 2, y = 1
\n\nOutput: 32
\n\nExplanation:
\n\nExample 3:
\n\nInput: n = 3, x = 3, y = 4
\n\nOutput: 684
\n\n
Constraints:
\n\n1 <= n, x, y <= 1000
You are given an array nums
of n
integers and two integers k
and x
.
The x-sum of an array is calculated by the following procedure:
\n\nx
most frequent elements. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent.Note that if an array has less than x
distinct elements, its x-sum is the sum of the array.
Return an integer array answer
of length n - k + 1
where answer[i]
is the x-sum of the subarray nums[i..i + k - 1]
.
\n
Example 1:
\n\nInput: nums = [1,1,2,2,3,4,2,3], k = 6, x = 2
\n\nOutput: [6,10,12]
\n\nExplanation:
\n\n[1, 1, 2, 2, 3, 4]
, only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2
.[1, 2, 2, 3, 4, 2]
, only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4
. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.[2, 2, 3, 4, 2, 3]
, only elements 2 and 3 are kept in the resulting array. Hence, answer[2] = 2 + 2 + 2 + 3 + 3
.Example 2:
\n\nInput: nums = [3,8,7,8,7,5], k = 2, x = 2
\n\nOutput: [11,15,15,15,12]
\n\nExplanation:
\n\nSince k == x
, answer[i]
is equal to the sum of the subarray nums[i..i + k - 1]
.
\n
Constraints:
\n\n1 <= n == nums.length <= 50
1 <= nums[i] <= 50
1 <= x <= k <= nums.length
You are given the root
of a binary tree and an integer k
.
Return an integer denoting the size of the kth
largest perfect binary subtree, or -1
if it doesn't exist.
A perfect binary tree is a tree where all leaves are on the same level, and every parent has two children.
\n\n\n
Example 1:
\n\nInput: root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2
\n\nOutput: 3
\n\nExplanation:
\n\nThe roots of the perfect binary subtrees are highlighted in black. Their sizes, in non-increasing order are [3, 3, 1, 1, 1, 1, 1, 1]
.
\nThe 2nd
largest size is 3.
Example 2:
\n\nInput: root = [1,2,3,4,5,6,7], k = 1
\n\nOutput: 7
\n\nExplanation:
\n\nThe sizes of the perfect binary subtrees in non-increasing order are [7, 3, 3, 1, 1, 1, 1]
. The size of the largest perfect binary subtree is 7.
Example 3:
\n\nInput: root = [1,2,3,null,4], k = 3
\n\nOutput: -1
\n\nExplanation:
\n\nThe sizes of the perfect binary subtrees in non-increasing order are [1, 1]
. There are fewer than 3 perfect binary subtrees.
\n
Constraints:
\n\n[1, 2000]
.1 <= Node.val <= 2000
1 <= k <= 1024
Alice and Bob are playing a fantasy battle game consisting of n
rounds where they summon one of three magical creatures each round: a Fire Dragon, a Water Serpent, or an Earth Golem. In each round, players simultaneously summon their creature and are awarded points as follows:
You are given a string s
consisting of n
characters 'F'
, 'W'
, and 'E'
, representing the sequence of creatures Alice will summon in each round:
s[i] == 'F'
, Alice summons a Fire Dragon.s[i] == 'W'
, Alice summons a Water Serpent.s[i] == 'E'
, Alice summons an Earth Golem.Bob’s sequence of moves is unknown, but it is guaranteed that Bob will never summon the same creature in two consecutive rounds. Bob beats Alice if the total number of points awarded to Bob after n
rounds is strictly greater than the points awarded to Alice.
Return the number of distinct sequences Bob can use to beat Alice.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: s = "FFF"
\n\nOutput: 3
\n\nExplanation:
\n\nBob can beat Alice by making one of the following sequences of moves: "WFW"
, "FWF"
, or "WEW"
. Note that other winning sequences like "WWE"
or "EWW"
are invalid since Bob cannot make the same move twice in a row.
Example 2:
\n\nInput: s = "FWEFW"
\n\nOutput: 18
\n\nExplanation:
\n\n"FWFWF"
, "FWFWE"
, "FWEFE"
, "FWEWE"
, "FEFWF"
, "FEFWE"
, "FEFEW"
, "FEWFE"
, "WFEFE"
, "WFEWE"
, "WEFWF"
, "WEFWE"
, "WEFEF"
, "WEFEW"
, "WEWFW"
, "WEWFE"
, "EWFWE"
, or "EWEWE"
.
\n
Constraints:
\n\n1 <= s.length <= 1000
s[i]
is one of 'F'
, 'W'
, or 'E'
.You are given an array nums
of n
integers and two integers k
and x
.
The x-sum of an array is calculated by the following procedure:
\n\nx
most frequent elements. If two elements have the same number of occurrences, the element with the bigger value is considered more frequent.Note that if an array has less than x
distinct elements, its x-sum is the sum of the array.
Return an integer array answer
of length n - k + 1
where answer[i]
is the x-sum of the subarray nums[i..i + k - 1]
.
\n
Example 1:
\n\nInput: nums = [1,1,2,2,3,4,2,3], k = 6, x = 2
\n\nOutput: [6,10,12]
\n\nExplanation:
\n\n[1, 1, 2, 2, 3, 4]
, only elements 1 and 2 will be kept in the resulting array. Hence, answer[0] = 1 + 1 + 2 + 2
.[1, 2, 2, 3, 4, 2]
, only elements 2 and 4 will be kept in the resulting array. Hence, answer[1] = 2 + 2 + 2 + 4
. Note that 4 is kept in the array since it is bigger than 3 and 1 which occur the same number of times.[2, 2, 3, 4, 2, 3]
, only elements 2 and 3 are kept in the resulting array. Hence, answer[2] = 2 + 2 + 2 + 3 + 3
.Example 2:
\n\nInput: nums = [3,8,7,8,7,5], k = 2, x = 2
\n\nOutput: [11,15,15,15,12]
\n\nExplanation:
\n\nSince k == x
, answer[i]
is equal to the sum of the subarray nums[i..i + k - 1]
.
\n
Constraints:
\n\nnums.length == n
1 <= n <= 105
1 <= nums[i] <= 109
1 <= x <= k <= nums.length
You are given a string target
.
Alice is going to type target
on her computer using a special keyboard that has only two keys:
"a"
to the string on the screen."c"
changes to "d"
and "z"
changes to "a"
.Note that initially there is an empty string ""
on the screen, so she can only press key 1.
Return a list of all strings that appear on the screen as Alice types target
, in the order they appear, using the minimum key presses.
\n
Example 1:
\n\nInput: target = "abc"
\n\nOutput: ["a","aa","ab","aba","abb","abc"]
\n\nExplanation:
\n\nThe sequence of key presses done by Alice are:
\n\n"a"
."aa"
."ab"
."aba"
."abb"
."abc"
.Example 2:
\n\nInput: target = "he"
\n\nOutput: ["a","b","c","d","e","f","g","h","ha","hb","hc","hd","he"]
\n\n
Constraints:
\n\n1 <= target.length <= 400
target
consists only of lowercase English letters.Given a string s
and an integer k
, return the total number of substrings of s
where at least one character appears at least k
times.
\n
Example 1:
\n\nInput: s = "abacb", k = 2
\n\nOutput: 4
\n\nExplanation:
\n\nThe valid substrings are:
\n\n"aba"
(character 'a'
appears 2 times)."abac"
(character 'a'
appears 2 times)."abacb"
(character 'a'
appears 2 times)."bacb"
(character 'b'
appears 2 times).Example 2:
\n\nInput: s = "abcde", k = 1
\n\nOutput: 15
\n\nExplanation:
\n\nAll substrings are valid because every character appears at least once.
\n\n
Constraints:
\n\n1 <= s.length <= 3000
1 <= k <= s.length
s
consists only of lowercase English letters.You are given an integer array nums
.
Any positive divisor of a natural number x
that is strictly less than x
is called a proper divisor of x
. For example, 2 is a proper divisor of 4, while 6 is not a proper divisor of 6.
You are allowed to perform an operation any number of times on nums
, where in each operation you select any one element from nums
and divide it by its greatest proper divisor.
Return the minimum number of operations required to make the array non-decreasing.
\n\nIf it is not possible to make the array non-decreasing using any number of operations, return -1
.
\n
Example 1:
\n\nInput: nums = [25,7]
\n\nOutput: 1
\n\nExplanation:
\n\nUsing a single operation, 25 gets divided by 5 and nums
becomes [5, 7]
.
Example 2:
\n\nInput: nums = [7,7,6]
\n\nOutput: -1
\nExample 3:
\n\nInput: nums = [1,1,1,1]
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 106
You are given a tree rooted at node 0, consisting of n
nodes numbered from 0
to n - 1
. The tree is represented by an array parent
of size n
, where parent[i]
is the parent of node i
. Since node 0 is the root, parent[0] == -1
.
You are also given a string s
of length n
, where s[i]
is the character assigned to node i
.
Consider an empty string dfsStr
, and define a recursive function dfs(int x)
that takes a node x
as a parameter and performs the following steps in order:
y
of x
in increasing order of their numbers, and call dfs(y)
.s[x]
to the end of the string dfsStr
.Note that dfsStr
is shared across all recursive calls of dfs
.
You need to find a boolean array answer
of size n
, where for each index i
from 0
to n - 1
, you do the following:
dfsStr
and call dfs(i)
.dfsStr
is a palindrome, then set answer[i]
to true
. Otherwise, set answer[i]
to false
.Return the array answer
.
\n
Example 1:
\nInput: parent = [-1,0,0,1,1,2], s = "aababa"
\n\nOutput: [true,true,false,true,true,true]
\n\nExplanation:
\n\ndfs(0)
results in the string dfsStr = "abaaba"
, which is a palindrome.dfs(1)
results in the string dfsStr = "aba"
, which is a palindrome.dfs(2)
results in the string dfsStr = "ab"
, which is not a palindrome.dfs(3)
results in the string dfsStr = "a"
, which is a palindrome.dfs(4)
results in the string dfsStr = "b"
, which is a palindrome.dfs(5)
results in the string dfsStr = "a"
, which is a palindrome.Example 2:
\nInput: parent = [-1,0,0,0,0], s = "aabcb"
\n\nOutput: [true,true,true,true,true]
\n\nExplanation:
\n\nEvery call on dfs(x)
results in a palindrome string.
\n
Constraints:
\n\nn == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1
for all i >= 1
.parent[0] == -1
parent
represents a valid tree.s
consists only of lowercase English letters.Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and may press a key for too long, resulting in a character being typed multiple times.
\n\nAlthough Alice tried to focus on her typing, she is aware that she may still have done this at most once.
\n\nYou are given a string word
, which represents the final output displayed on Alice's screen.
Return the total number of possible original strings that Alice might have intended to type.
\n\n\n
Example 1:
\n\nInput: word = "abbcccc"
\n\nOutput: 5
\n\nExplanation:
\n\nThe possible strings are: "abbcccc"
, "abbccc"
, "abbcc"
, "abbc"
, and "abcccc"
.
Example 2:
\n\nInput: word = "abcd"
\n\nOutput: 1
\n\nExplanation:
\n\nThe only possible string is "abcd"
.
Example 3:
\n\nInput: word = "aaaa"
\n\nOutput: 4
\n\n
Constraints:
\n\n1 <= word.length <= 100
word
consists only of lowercase English letters.You are given a tree rooted at node 0 that consists of n
nodes numbered from 0
to n - 1
. The tree is represented by an array parent
of size n
, where parent[i]
is the parent of node i
. Since node 0 is the root, parent[0] == -1
.
You are also given a string s
of length n
, where s[i]
is the character assigned to node i
.
We make the following changes on the tree one time simultaneously for all nodes x
from 1
to n - 1
:
y
to node x
such that y
is an ancestor of x
, and s[x] == s[y]
.y
does not exist, do nothing.x
and its current parent and make node y
the new parent of x
by adding an edge between them.Return an array answer
of size n
where answer[i]
is the size of the subtree rooted at node i
in the final tree.
\n
Example 1:
\n\nInput: parent = [-1,0,0,1,1,1], s = "abaabc"
\n\nOutput: [6,3,1,1,1,1]
\n\nExplanation:
\nThe parent of node 3 will change from node 1 to node 0.
\nExample 2:
\n\nInput: parent = [-1,0,4,0,1], s = "abbba"
\n\nOutput: [5,2,1,1,1]
\n\nExplanation:
\nThe following changes will happen at the same time:
\n\n\n
Constraints:
\n\nn == parent.length == s.length
1 <= n <= 105
0 <= parent[i] <= n - 1
for all i >= 1
.parent[0] == -1
parent
represents a valid tree.s
consists only of lowercase English letters.You are given two integers, n
and k
, along with two 2D integer arrays, stayScore
and travelScore
.
A tourist is visiting a country with n
cities, where each city is directly connected to every other city. The tourist's journey consists of exactly k
0-indexed days, and they can choose any city as their starting point.
Each day, the tourist has two choices:
\n\ncurr
during day i
, they will earn stayScore[i][curr]
points.curr
to city dest
, they will earn travelScore[curr][dest]
points.Return the maximum possible points the tourist can earn.
\n\n\n
Example 1:
\n\nInput: n = 2, k = 1, stayScore = [[2,3]], travelScore = [[0,2],[1,0]]
\n\nOutput: 3
\n\nExplanation:
\n\nThe tourist earns the maximum number of points by starting in city 1 and staying in that city.
\nExample 2:
\n\nInput: n = 3, k = 2, stayScore = [[3,4,2],[2,1,2]], travelScore = [[0,2,1],[2,0,4],[3,2,0]]
\n\nOutput: 8
\n\nExplanation:
\n\nThe tourist earns the maximum number of points by starting in city 1, staying in that city on day 0, and traveling to city 2 on day 1.
\n\n
Constraints:
\n\n1 <= n <= 200
1 <= k <= 200
n == travelScore.length == travelScore[i].length == stayScore[i].length
k == stayScore.length
1 <= stayScore[i][j] <= 100
0 <= travelScore[i][j] <= 100
travelScore[i][i] == 0
Alice is attempting to type a specific string on her computer. However, she tends to be clumsy and may press a key for too long, resulting in a character being typed multiple times.
\n\nYou are given a string word
, which represents the final output displayed on Alice's screen. You are also given a positive integer k
.
Return the total number of possible original strings that Alice might have intended to type, if she was trying to type a string of size at least k
.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: word = "aabbccdd", k = 7
\n\nOutput: 5
\n\nExplanation:
\n\nThe possible strings are: "aabbccdd"
, "aabbccd"
, "aabbcdd"
, "aabccdd"
, and "abbccdd"
.
Example 2:
\n\nInput: word = "aabbccdd", k = 8
\n\nOutput: 1
\n\nExplanation:
\n\nThe only possible string is "aabbccdd"
.
Example 3:
\n\nInput: word = "aaabbb", k = 3
\n\nOutput: 8
\n\n
Constraints:
\n\n1 <= word.length <= 5 * 105
word
consists only of lowercase English letters.1 <= k <= 2000
You are given an integer array nums
.
The factor score of an array is defined as the product of the LCM and GCD of all elements of that array.
\n\nReturn the maximum factor score of nums
after removing at most one element from it.
Note that both the LCM and GCD of a single number are the number itself, and the factor score of an empty array is 0.
\n\n\n
Example 1:
\n\nInput: nums = [2,4,8,16]
\n\nOutput: 64
\n\nExplanation:
\n\nOn removing 2, the GCD of the rest of the elements is 4 while the LCM is 16, which gives a maximum factor score of 4 * 16 = 64
.
Example 2:
\n\nInput: nums = [1,2,3,4,5]
\n\nOutput: 60
\n\nExplanation:
\n\nThe maximum factor score of 60 can be obtained without removing any elements.
\nExample 3:
\n\nInput: nums = [3]
\n\nOutput: 9
\n\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 30
You are given a string s
and an integer t
, representing the number of transformations to perform. In one transformation, every character in s
is replaced according to the following rules:
'z'
, replace it with the string "ab"
.'a'
is replaced with 'b'
, 'b'
is replaced with 'c'
, and so on.Return the length of the resulting string after exactly t
transformations.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: s = "abcyy", t = 2
\n\nOutput: 7
\n\nExplanation:
\n\n'a'
becomes 'b'
'b'
becomes 'c'
'c'
becomes 'd'
'y'
becomes 'z'
'y'
becomes 'z'
"bcdzz"
'b'
becomes 'c'
'c'
becomes 'd'
'd'
becomes 'e'
'z'
becomes "ab"
'z'
becomes "ab"
"cdeabab"
"cdeabab"
, which has 7 characters.Example 2:
\n\nInput: s = "azbk", t = 1
\n\nOutput: 5
\n\nExplanation:
\n\n'a'
becomes 'b'
'z'
becomes "ab"
'b'
becomes 'c'
'k'
becomes 'l'
"babcl"
"babcl"
, which has 5 characters.\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.1 <= t <= 105
You are given an integer array nums
.
Your task is to find the number of pairs of non-empty subsequences (seq1, seq2)
of nums
that satisfy the following conditions:
seq1
and seq2
are disjoint, meaning no index of nums
is common between them.seq1
is equal to the GCD of the elements of seq2
.Return the total number of such pairs.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 10
\n\nExplanation:
\n\nThe subsequence pairs which have the GCD of their elements equal to 1 are:
\n\n([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
([1, 2, 3, 4], [1, 2, 3, 4])
Example 2:
\n\nInput: nums = [10,20,30]
\n\nOutput: 2
\n\nExplanation:
\n\nThe subsequence pairs which have the GCD of their elements equal to 10 are:
\n\n([10, 20, 30], [10, 20, 30])
([10, 20, 30], [10, 20, 30])
Example 3:
\n\nInput: nums = [1,1,1,1]
\n\nOutput: 50
\n\n
Constraints:
\n\n1 <= nums.length <= 200
1 <= nums[i] <= 200
You are given a string s
consisting of lowercase English letters, an integer t
representing the number of transformations to perform, and an array nums
of size 26. In one transformation, every character in s
is replaced according to the following rules:
s[i]
with the next nums[s[i] - 'a']
consecutive characters in the alphabet. For example, if s[i] = 'a'
and nums[0] = 3
, the character 'a'
transforms into the next 3 consecutive characters ahead of it, which results in "bcd"
.'z'
. For example, if s[i] = 'y'
and nums[24] = 3
, the character 'y'
transforms into the next 3 consecutive characters ahead of it, which results in "zab"
.Return the length of the resulting string after exactly t
transformations.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: s = "abcyy", t = 2, nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2]
\n\nOutput: 7
\n\nExplanation:
\n\nFirst Transformation (t = 1):
\n\n\t'a'
becomes 'b'
as nums[0] == 1
'b'
becomes 'c'
as nums[1] == 1
'c'
becomes 'd'
as nums[2] == 1
'y'
becomes 'z'
as nums[24] == 1
'y'
becomes 'z'
as nums[24] == 1
"bcdzz"
Second Transformation (t = 2):
\n\n\t'b'
becomes 'c'
as nums[1] == 1
'c'
becomes 'd'
as nums[2] == 1
'd'
becomes 'e'
as nums[3] == 1
'z'
becomes 'ab'
as nums[25] == 2
'z'
becomes 'ab'
as nums[25] == 2
"cdeabab"
Final Length of the string: The string is "cdeabab"
, which has 7 characters.
Example 2:
\n\nInput: s = "azbk", t = 1, nums = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
\n\nOutput: 8
\n\nExplanation:
\n\nFirst Transformation (t = 1):
\n\n\t'a'
becomes 'bc'
as nums[0] == 2
'z'
becomes 'ab'
as nums[25] == 2
'b'
becomes 'cd'
as nums[1] == 2
'k'
becomes 'lm'
as nums[10] == 2
"bcabcdlm"
Final Length of the string: The string is "bcabcdlm"
, which has 8 characters.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.1 <= t <= 109
nums.length == 26
1 <= nums[i] <= 25
You are given a string num
consisting of only digits. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of digits at odd indices.
Return true
if num
is balanced, otherwise return false
.
\n
Example 1:
\n\nInput: num = "1234"
\n\nOutput: false
\n\nExplanation:
\n\n1 + 3 == 4
, and the sum of digits at odd indices is 2 + 4 == 6
.num
is not balanced.Example 2:
\n\nInput: num = "24123"
\n\nOutput: true
\n\nExplanation:
\n\n2 + 1 + 3 == 6
, and the sum of digits at odd indices is 4 + 2 == 6
.num
is balanced.\n
Constraints:
\n\n2 <= num.length <= 100
num
consists of digits onlyThere is a dungeon with n x m
rooms arranged as a grid.
You are given a 2D array moveTime
of size n x m
, where moveTime[i][j]
represents the minimum time in seconds when you can start moving to that room. You start from the room (0, 0)
at time t = 0
and can move to an adjacent room. Moving between adjacent rooms takes exactly one second.
Return the minimum time to reach the room (n - 1, m - 1)
.
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
\n\n\n
Example 1:
\n\nInput: moveTime = [[0,4],[4,4]]
\n\nOutput: 6
\n\nExplanation:
\n\nThe minimum time required is 6 seconds.
\n\nt == 4
, move from room (0, 0)
to room (1, 0)
in one second.t == 5
, move from room (1, 0)
to room (1, 1)
in one second.Example 2:
\n\nInput: moveTime = [[0,0,0],[0,0,0]]
\n\nOutput: 3
\n\nExplanation:
\n\nThe minimum time required is 3 seconds.
\n\nt == 0
, move from room (0, 0)
to room (1, 0)
in one second.t == 1
, move from room (1, 0)
to room (1, 1)
in one second.t == 2
, move from room (1, 1)
to room (1, 2)
in one second.Example 3:
\n\nInput: moveTime = [[0,1],[1,2]]
\n\nOutput: 3
\n\n
Constraints:
\n\n2 <= n == moveTime.length <= 50
2 <= m == moveTime[i].length <= 50
0 <= moveTime[i][j] <= 109
There is a dungeon with n x m
rooms arranged as a grid.
You are given a 2D array moveTime
of size n x m
, where moveTime[i][j]
represents the minimum time in seconds after which the room opens and can be moved to. You start from the room (0, 0)
at time t = 0
and can move to an adjacent room. Moving between adjacent rooms takes exactly one second.
Return the minimum time to reach the room (n - 1, m - 1)
.
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
\n\n\n
Example 1:
\n\nInput: moveTime = [[0,4],[4,4]]
\n\nOutput: 6
\n\nExplanation:
\n\nThe minimum time required is 6 seconds.
\n\nt == 4
, move from room (0, 0)
to room (1, 0)
in one second.t == 5
, move from room (1, 0)
to room (1, 1)
in one second.Example 2:
\n\nInput: moveTime = [[0,0,0],[0,0,0]]
\n\nOutput: 3
\n\nExplanation:
\n\nThe minimum time required is 3 seconds.
\n\nt == 0
, move from room (0, 0)
to room (1, 0)
in one second.t == 1
, move from room (1, 0)
to room (1, 1)
in one second.t == 2
, move from room (1, 1)
to room (1, 2)
in one second.Example 3:
\n\nInput: moveTime = [[0,1],[1,2]]
\n\nOutput: 3
\n\n
Constraints:
\n\n2 <= n == moveTime.length <= 50
2 <= m == moveTime[i].length <= 50
0 <= moveTime[i][j] <= 109
There is a dungeon with n x m
rooms arranged as a grid.
You are given a 2D array moveTime
of size n x m
, where moveTime[i][j]
represents the minimum time in seconds when you can start moving to that room. You start from the room (0, 0)
at time t = 0
and can move to an adjacent room. Moving between adjacent rooms takes one second for one move and two seconds for the next, alternating between the two.
Return the minimum time to reach the room (n - 1, m - 1)
.
Two rooms are adjacent if they share a common wall, either horizontally or vertically.
\n\n\n
Example 1:
\n\nInput: moveTime = [[0,4],[4,4]]
\n\nOutput: 7
\n\nExplanation:
\n\nThe minimum time required is 7 seconds.
\n\nt == 4
, move from room (0, 0)
to room (1, 0)
in one second.t == 5
, move from room (1, 0)
to room (1, 1)
in two seconds.Example 2:
\n\nInput: moveTime = [[0,0,0,0],[0,0,0,0]]
\n\nOutput: 6
\n\nExplanation:
\n\nThe minimum time required is 6 seconds.
\n\nt == 0
, move from room (0, 0)
to room (1, 0)
in one second.t == 1
, move from room (1, 0)
to room (1, 1)
in two seconds.t == 3
, move from room (1, 1)
to room (1, 2)
in one second.t == 4
, move from room (1, 2)
to room (1, 3)
in two seconds.Example 3:
\n\nInput: moveTime = [[0,1],[1,2]]
\n\nOutput: 4
\n\n
Constraints:
\n\n2 <= n == moveTime.length <= 750
2 <= m == moveTime[i].length <= 750
0 <= moveTime[i][j] <= 109
You are given a string num
. A string of digits is called balanced if the sum of the digits at even indices is equal to the sum of the digits at odd indices.
Return the number of distinct permutations of num
that are balanced.
Since the answer may be very large, return it modulo 109 + 7
.
A permutation is a rearrangement of all the characters of a string.
\n\n\n
Example 1:
\n\nInput: num = "123"
\n\nOutput: 2
\n\nExplanation:
\n\nnum
are "123"
, "132"
, "213"
, "231"
, "312"
and "321"
."132"
and "231"
are balanced. Thus, the answer is 2.Example 2:
\n\nInput: num = "112"
\n\nOutput: 1
\n\nExplanation:
\n\nnum
are "112"
, "121"
, and "211"
."121"
is balanced. Thus, the answer is 1.Example 3:
\n\nInput: num = "12345"
\n\nOutput: 0
\n\nExplanation:
\n\nnum
are balanced, so the answer is 0.\n
Constraints:
\n\n2 <= num.length <= 80
num
consists of digits '0'
to '9'
only.You are given two integers n
and t
. Return the smallest number greater than or equal to n
such that the product of its digits is divisible by t
.
\n
Example 1:
\n\nInput: n = 10, t = 2
\n\nOutput: 10
\n\nExplanation:
\n\nThe digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.
\nExample 2:
\n\nInput: n = 15, t = 3
\n\nOutput: 16
\n\nExplanation:
\n\nThe digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.
\n\n
Constraints:
\n\n1 <= n <= 100
1 <= t <= 10
You are given an integer array nums
and two integers k
and numOperations
.
You must perform an operation numOperations
times on nums
, where in each operation you:
i
that was not selected in any previous operations.[-k, k]
to nums[i]
.Return the maximum possible frequency of any element in nums
after performing the operations.
\n
Example 1:
\n\nInput: nums = [1,4,5], k = 1, numOperations = 2
\n\nOutput: 2
\n\nExplanation:
\n\nWe can achieve a maximum frequency of two by:
\n\nnums[1]
. nums
becomes [1, 4, 5]
.nums[2]
. nums
becomes [1, 4, 4]
.Example 2:
\n\nInput: nums = [5,11,20,20], k = 5, numOperations = 1
\n\nOutput: 2
\n\nExplanation:
\n\nWe can achieve a maximum frequency of two by:
\n\nnums[1]
.\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 105
0 <= k <= 105
0 <= numOperations <= nums.length
You are given an integer array nums
and two integers k
and numOperations
.
You must perform an operation numOperations
times on nums
, where in each operation you:
i
that was not selected in any previous operations.[-k, k]
to nums[i]
.Return the maximum possible frequency of any element in nums
after performing the operations.
\n
Example 1:
\n\nInput: nums = [1,4,5], k = 1, numOperations = 2
\n\nOutput: 2
\n\nExplanation:
\n\nWe can achieve a maximum frequency of two by:
\n\nnums[1]
, after which nums
becomes [1, 4, 5]
.nums[2]
, after which nums
becomes [1, 4, 4]
.Example 2:
\n\nInput: nums = [5,11,20,20], k = 5, numOperations = 1
\n\nOutput: 2
\n\nExplanation:
\n\nWe can achieve a maximum frequency of two by:
\n\nnums[1]
.\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= k <= 109
0 <= numOperations <= nums.length
You are given a string num
which represents a positive integer, and an integer t
.
A number is called zero-free if none of its digits are 0.
\n\nReturn a string representing the smallest zero-free number greater than or equal to num
such that the product of its digits is divisible by t
. If no such number exists, return "-1"
.
\n
Example 1:
\n\nInput: num = "1234", t = 256
\n\nOutput: "1488"
\n\nExplanation:
\n\nThe smallest zero-free number that is greater than 1234 and has the product of its digits divisible by 256 is 1488, with the product of its digits equal to 256.
\nExample 2:
\n\nInput: num = "12355", t = 50
\n\nOutput: "12355"
\n\nExplanation:
\n\n12355 is already zero-free and has the product of its digits divisible by 50, with the product of its digits equal to 150.
\nExample 3:
\n\nInput: num = "11111", t = 26
\n\nOutput: "-1"
\n\nExplanation:
\n\nNo number greater than 11111 has the product of its digits divisible by 26.
\n\n
Constraints:
\n\n2 <= num.length <= 2 * 105
num
consists only of digits in the range ['0', '9']
.num
does not contain leading zeros.1 <= t <= 1014
Given an array nums
of n
integers and an integer k
, determine whether there exist two adjacent subarrays of length k
such that both subarrays are strictly increasing. Specifically, check if there are two subarrays starting at indices a
and b
(a < b
), where:
nums[a..a + k - 1]
and nums[b..b + k - 1]
are strictly increasing.b = a + k
.Return true
if it is possible to find two such subarrays, and false
otherwise.
\n
Example 1:
\n\nInput: nums = [2,5,7,8,9,2,3,4,3,1], k = 3
\n\nOutput: true
\n\nExplanation:
\n\n2
is [7, 8, 9]
, which is strictly increasing.5
is [2, 3, 4]
, which is also strictly increasing.true
.Example 2:
\n\nInput: nums = [1,2,3,4,4,4,4,5,6,7], k = 5
\n\nOutput: false
\n\n
Constraints:
\n\n2 <= nums.length <= 100
1 < 2 * k <= nums.length
-1000 <= nums[i] <= 1000
Given an array nums
of n
integers, your task is to find the maximum value of k
for which there exist two adjacent subarrays of length k
each, such that both subarrays are strictly increasing. Specifically, check if there are two subarrays of length k
starting at indices a
and b
(a < b
), where:
nums[a..a + k - 1]
and nums[b..b + k - 1]
are strictly increasing.b = a + k
.Return the maximum possible value of k
.
A subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\nInput: nums = [2,5,7,8,9,2,3,4,3,1]
\n\nOutput: 3
\n\nExplanation:
\n\n[7, 8, 9]
, which is strictly increasing.[2, 3, 4]
, which is also strictly increasing.k
for which two such adjacent strictly increasing subarrays exist.Example 2:
\n\nInput: nums = [1,2,3,4,4,4,4,5,6,7]
\n\nOutput: 2
\n\nExplanation:
\n\n[1, 2]
, which is strictly increasing.[3, 4]
, which is also strictly increasing.k
for which two such adjacent strictly increasing subarrays exist.\n
Constraints:
\n\n2 <= nums.length <= 2 * 105
-109 <= nums[i] <= 109
You are given an integer array nums
. A good subsequence is defined as a subsequence of nums
where the absolute difference between any two consecutive elements in the subsequence is exactly 1.
Return the sum of all possible good subsequences of nums
.
Since the answer may be very large, return it modulo 109 + 7
.
Note that a subsequence of size 1 is considered good by definition.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,1]
\n\nOutput: 14
\n\nExplanation:
\n\n[1]
, [2]
, [1]
, [1,2]
, [2,1]
, [1,2,1]
.Example 2:
\n\nInput: nums = [3,4,5]
\n\nOutput: 40
\n\nExplanation:
\n\n[3]
, [4]
, [5]
, [3,4]
, [4,5]
, [3,4,5]
.\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
You are given a binary string s
representing a number n
in its binary form.
You are also given an integer k
.
An integer x
is called k-reducible if performing the following operation at most k
times reduces it to 1:
x
with the count of set bits in its binary representation.For example, the binary representation of 6 is "110"
. Applying the operation once reduces it to 2 (since "110"
has two set bits). Applying the operation again to 2 (binary "10"
) reduces it to 1 (since "10"
has one set bit).
Return an integer denoting the number of positive integers less than n
that are k-reducible.
Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: s = "111", k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nn = 7
. The 1-reducible integers less than 7 are 1, 2, and 4.
Example 2:
\n\nInput: s = "1000", k = 2
\n\nOutput: 6
\n\nExplanation:
\n\nn = 8
. The 2-reducible integers less than 8 are 1, 2, 3, 4, 5, and 6.
Example 3:
\n\nInput: s = "1", k = 3
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no positive integers less than n = 1
, so the answer is 0.
\n
Constraints:
\n\n1 <= s.length <= 800
s
has no leading zeros.s
consists only of the characters '0'
and '1'
.1 <= k <= 5
You are given an integer array nums
.
Start by selecting a starting position curr
such that nums[curr] == 0
, and choose a movement direction of either left or right.
After that, you repeat the following process:
\n\ncurr
is out of the range [0, n - 1]
, this process ends.nums[curr] == 0
, move in the current direction by incrementing curr
if you are moving right, or decrementing curr
if you are moving left.nums[curr] > 0
:\n\tnums[curr]
by 1.A selection of the initial position curr
and movement direction is considered valid if every element in nums
becomes 0 by the end of the process.
Return the number of possible valid selections.
\n\n\n
Example 1:
\n\nInput: nums = [1,0,2,0,3]
\n\nOutput: 2
\n\nExplanation:
\n\nThe only possible valid selections are the following:
\n\ncurr = 3
, and a movement direction to the left.\n\n\t[1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,1,0,3] -> [1,0,1,0,3] -> [1,0,1,0,2] -> [1,0,1,0,2] -> [1,0,0,0,2] -> [1,0,0,0,2] -> [1,0,0,0,1] -> [1,0,0,0,1] -> [1,0,0,0,1] -> [1,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,1] -> [0,0,0,0,0]
.curr = 3
, and a movement direction to the right.\n\t[1,0,2,0,3] -> [1,0,2,0,3] -> [1,0,2,0,2] -> [1,0,2,0,2] -> [1,0,1,0,2] -> [1,0,1,0,2] -> [1,0,1,0,1] -> [1,0,1,0,1] -> [1,0,0,0,1] -> [1,0,0,0,1] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [1,0,0,0,0] -> [0,0,0,0,0].
Example 2:
\n\nInput: nums = [2,3,4,0,4,1,0]
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no possible valid selections.
\n\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 100
i
where nums[i] == 0
.You are given an integer array nums
of length n
and a 2D array queries
, where queries[i] = [li, ri]
.
For each queries[i]
:
[li, ri]
in nums
.A Zero Array is an array where all elements are equal to 0.
\n\nReturn true
if it is possible to transform nums
into a Zero Array after processing all the queries sequentially, otherwise return false
.
\n
Example 1:
\n\nInput: nums = [1,0,1], queries = [[0,2]]
\n\nOutput: true
\n\nExplanation:
\n\n[0, 2]
and decrement the values at these indices by 1.[0, 0, 0]
, which is a Zero Array.Example 2:
\n\nInput: nums = [4,3,2,1], queries = [[1,3],[0,2]]
\n\nOutput: false
\n\nExplanation:
\n\n[1, 2, 3]
and decrement the values at these indices by 1.[4, 2, 1, 0]
.[0, 1, 2]
and decrement the values at these indices by 1.[3, 1, 0, 0]
, which is not a Zero Array.\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= li <= ri < nums.length
You are given an integer array nums
of length n
and a 2D array queries
where queries[i] = [li, ri, vali]
.
Each queries[i]
represents the following action on nums
:
[li, ri]
in nums
by at most vali
.A Zero Array is an array with all its elements equal to 0.
\n\nReturn the minimum possible non-negative value of k
, such that after processing the first k
queries in sequence, nums
becomes a Zero Array. If no such k
exists, return -1.
\n
Example 1:
\n\nInput: nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]
\n\nOutput: 2
\n\nExplanation:
\n\n[0, 1, 2]
by [1, 0, 1]
respectively.[1, 0, 1]
.[0, 1, 2]
by [1, 0, 1]
respectively.[0, 0, 0]
, which is a Zero Array. Therefore, the minimum value of k
is 2.Example 2:
\n\nInput: nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
\n\nOutput: -1
\n\nExplanation:
\n\n[1, 2, 3]
by [2, 2, 1]
respectively.[4, 1, 0, 0]
.[0, 1, 2]
by [1, 1, 0]
respectively.[3, 0, 0, 0]
, which is not a Zero Array.\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 5 * 105
1 <= queries.length <= 105
queries[i].length == 3
0 <= li <= ri < nums.length
1 <= vali <= 5
You are given an array of integers nums
. Some values in nums
are missing and are denoted by -1.
You can choose a pair of positive integers (x, y)
exactly once and replace each missing element with either x
or y
.
You need to minimize the maximum absolute difference between adjacent elements of nums
after replacements.
Return the minimum possible difference.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,-1,10,8]
\n\nOutput: 4
\n\nExplanation:
\n\nBy choosing the pair as (6, 7)
, nums can be changed to [1, 2, 6, 10, 8]
.
The absolute differences between adjacent elements are:
\n\n|1 - 2| == 1
|2 - 6| == 4
|6 - 10| == 4
|10 - 8| == 2
Example 2:
\n\nInput: nums = [-1,-1,-1]
\n\nOutput: 0
\n\nExplanation:
\n\nBy choosing the pair as (4, 4)
, nums can be changed to [4, 4, 4]
.
Example 3:
\n\nInput: nums = [-1,10,-1,8]
\n\nOutput: 1
\n\nExplanation:
\n\nBy choosing the pair as (11, 9)
, nums can be changed to [11, 10, 9, 8]
.
\n
Constraints:
\n\n2 <= nums.length <= 105
nums[i]
is either -1 or in the range [1, 109]
.You are given an array of integers nums
. Some values in nums
are missing and are denoted by -1.
You must choose a pair of positive integers (x, y)
exactly once and replace each missing element with either x
or y
.
You need to minimize the maximum absolute difference between adjacent elements of nums
after replacements.
Return the minimum possible difference.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,-1,10,8]
\n\nOutput: 4
\n\nExplanation:
\n\nBy choosing the pair as (6, 7)
, nums can be changed to [1, 2, 6, 10, 8]
.
The absolute differences between adjacent elements are:
\n\n|1 - 2| == 1
|2 - 6| == 4
|6 - 10| == 4
|10 - 8| == 2
Example 2:
\n\nInput: nums = [-1,-1,-1]
\n\nOutput: 0
\n\nExplanation:
\n\nBy choosing the pair as (4, 4)
, nums can be changed to [4, 4, 4]
.
Example 3:
\n\nInput: nums = [-1,10,-1,8]
\n\nOutput: 1
\n\nExplanation:
\n\nBy choosing the pair as (11, 9)
, nums can be changed to [11, 10, 9, 8]
.
\n
Constraints:
\n\n2 <= nums.length <= 105
nums[i]
is either -1 or in the range [1, 109]
.Alice and Bob are playing a game where they take turns removing stones from a pile, with Alice going first.
\n\nThe player who cannot make a move loses the game.
\n\nGiven a positive integer n
, return true
if Alice wins the game and false
otherwise.
\n
Example 1:
\n\nInput: n = 12
\n\nOutput: true
\n\nExplanation:
\n\nExample 2:
\n\nInput: n = 1
\n\nOutput: false
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= n <= 50
You are given two strings s
and t
of the same length, and two integer arrays nextCost
and previousCost
.
In one operation, you can pick any index i
of s
, and perform either one of the following actions:
s[i]
to the next letter in the alphabet. If s[i] == 'z'
, you should replace it with 'a'
. This operation costs nextCost[j]
where j
is the index of s[i]
in the alphabet.s[i]
to the previous letter in the alphabet. If s[i] == 'a'
, you should replace it with 'z'
. This operation costs previousCost[j]
where j
is the index of s[i]
in the alphabet.The shift distance is the minimum total cost of operations required to transform s
into t
.
Return the shift distance from s
to t
.
\n
Example 1:
\n\nInput: s = "abab", t = "baba", nextCost = [100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], previousCost = [1,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
\n\nOutput: 2
\n\nExplanation:
\n\ni = 0
and shift s[0]
25 times to the previous character for a total cost of 1.i = 1
and shift s[1]
25 times to the next character for a total cost of 0.i = 2
and shift s[2]
25 times to the previous character for a total cost of 1.i = 3
and shift s[3]
25 times to the next character for a total cost of 0.Example 2:
\n\nInput: s = "leet", t = "code", nextCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], previousCost = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
\n\nOutput: 31
\n\nExplanation:
\n\ni = 0
and shift s[0]
9 times to the previous character for a total cost of 9.i = 1
and shift s[1]
10 times to the next character for a total cost of 10.i = 2
and shift s[2]
1 time to the previous character for a total cost of 1.i = 3
and shift s[3]
11 times to the next character for a total cost of 11.\n
Constraints:
\n\n1 <= s.length == t.length <= 105
s
and t
consist only of lowercase English letters.nextCost.length == previousCost.length == 26
0 <= nextCost[i], previousCost[i] <= 109
You are given an integer array nums
of length n
and a 2D array queries
where queries[i] = [li, ri]
.
Each queries[i]
represents the following action on nums
:
[li, ri]
in nums
by at most 1.A Zero Array is an array with all its elements equal to 0.
\n\nReturn the maximum number of elements that can be removed from queries
, such that nums
can still be converted to a zero array using the remaining queries. If it is not possible to convert nums
to a zero array, return -1.
\n
Example 1:
\n\nInput: nums = [2,0,2], queries = [[0,2],[0,2],[1,1]]
\n\nOutput: 1
\n\nExplanation:
\n\nAfter removing queries[2]
, nums
can still be converted to a zero array.
queries[0]
, decrement nums[0]
and nums[2]
by 1 and nums[1]
by 0.queries[1]
, decrement nums[0]
and nums[2]
by 1 and nums[1]
by 0.Example 2:
\n\nInput: nums = [1,1,1,1], queries = [[1,3],[0,2],[1,3],[1,2]]
\n\nOutput: 2
\n\nExplanation:
\n\nWe can remove queries[2]
and queries[3]
.
Example 3:
\n\nInput: nums = [1,2,3,4], queries = [[0,3]]
\n\nOutput: -1
\n\nExplanation:
\n\nnums
cannot be converted to a zero array even after using all the queries.
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= li <= ri < nums.length
There is a game dungeon comprised of n x n
rooms arranged in a grid.
You are given a 2D array fruits
of size n x n
, where fruits[i][j]
represents the number of fruits in the room (i, j)
. Three children will play in the game dungeon, with initial positions at the corner rooms (0, 0)
, (0, n - 1)
, and (n - 1, 0)
.
The children will make exactly n - 1
moves according to the following rules to reach the room (n - 1, n - 1)
:
(0, 0)
must move from their current room (i, j)
to one of the rooms (i + 1, j + 1)
, (i + 1, j)
, and (i, j + 1)
if the target room exists.(0, n - 1)
must move from their current room (i, j)
to one of the rooms (i + 1, j - 1)
, (i + 1, j)
, and (i + 1, j + 1)
if the target room exists.(n - 1, 0)
must move from their current room (i, j)
to one of the rooms (i - 1, j + 1)
, (i, j + 1)
, and (i + 1, j + 1)
if the target room exists.When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.
\n\nReturn the maximum number of fruits the children can collect from the dungeon.
\n\n\n
Example 1:
\n\nInput: fruits = [[1,2,3,4],[5,6,8,7],[9,10,11,12],[13,14,15,16]]
\n\nOutput: 100
\n\nExplanation:
\n\nIn this example:
\n\n(0,0) -> (1,1) -> (2,2) -> (3, 3)
.(0,3) -> (1,2) -> (2,3) -> (3, 3)
.(3,0) -> (3,1) -> (3,2) -> (3, 3)
.In total they collect 1 + 6 + 11 + 16 + 4 + 8 + 12 + 13 + 14 + 15 = 100
fruits.
Example 2:
\n\nInput: fruits = [[1,1],[1,1]]
\n\nOutput: 4
\n\nExplanation:
\n\nIn this example:
\n\n(0,0) -> (1,1)
.(0,1) -> (1,1)
.(1,0) -> (1,1)
.In total they collect 1 + 1 + 1 + 1 = 4
fruits.
\n
Constraints:
\n\n2 <= n == fruits.length == fruits[i].length <= 1000
0 <= fruits[i][j] <= 1000
You are given an integer array nums
and two integers l
and r
. Your task is to find the minimum sum of a subarray whose size is between l
and r
(inclusive) and whose sum is greater than 0.
Return the minimum sum of such a subarray. If no such subarray exists, return -1.
\n\nA subarray is a contiguous non-empty sequence of elements within an array.
\n\n\n
Example 1:
\n\nInput: nums = [3, -2, 1, 4], l = 2, r = 3
\n\nOutput: 1
\n\nExplanation:
\n\nThe subarrays of length between l = 2
and r = 3
where the sum is greater than 0 are:
[3, -2]
with a sum of 1[1, 4]
with a sum of 5[3, -2, 1]
with a sum of 2[-2, 1, 4]
with a sum of 3Out of these, the subarray [3, -2]
has a sum of 1, which is the smallest positive sum. Hence, the answer is 1.
Example 2:
\n\nInput: nums = [-2, 2, -3, 1], l = 2, r = 3
\n\nOutput: -1
\n\nExplanation:
\n\nThere is no subarray of length between l
and r
that has a sum greater than 0. So, the answer is -1.
Example 3:
\n\nInput: nums = [1, 2, 3, 4], l = 2, r = 4
\n\nOutput: 3
\n\nExplanation:
\n\nThe subarray [1, 2]
has a length of 2 and the minimum sum greater than 0. So, the answer is 3.
\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= l <= r <= nums.length
-1000 <= nums[i] <= 1000
You are given two strings s
and t
, both of which are anagrams of each other, and an integer k
.
Your task is to determine whether it is possible to split the string s
into k
equal-sized substrings, rearrange the substrings, and concatenate them in any order to create a new string that matches the given string t
.
Return true
if this is possible, otherwise, return false
.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.
\n\nA substring is a contiguous non-empty sequence of characters within a string.
\n\n\n
Example 1:
\n\nInput: s = "abcd", t = "cdab", k = 2
\n\nOutput: true
\n\nExplanation:
\n\ns
into 2 substrings of length 2: ["ab", "cd"]
.["cd", "ab"]
, and then concatenating them results in "cdab"
, which matches t
.Example 2:
\n\nInput: s = "aabbcc", t = "bbaacc", k = 3
\n\nOutput: true
\n\nExplanation:
\n\ns
into 3 substrings of length 2: ["aa", "bb", "cc"]
.["bb", "aa", "cc"]
, and then concatenating them results in "bbaacc"
, which matches t
.Example 3:
\n\nInput: s = "aabbcc", t = "bbaacc", k = 2
\n\nOutput: false
\n\nExplanation:
\n\ns
into 2 substrings of length 3: ["aab", "bcc"]
.t = "bbaacc"
, so the output is false
.\n
Constraints:
\n\n1 <= s.length == t.length <= 2 * 105
1 <= k <= s.length
s.length
is divisible by k
.s
and t
consist only of lowercase English letters.s
and t
are anagrams of each other.You are given an integer array nums
and three integers k
, op1
, and op2
.
You can perform the following operations on nums
:
i
and divide nums[i]
by 2, rounding up to the nearest whole number. You can perform this operation at most op1
times, and not more than once per index.i
and subtract k
from nums[i]
, but only if nums[i]
is greater than or equal to k
. You can perform this operation at most op2
times, and not more than once per index.Note: Both operations can be applied to the same index, but at most once each.
\n\nReturn the minimum possible sum of all elements in nums
after performing any number of operations.
\n
Example 1:
\n\nInput: nums = [2,8,3,19,3], k = 3, op1 = 1, op2 = 1
\n\nOutput: 23
\n\nExplanation:
\n\nnums[1] = 8
, making nums[1] = 5
.nums[3] = 19
, making nums[3] = 10
.[2, 5, 3, 10, 3]
, which has the minimum possible sum of 23 after applying the operations.Example 2:
\n\nInput: nums = [2,4,3], k = 3, op1 = 2, op2 = 1
\n\nOutput: 3
\n\nExplanation:
\n\nnums[0] = 2
, making nums[0] = 1
.nums[1] = 4
, making nums[1] = 2
.nums[2] = 3
, making nums[2] = 0
.[1, 2, 0]
, which has the minimum possible sum of 3 after applying the operations.\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 105
0 <= k <= 105
0 <= op1, op2 <= nums.length
There exists an undirected tree with n
nodes numbered 0
to n - 1
. You are given a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi, wi]
indicates that there is an edge between nodes ui
and vi
with weight wi
in the tree.
Your task is to remove zero or more edges such that:
\n\nk
other nodes, where k
is given.Return the maximum possible sum of weights for the remaining edges after making the necessary removals.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1,4],[0,2,2],[2,3,12],[2,4,6]], k = 2
\n\nOutput: 22
\n\nExplanation:
\n\n[0, 2, 2]
, ensuring that no node has edges with more than k = 2
nodes.Example 2:
\n\nInput: edges = [[0,1,5],[1,2,10],[0,3,15],[3,4,20],[3,5,5],[0,6,10]], k = 3
\n\nOutput: 65
\n\nExplanation:
\n\nk = 3
nodes, we don't remove any edges.\n
Constraints:
\n\n2 <= n <= 105
1 <= k <= n - 1
edges.length == n - 1
edges[i].length == 3
0 <= edges[i][0] <= n - 1
0 <= edges[i][1] <= n - 1
1 <= edges[i][2] <= 106
edges
form a valid tree.You are given a positive number n
.
Return the smallest number x
greater than or equal to n
, such that the binary representation of x
contains only set bits
\n
Example 1:
\n\nInput: n = 5
\n\nOutput: 7
\n\nExplanation:
\n\nThe binary representation of 7 is "111"
.
Example 2:
\n\nInput: n = 10
\n\nOutput: 15
\n\nExplanation:
\n\nThe binary representation of 15 is "1111"
.
Example 3:
\n\nInput: n = 3
\n\nOutput: 3
\n\nExplanation:
\n\nThe binary representation of 3 is "11"
.
\n
Constraints:
\n\n1 <= n <= 1000
You are given an integer array nums
. This array contains n
elements, where exactly n - 2
elements are special numbers. One of the remaining two elements is the sum of these special numbers, and the other is an outlier.
An outlier is defined as a number that is neither one of the original special numbers nor the element representing the sum of those numbers.
\n\nNote that special numbers, the sum element, and the outlier must have distinct indices, but may share the same value.
\n\nReturn the largest potential outlier in nums
.
\n
Example 1:
\n\nInput: nums = [2,3,5,10]
\n\nOutput: 10
\n\nExplanation:
\n\nThe special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.
\nExample 2:
\n\nInput: nums = [-2,-1,-3,-6,4]
\n\nOutput: 4
\n\nExplanation:
\n\nThe special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.
\nExample 3:
\n\nInput: nums = [1,1,1,1,1,5,5]
\n\nOutput: 5
\n\nExplanation:
\n\nThe special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.
\n\n
Constraints:
\n\n3 <= nums.length <= 105
-1000 <= nums[i] <= 1000
nums
.There exist two undirected trees with n
and m
nodes, with distinct labels in ranges [0, n - 1]
and [0, m - 1]
, respectively.
You are given two 2D integer arrays edges1
and edges2
of lengths n - 1
and m - 1
, respectively, where edges1[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the first tree and edges2[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the second tree. You are also given an integer k
.
Node u
is target to node v
if the number of edges on the path from u
to v
is less than or equal to k
. Note that a node is always target to itself.
Return an array of n
integers answer
, where answer[i]
is the maximum possible number of nodes target to node i
of the first tree if you have to connect one node from the first tree to another node in the second tree.
Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.
\n\n\n
Example 1:
\n\nInput: edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]], k = 2
\n\nOutput: [9,7,9,8,8]
\n\nExplanation:
\n\ni = 0
, connect node 0 from the first tree to node 0 from the second tree.i = 1
, connect node 1 from the first tree to node 0 from the second tree.i = 2
, connect node 2 from the first tree to node 4 from the second tree.i = 3
, connect node 3 from the first tree to node 4 from the second tree.i = 4
, connect node 4 from the first tree to node 4 from the second tree.Example 2:
\n\nInput: edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]], k = 1
\n\nOutput: [6,3,3,3,3]
\n\nExplanation:
\n\nFor every i
, connect node i
of the first tree with any node of the second tree.
\n
Constraints:
\n\n2 <= n, m <= 1000
edges1.length == n - 1
edges2.length == m - 1
edges1[i].length == edges2[i].length == 2
edges1[i] = [ai, bi]
0 <= ai, bi < n
edges2[i] = [ui, vi]
0 <= ui, vi < m
edges1
and edges2
represent valid trees.0 <= k <= 1000
There exist two undirected trees with n
and m
nodes, labeled from [0, n - 1]
and [0, m - 1]
, respectively.
You are given two 2D integer arrays edges1
and edges2
of lengths n - 1
and m - 1
, respectively, where edges1[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
in the first tree and edges2[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
in the second tree.
Node u
is target to node v
if the number of edges on the path from u
to v
is even. Note that a node is always target to itself.
Return an array of n
integers answer
, where answer[i]
is the maximum possible number of nodes that are target to node i
of the first tree if you had to connect one node from the first tree to another node in the second tree.
Note that queries are independent from each other. That is, for every query you will remove the added edge before proceeding to the next query.
\n\n\n
Example 1:
\n\nInput: edges1 = [[0,1],[0,2],[2,3],[2,4]], edges2 = [[0,1],[0,2],[0,3],[2,7],[1,4],[4,5],[4,6]]
\n\nOutput: [8,7,7,8,8]
\n\nExplanation:
\n\ni = 0
, connect node 0 from the first tree to node 0 from the second tree.i = 1
, connect node 1 from the first tree to node 4 from the second tree.i = 2
, connect node 2 from the first tree to node 7 from the second tree.i = 3
, connect node 3 from the first tree to node 0 from the second tree.i = 4
, connect node 4 from the first tree to node 4 from the second tree.Example 2:
\n\nInput: edges1 = [[0,1],[0,2],[0,3],[0,4]], edges2 = [[0,1],[1,2],[2,3]]
\n\nOutput: [3,6,6,6,6]
\n\nExplanation:
\n\nFor every i
, connect node i
of the first tree with any node of the second tree.
\n
Constraints:
\n\n2 <= n, m <= 105
edges1.length == n - 1
edges2.length == m - 1
edges1[i].length == edges2[i].length == 2
edges1[i] = [ai, bi]
0 <= ai, bi < n
edges2[i] = [ui, vi]
0 <= ui, vi < m
edges1
and edges2
represent valid trees.Table: user_content
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| content_id | int |\n| content_text| varchar |\n+-------------+---------+\ncontent_id is the unique key for this table.\nEach row contains a unique ID and the corresponding text content.\n\n\n
Write a solution to transform the text in the content_text
column by applying the following rules:
-
, both parts should be capitalized (e.g., top-rated → Top-Rated)Return the result table that includes both the original content_text
and the modified text following the above rules.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nuser_content table:
\n\n\n+------------+---------------------------------+\n| content_id | content_text |\n+------------+---------------------------------+\n| 1 | hello world of SQL |\n| 2 | the QUICK-brown fox |\n| 3 | modern-day DATA science |\n| 4 | web-based FRONT-end development |\n+------------+---------------------------------+\n\n\n
Output:
\n\n\n+------------+---------------------------------+---------------------------------+\n| content_id | original_text | converted_text |\n+------------+---------------------------------+---------------------------------+\n| 1 | hello world of SQL | Hello World Of Sql |\n| 2 | the QUICK-brown fox | The Quick-Brown Fox |\n| 3 | modern-day DATA science | Modern-Day Data Science |\n| 4 | web-based FRONT-end development | Web-Based Front-End Development |\n+------------+---------------------------------+---------------------------------+\n\n\n
Explanation:
\n\nYou are given an integer array nums
and an integer k
.
An integer h
is called valid if all values in the array that are strictly greater than h
are identical.
For example, if nums = [10, 8, 10, 8]
, a valid integer is h = 9
because all nums[i] > 9
are equal to 10, but 5 is not a valid integer.
You are allowed to perform the following operation on nums
:
h
that is valid for the current values in nums
.i
where nums[i] > h
, set nums[i]
to h
.Return the minimum number of operations required to make every element in nums
equal to k
. If it is impossible to make all elements equal to k
, return -1.
\n
Example 1:
\n\nInput: nums = [5,2,5,4,5], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nThe operations can be performed in order using valid integers 4 and then 2.
\nExample 2:
\n\nInput: nums = [2,1,2], k = 2
\n\nOutput: -1
\n\nExplanation:
\n\nIt is impossible to make all the values equal to 2.
\nExample 3:
\n\nInput: nums = [9,7,5,3], k = 1
\n\nOutput: 4
\n\nExplanation:
\n\nThe operations can be performed using valid integers in the order 7, 5, 3, and 1.
\n\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 100
Bob is stuck in a dungeon and must break n
locks, each requiring some amount of energy to break. The required energy for each lock is stored in an array called strength
where strength[i]
indicates the energy needed to break the ith
lock.
To break a lock, Bob uses a sword with the following characteristics:
\n\nx
by which the energy of the sword increases is 1.x
.ith
lock, the energy of the sword must reach at least strength[i]
.x
increases by a given value k
.Your task is to determine the minimum time in minutes required for Bob to break all n
locks and escape the dungeon.
Return the minimum time required for Bob to break all n
locks.
\n
Example 1:
\n\nInput: strength = [3,4,1], k = 1
\n\nOutput: 4
\n\nExplanation:
\n\nTime | \n\t\t\tEnergy | \n\t\t\tx | \n\t\t\tAction | \n\t\t\tUpdated x | \n\t\t
---|---|---|---|---|
0 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t\tNothing | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\tBreak 3rd Lock | \n\t\t\t2 | \n\t\t
2 | \n\t\t\t2 | \n\t\t\t2 | \n\t\t\tNothing | \n\t\t\t2 | \n\t\t
3 | \n\t\t\t4 | \n\t\t\t2 | \n\t\t\tBreak 2nd Lock | \n\t\t\t3 | \n\t\t
4 | \n\t\t\t3 | \n\t\t\t3 | \n\t\t\tBreak 1st Lock | \n\t\t\t3 | \n\t\t
The locks cannot be broken in less than 4 minutes; thus, the answer is 4.
\nExample 2:
\n\nInput: strength = [2,5,4], k = 2
\n\nOutput: 5
\n\nExplanation:
\n\nTime | \n\t\t\tEnergy | \n\t\t\tx | \n\t\t\tAction | \n\t\t\tUpdated x | \n\t\t
---|---|---|---|---|
0 | \n\t\t\t0 | \n\t\t\t1 | \n\t\t\tNothing | \n\t\t\t1 | \n\t\t
1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\tNothing | \n\t\t\t1 | \n\t\t
2 | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\tBreak 1st Lock | \n\t\t\t3 | \n\t\t
3 | \n\t\t\t3 | \n\t\t\t3 | \n\t\t\tNothing | \n\t\t\t3 | \n\t\t
4 | \n\t\t\t6 | \n\t\t\t3 | \n\t\t\tBreak 2nd Lock | \n\t\t\t5 | \n\t\t
5 | \n\t\t\t5 | \n\t\t\t5 | \n\t\t\tBreak 3rd Lock | \n\t\t\t7 | \n\t\t
The locks cannot be broken in less than 5 minutes; thus, the answer is 5.
\n\n
Constraints:
\n\nn == strength.length
1 <= n <= 8
1 <= K <= 10
1 <= strength[i] <= 106
You are given two integers n
and m
that consist of the same number of digits.
You can perform the following operations any number of times:
\n\nn
that is not 9 and increase it by 1.n
that is not 0 and decrease it by 1.The integer n
must not be a prime number at any point, including its original value and after each operation.
The cost of a transformation is the sum of all values that n
takes throughout the operations performed.
Return the minimum cost to transform n
into m
. If it is impossible, return -1.
\n
Example 1:
\n\nInput: n = 10, m = 12
\n\nOutput: 85
\n\nExplanation:
\n\nWe perform the following operations:
\n\nn = 20
.n = 21
.n = 22
.n = 12
.Example 2:
\n\nInput: n = 4, m = 8
\n\nOutput: -1
\n\nExplanation:
\n\nIt is impossible to make n
equal to m
.
Example 3:
\n\nInput: n = 6, m = 2
\n\nOutput: -1
\n\nExplanation:
\n\nSince 2 is already a prime, we can't make n
equal to m
.
\n
Constraints:
\n\n1 <= n, m < 104
n
and m
consist of the same number of digits.You are given an array of integers nums
of size n
and a positive integer threshold
.
There is a graph consisting of n
nodes with the ith
node having a value of nums[i]
. Two nodes i
and j
in the graph are connected via an undirected edge if lcm(nums[i], nums[j]) <= threshold
.
Return the number of connected components in this graph.
\n\nA connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph.
\n\nThe term lcm(a, b)
denotes the least common multiple of a
and b
.
\n
Example 1:
\n\nInput: nums = [2,4,8,3,9], threshold = 5
\n\nOutput: 4
\n\nExplanation:
\n\n\n\n
The four connected components are (2, 4)
, (3)
, (8)
, (9)
.
Example 2:
\n\nInput: nums = [2,4,8,3,9,12], threshold = 10
\n\nOutput: 2
\n\nExplanation:
\n\nThe two connected components are (2, 3, 4, 8, 9)
, and (12)
.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
nums
are unique.1 <= threshold <= 2 * 105
You are given an integer array nums
that represents a circular array. Your task is to create a new array result
of the same size, following these rules:
i
(where 0 <= i < nums.length
), perform the following independent actions:\n\nnums[i] > 0
: Start at index i
and move nums[i]
steps to the right in the circular array. Set result[i]
to the value of the index where you land.nums[i] < 0
: Start at index i
and move abs(nums[i])
steps to the left in the circular array. Set result[i]
to the value of the index where you land.nums[i] == 0
: Set result[i]
to nums[i]
.Return the new array result
.
Note: Since nums
is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.
\n
Example 1:
\n\nInput: nums = [3,-2,1,1]
\n\nOutput: [1,1,1,3]
\n\nExplanation:
\n\nnums[0]
that is equal to 3, If we move 3 steps to right, we reach nums[3]
. So result[0]
should be 1.nums[1]
that is equal to -2, If we move 2 steps to left, we reach nums[3]
. So result[1]
should be 1.nums[2]
that is equal to 1, If we move 1 step to right, we reach nums[3]
. So result[2]
should be 1.nums[3]
that is equal to 1, If we move 1 step to right, we reach nums[0]
. So result[3]
should be 3.Example 2:
\n\nInput: nums = [-1,4,-1]
\n\nOutput: [-1,-1,4]
\n\nExplanation:
\n\nnums[0]
that is equal to -1, If we move 1 step to left, we reach nums[2]
. So result[0]
should be -1.nums[1]
that is equal to 4, If we move 4 steps to right, we reach nums[2]
. So result[1]
should be -1.nums[2]
that is equal to -1, If we move 1 step to left, we reach nums[1]
. So result[2]
should be 4.\n
Constraints:
\n\n1 <= nums.length <= 100
-100 <= nums[i] <= 100
You are given an array points
where points[i] = [xi, yi]
represents the coordinates of a point on an infinite plane.
Your task is to find the maximum area of a rectangle that:
\n\nReturn the maximum area that you can obtain or -1 if no such rectangle is possible.
\n\n\n
Example 1:
\n\nInput: points = [[1,1],[1,3],[3,1],[3,3]]
\n\nOutput: 4
\n\nExplanation:
\n\nWe can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border. Hence, the maximum possible area would be 4.
\nExample 2:
\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
\n\nOutput: -1
\n\nExplanation:
\n\nThere is only one rectangle possible is with points [1,1], [1,3], [3,1]
and [3,3]
but [2,2]
will always lie inside it. Hence, returning -1.
Example 3:
\n\nInput: points = [[1,1],[1,3],[3,1],[3,3],[1,2],[3,2]]
\n\nOutput: 2
\n\nExplanation:
\n\nThe maximum area rectangle is formed by the points [1,3], [1,2], [3,2], [3,3]
, which has an area of 2. Additionally, the points [1,1], [1,2], [3,1], [3,2]
also form a valid rectangle with the same area.
\n
Constraints:
\n\n1 <= points.length <= 10
points[i].length == 2
0 <= xi, yi <= 100
You are given an array of integers nums
and an integer k
.
Return the maximum sum of a subarray of nums
, such that the size of the subarray is divisible by k
.
\n
Example 1:
\n\nInput: nums = [1,2], k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nThe subarray [1, 2]
with sum 3 has length equal to 2 which is divisible by 1.
Example 2:
\n\nInput: nums = [-1,-2,-3,-4,-5], k = 4
\n\nOutput: -10
\n\nExplanation:
\n\nThe maximum sum subarray is [-1, -2, -3, -4]
which has length equal to 4 which is divisible by 4.
Example 3:
\n\nInput: nums = [-5,1,2,-3,4], k = 2
\n\nOutput: 4
\n\nExplanation:
\n\nThe maximum sum subarray is [1, 2, -3, 4]
which has length equal to 4 which is divisible by 2.
\n
Constraints:
\n\n1 <= k <= nums.length <= 2 * 105
-109 <= nums[i] <= 109
There are n points on an infinite plane. You are given two integer arrays xCoord
and yCoord
where (xCoord[i], yCoord[i])
represents the coordinates of the ith
point.
Your task is to find the maximum area of a rectangle that:
\n\nReturn the maximum area that you can obtain or -1 if no such rectangle is possible.
\n\n\n
Example 1:
\n\nInput: xCoord = [1,1,3,3], yCoord = [1,3,1,3]
\n\nOutput: 4
\n\nExplanation:
\n\nWe can make a rectangle with these 4 points as corners and there is no other point that lies inside or on the border. Hence, the maximum possible area would be 4.
\nExample 2:
\n\nInput: xCoord = [1,1,3,3,2], yCoord = [1,3,1,3,2]
\n\nOutput: -1
\n\nExplanation:
\n\nThere is only one rectangle possible is with points [1,1], [1,3], [3,1]
and [3,3]
but [2,2]
will always lie inside it. Hence, returning -1.
Example 3:
\n\nInput: xCoord = [1,1,3,3,1,3], yCoord = [1,3,1,3,2,2]
\n\nOutput: 2
\n\nExplanation:
\n\nThe maximum area rectangle is formed by the points [1,3], [1,2], [3,2], [3,3]
, which has an area of 2. Additionally, the points [1,1], [1,2], [3,1], [3,2]
also form a valid rectangle with the same area.
\n
Constraints:
\n\n1 <= xCoord.length == yCoord.length <= 2 * 105
0 <= xCoord[i], yCoord[i] <= 8 * 107
You are given a 2D array events
which represents a sequence of events where a child pushes a series of buttons on a keyboard.
Each events[i] = [indexi, timei]
indicates that the button at index indexi
was pressed at time timei
.
time
.Return the index
of the button that took the longest time to push. If multiple buttons have the same longest time, return the button with the smallest index
.
\n
Example 1:
\n\nInput: events = [[1,2],[2,5],[3,9],[1,15]]
\n\nOutput: 1
\n\nExplanation:
\n\n5 - 2 = 3
units of time.9 - 5 = 4
units of time.15 - 9 = 6
units of time.Example 2:
\n\nInput: events = [[10,5],[1,7]]
\n\nOutput: 10
\n\nExplanation:
\n\n7 - 5 = 2
units of time.\n
Constraints:
\n\n1 <= events.length <= 1000
events[i] == [indexi, timei]
1 <= indexi, timei <= 105
events
is sorted in increasing order of timei
.You are given a string initialCurrency
, and you start with 1.0
of initialCurrency
.
You are also given four arrays with currency pairs (strings) and rates (real numbers):
\n\npairs1[i] = [startCurrencyi, targetCurrencyi]
denotes that you can convert from startCurrencyi
to targetCurrencyi
at a rate of rates1[i]
on day 1.pairs2[i] = [startCurrencyi, targetCurrencyi]
denotes that you can convert from startCurrencyi
to targetCurrencyi
at a rate of rates2[i]
on day 2.targetCurrency
can be converted back to its corresponding startCurrency
at a rate of 1 / rate
.You can perform any number of conversions, including zero, using rates1
on day 1, followed by any number of additional conversions, including zero, using rates2
on day 2.
Return the maximum amount of initialCurrency
you can have after performing any number of conversions on both days in order.
Note: Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other.
\n\n\n
Example 1:
\n\nInput: initialCurrency = "EUR", pairs1 = [["EUR","USD"],["USD","JPY"]], rates1 = [2.0,3.0], pairs2 = [["JPY","USD"],["USD","CHF"],["CHF","EUR"]], rates2 = [4.0,5.0,6.0]
\n\nOutput: 720.00000
\n\nExplanation:
\n\nTo get the maximum amount of EUR, starting with 1.0 EUR:
\n\nExample 2:
\n\nInput: initialCurrency = "NGN", pairs1 = [["NGN","EUR"]], rates1 = [9.0], pairs2 = [["NGN","EUR"]], rates2 = [6.0]
\n\nOutput: 1.50000
\n\nExplanation:
\n\nConverting NGN to EUR on day 1 and EUR to NGN using the inverse rate on day 2 gives the maximum amount.
\nExample 3:
\n\nInput: initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0]
\n\nOutput: 1.00000
\n\nExplanation:
\n\nIn this example, there is no need to make any conversions on either day.
\n\n
Constraints:
\n\n1 <= initialCurrency.length <= 3
initialCurrency
consists only of uppercase English letters.1 <= n == pairs1.length <= 10
1 <= m == pairs2.length <= 10
pairs1[i] == [startCurrencyi, targetCurrencyi]
pairs2[i] == [startCurrencyi, targetCurrencyi]
1 <= startCurrencyi.length, targetCurrencyi.length <= 3
startCurrencyi
and targetCurrencyi
consist only of uppercase English letters.rates1.length == n
rates2.length == m
1.0 <= rates1[i], rates2[i] <= 10.0
5 * 1010
.You are given an array nums
.
A split of an array nums
is beautiful if:
nums
is split into three subarrays: nums1
, nums2
, and nums3
, such that nums
can be formed by concatenating nums1
, nums2
, and nums3
in that order.nums1
is a prefix of nums2
OR nums2
is a prefix of nums3
.Return the number of ways you can make this split.
\n\n\n
Example 1:
\n\nInput: nums = [1,1,2,1]
\n\nOutput: 2
\n\nExplanation:
\n\nThe beautiful splits are:
\n\nnums1 = [1]
, nums2 = [1,2]
, nums3 = [1]
.nums1 = [1]
, nums2 = [1]
, nums3 = [2,1]
.Example 2:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 0
\n\nExplanation:
\n\nThere are 0 beautiful splits.
\n\n
Constraints:
\n\n1 <= nums.length <= 5000
0 <= nums[i] <= 50
You are given a string s
.
A string t
is called good if all characters of t
occur the same number of times.
You can perform the following operations any number of times:
\n\ns
.s
.s
to its next letter in the alphabet.Note that you cannot change 'z'
to 'a'
using the third operation.
Return the minimum number of operations required to make s
good.
\n
Example 1:
\n\nInput: s = "acab"
\n\nOutput: 1
\n\nExplanation:
\n\nWe can make s
good by deleting one occurrence of character 'a'
.
Example 2:
\n\nInput: s = "wddw"
\n\nOutput: 0
\n\nExplanation:
\n\nWe do not need to perform any operations since s
is initially good.
Example 3:
\n\nInput: s = "aaabc"
\n\nOutput: 2
\n\nExplanation:
\n\nWe can make s
good by applying these operations:
'a'
to 'b'
'c'
into s
\n
Constraints:
\n\n3 <= s.length <= 2 * 104
s
contains only lowercase English letters.Given an integer array nums
, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number.
\n
Example 1:
\n\nInput: nums = [1,2,1,4,1]
\n\nOutput: 1
\n\nExplanation:
\n\nOnly the subarray [1,4,1]
contains exactly 3 elements where the sum of the first and third numbers equals half the middle number.
Example 2:
\n\nInput: nums = [1,1,1]
\n\nOutput: 0
\n\nExplanation:
\n\n[1,1,1]
is the only subarray of length 3. However, its first and third numbers do not add to half the middle number.
\n
Constraints:
\n\n3 <= nums.length <= 100
-100 <= nums[i] <= 100
You are given a 2D integer array grid
with size m x n
. You are also given an integer k
.
Your task is to calculate the number of paths you can take from the top-left cell (0, 0)
to the bottom-right cell (m - 1, n - 1)
satisfying the following constraints:
(i, j)
you may move to the cell (i, j + 1)
or to the cell (i + 1, j)
if the target cell exists.XOR
of all the numbers on the path must be equal to k
.Return the total number of such paths.
\n\nSince the answer can be very large, return the result modulo 109 + 7
.
\n
Example 1:
\n\nInput: grid = [[2, 1, 5], [7, 10, 0], [12, 6, 4]], k = 11
\n\nOutput: 3
\n\nExplanation:
\n\nThe 3 paths are:
\n\n(0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2)
(0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)
(0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)
Example 2:
\n\nInput: grid = [[1, 3, 3, 3], [0, 3, 3, 2], [3, 0, 1, 1]], k = 2
\n\nOutput: 5
\n\nExplanation:
\n\nThe 5 paths are:
\n\n(0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2) → (2, 3)
(0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → (2, 3)
(0, 0) → (1, 0) → (1, 1) → (1, 2) → (1, 3) → (2, 3)
(0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2) → (2, 3)
(0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (2, 3)
Example 3:
\n\nInput: grid = [[1, 1, 1, 2], [3, 0, 3, 2], [3, 0, 2, 2]], k = 10
\n\nOutput: 0
\n\n
Constraints:
\n\n1 <= m == grid.length <= 300
1 <= n == grid[r].length <= 300
0 <= grid[r][c] < 16
0 <= k < 16
You are given an integer n
representing the dimensions of an n x n
grid, with the origin at the bottom-left corner of the grid. You are also given a 2D array of coordinates rectangles
, where rectangles[i]
is in the form [startx, starty, endx, endy]
, representing a rectangle on the grid. Each rectangle is defined as follows:
(startx, starty)
: The bottom-left corner of the rectangle.(endx, endy)
: The top-right corner of the rectangle.Note that the rectangles do not overlap. Your task is to determine if it is possible to make either two horizontal or two vertical cuts on the grid such that:
\n\nReturn true
if such cuts can be made; otherwise, return false
.
\n
Example 1:
\n\nInput: n = 5, rectangles = [[1,0,5,2],[0,2,2,4],[3,2,5,3],[0,4,4,5]]
\n\nOutput: true
\n\nExplanation:
\n\nThe grid is shown in the diagram. We can make horizontal cuts at y = 2
and y = 4
. Hence, output is true.
Example 2:
\n\nInput: n = 4, rectangles = [[0,0,1,1],[2,0,3,4],[0,2,2,3],[3,0,4,3]]
\n\nOutput: true
\n\nExplanation:
\n\nWe can make vertical cuts at x = 2
and x = 3
. Hence, output is true.
Example 3:
\n\nInput: n = 4, rectangles = [[0,2,2,4],[1,0,3,2],[2,2,3,4],[3,0,4,2],[3,2,4,4]]
\n\nOutput: false
\n\nExplanation:
\n\nWe cannot make two horizontal or two vertical cuts that satisfy the conditions. Hence, output is false.
\n\n
Constraints:
\n\n3 <= n <= 109
3 <= rectangles.length <= 105
0 <= rectangles[i][0] < rectangles[i][2] <= n
0 <= rectangles[i][1] < rectangles[i][3] <= n
Given an integer array nums
, find the number of subsequences of size 5 of nums
with a unique middle mode.
Since the answer may be very large, return it modulo 109 + 7
.
A mode of a sequence of numbers is defined as the element that appears the maximum number of times in the sequence.
\n\nA sequence of numbers contains a unique mode if it has only one mode.
\n\nA sequence of numbers seq
of size 5 contains a unique middle mode if the middle element (seq[2]
) is a unique mode.
\n
Example 1:
\n\nInput: nums = [1,1,1,1,1,1]
\n\nOutput: 6
\n\nExplanation:
\n\n[1, 1, 1, 1, 1]
is the only subsequence of size 5 that can be formed, and it has a unique middle mode of 1. This subsequence can be formed in 6 different ways, so the output is 6.
Example 2:
\n\nInput: nums = [1,2,2,3,3,4]
\n\nOutput: 4
\n\nExplanation:
\n\n[1, 2, 2, 3, 4]
and [1, 2, 3, 3, 4]
each have a unique middle mode because the number at index 2 has the greatest frequency in the subsequence. [1, 2, 2, 3, 3]
does not have a unique middle mode because 2 and 3 appear twice.
Example 3:
\n\nInput: nums = [0,1,2,3,4,5,6,7,8]
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no subsequence of length 5 with a unique middle mode.
\n\n
Constraints:
\n\n5 <= nums.length <= 1000
-109 <= nums[i] <= 109
You are given an integer array nums
. You need to ensure that the elements in the array are distinct. To achieve this, you can perform the following operation any number of times:
Note that an empty array is considered to have distinct elements. Return the minimum number of operations needed to make the elements in the array distinct.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,4,2,3,3,5,7]
\n\nOutput: 2
\n\nExplanation:
\n\n[4, 2, 3, 3, 5, 7]
.[3, 5, 7]
, which has distinct elements.Therefore, the answer is 2.
\nExample 2:
\n\nInput: nums = [4,5,6,4,4]
\n\nOutput: 2
\n\nExplanation:
\n\n[4, 4]
.Therefore, the answer is 2.
\nExample 3:
\n\nInput: nums = [6,7,8,9]
\n\nOutput: 0
\n\nExplanation:
\n\nThe array already contains distinct elements. Therefore, the answer is 0.
\n\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 100
You are given an integer array nums
and an integer k
.
You are allowed to perform the following operation on each element of the array at most once:
\n\n[-k, k]
to the element.Return the maximum possible number of distinct elements in nums
after performing the operations.
\n
Example 1:
\n\nInput: nums = [1,2,2,3,3,4], k = 2
\n\nOutput: 6
\n\nExplanation:
\n\nnums
changes to [-1, 0, 1, 2, 3, 4]
after performing operations on the first four elements.
Example 2:
\n\nInput: nums = [4,4,4,4], k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nBy adding -1 to nums[0]
and 1 to nums[1]
, nums
changes to [3, 5, 4, 4]
.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
0 <= k <= 109
You are given a binary string s
of length n
and an integer numOps
.
You are allowed to perform the following operation on s
at most numOps
times:
i
(where 0 <= i < n
) and flip s[i]
. If s[i] == '1'
, change s[i]
to '0'
and vice versa.You need to minimize the length of the longest substring of s
such that all the characters in the substring are identical.
Return the minimum length after the operations.
\n\n\n
Example 1:
\n\nInput: s = "000001", numOps = 1
\n\nOutput: 2
\n\nExplanation:
\n\nBy changing s[2]
to '1'
, s
becomes "001001"
. The longest substrings with identical characters are s[0..1]
and s[3..4]
.
Example 2:
\n\nInput: s = "0000", numOps = 2
\n\nOutput: 1
\n\nExplanation:
\n\nBy changing s[0]
and s[2]
to '1'
, s
becomes "1010"
.
Example 3:
\n\nInput: s = "0101", numOps = 0
\n\nOutput: 1
\n\n
Constraints:
\n\n1 <= n == s.length <= 1000
s
consists only of '0'
and '1'
.0 <= numOps <= n
You are given a binary string s
of length n
and an integer numOps
.
You are allowed to perform the following operation on s
at most numOps
times:
i
(where 0 <= i < n
) and flip s[i]
. If s[i] == '1'
, change s[i]
to '0'
and vice versa.You need to minimize the length of the longest substring of s
such that all the characters in the substring are identical.
Return the minimum length after the operations.
\n\n\n
Example 1:
\n\nInput: s = "000001", numOps = 1
\n\nOutput: 2
\n\nExplanation:
\n\nBy changing s[2]
to '1'
, s
becomes "001001"
. The longest substrings with identical characters are s[0..1]
and s[3..4]
.
Example 2:
\n\nInput: s = "0000", numOps = 2
\n\nOutput: 1
\n\nExplanation:
\n\nBy changing s[0]
and s[2]
to '1'
, s
becomes "1010"
.
Example 3:
\n\nInput: s = "0101", numOps = 0
\n\nOutput: 1
\n\n
Constraints:
\n\n1 <= n == s.length <= 105
s
consists only of '0'
and '1'
.0 <= numOps <= n
You are given a m x n
matrix grid
consisting of non-negative integers.
In one operation, you can increment the value of any grid[i][j]
by 1.
Return the minimum number of operations needed to make all columns of grid
strictly increasing.
\n
Example 1:
\n\nInput: grid = [[3,2],[1,3],[3,4],[0,1]]
\n\nOutput: 15
\n\nExplanation:
\n\n0th
column strictly increasing, we can apply 3 operations on grid[1][0]
, 2 operations on grid[2][0]
, and 6 operations on grid[3][0]
.1st
column strictly increasing, we can apply 4 operations on grid[3][1]
.Example 2:
\n\nInput: grid = [[3,2,1],[2,1,0],[1,2,3]]
\n\nOutput: 12
\n\nExplanation:
\n\n0th
column strictly increasing, we can apply 2 operations on grid[1][0]
, and 4 operations on grid[2][0]
.1st
column strictly increasing, we can apply 2 operations on grid[1][1]
, and 2 operations on grid[2][1]
.2nd
column strictly increasing, we can apply 2 operations on grid[1][2]
.\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 50
0 <= grid[i][j] < 2500
\n
\n\n\n
You are given a string word
, and an integer numFriends
.
Alice is organizing a game for her numFriends
friends. There are multiple rounds in the game, where in each round:
word
is split into numFriends
non-empty strings, such that no previous round has had the exact same split.Find the lexicographically largest string from the box after all the rounds are finished.
\n\n\n
Example 1:
\n\nInput: word = "dbca", numFriends = 2
\n\nOutput: "dbc"
\n\nExplanation:
\n\nAll possible splits are:
\n\n"d"
and "bca"
."db"
and "ca"
."dbc"
and "a"
.Example 2:
\n\nInput: word = "gggg", numFriends = 4
\n\nOutput: "g"
\n\nExplanation:
\n\nThe only possible split is: "g"
, "g"
, "g"
, and "g"
.
\n
Constraints:
\n\n1 <= word.length <= 5 * 103
word
consists only of lowercase English letters.1 <= numFriends <= word.length
You are given an array nums
consisting of positive integers.
A special subsequence is defined as a subsequence of length 4, represented by indices (p, q, r, s)
, where p < q < r < s
. This subsequence must satisfy the following conditions:
nums[p] * nums[r] == nums[q] * nums[s]
q - p > 1
, r - q > 1
and s - r > 1
.Return the number of different special subsequences in nums
.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,3,6,1]
\n\nOutput: 1
\n\nExplanation:
\n\nThere is one special subsequence in nums
.
(p, q, r, s) = (0, 2, 4, 6)
:\n\n\t(1, 3, 3, 1)
.nums[p] * nums[r] = nums[0] * nums[4] = 1 * 3 = 3
nums[q] * nums[s] = nums[2] * nums[6] = 3 * 1 = 3
Example 2:
\n\nInput: nums = [3,4,3,4,3,4,3,4]
\n\nOutput: 3
\n\nExplanation:
\n\nThere are three special subsequences in nums
.
(p, q, r, s) = (0, 2, 4, 6)
:\n\n\t(3, 3, 3, 3)
.nums[p] * nums[r] = nums[0] * nums[4] = 3 * 3 = 9
nums[q] * nums[s] = nums[2] * nums[6] = 3 * 3 = 9
(p, q, r, s) = (1, 3, 5, 7)
:\n\t(4, 4, 4, 4)
.nums[p] * nums[r] = nums[1] * nums[5] = 4 * 4 = 16
nums[q] * nums[s] = nums[3] * nums[7] = 4 * 4 = 16
(p, q, r, s) = (0, 2, 5, 7)
:\n\t(3, 3, 4, 4)
.nums[p] * nums[r] = nums[0] * nums[5] = 3 * 4 = 12
nums[q] * nums[s] = nums[2] * nums[7] = 3 * 4 = 12
\n
Constraints:
\n\n7 <= nums.length <= 1000
1 <= nums[i] <= 1000
You are given three integers n
, m
, k
. A good array arr
of size n
is defined as follows:
arr
is in the inclusive range [1, m]
.k
indices i
(where 1 <= i < n
) satisfy the condition arr[i - 1] == arr[i]
.Return the number of good arrays that can be formed.
\n\nSince the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: n = 3, m = 2, k = 1
\n\nOutput: 4
\n\nExplanation:
\n\n[1, 1, 2]
, [1, 2, 2]
, [2, 1, 1]
and [2, 2, 1]
.Example 2:
\n\nInput: n = 4, m = 2, k = 2
\n\nOutput: 6
\n\nExplanation:
\n\n[1, 1, 1, 2]
, [1, 1, 2, 2]
, [1, 2, 2, 2]
, [2, 1, 1, 1]
, [2, 2, 1, 1]
and [2, 2, 2, 1]
.Example 3:
\n\nInput: n = 5, m = 2, k = 0
\n\nOutput: 2
\n\nExplanation:
\n\n[1, 2, 1, 2, 1]
and [2, 1, 2, 1, 2]
. Hence, the answer is 2.\n
Constraints:
\n\n1 <= n <= 105
1 <= m <= 105
0 <= k <= n - 1
You are given a string s
and a pattern string p
, where p
contains exactly one '*'
character.
The '*'
in p
can be replaced with any sequence of zero or more characters.
Return true
if p
can be made a substring of s
, and false
otherwise.
\n
Example 1:
\n\nInput: s = "leetcode", p = "ee*e"
\n\nOutput: true
\n\nExplanation:
\n\nBy replacing the '*'
with "tcod"
, the substring "eetcode"
matches the pattern.
Example 2:
\n\nInput: s = "car", p = "c*v"
\n\nOutput: false
\n\nExplanation:
\n\nThere is no substring matching the pattern.
\nExample 3:
\n\nInput: s = "luck", p = "u*"
\n\nOutput: true
\n\nExplanation:
\n\nThe substrings "u"
, "uc"
, and "uck"
match the pattern.
\n
Constraints:
\n\n1 <= s.length <= 50
1 <= p.length <= 50
s
contains only lowercase English letters.p
contains only lowercase English letters and exactly one '*'
There is a task management system that allows users to manage their tasks, each associated with a priority. The system should efficiently handle adding, modifying, executing, and removing tasks.
\n\nImplement the TaskManager
class:
TaskManager(vector<vector<int>>& tasks)
initializes the task manager with a list of user-task-priority triples. Each element in the input list is of the form [userId, taskId, priority]
, which adds a task to the specified user with the given priority.
void add(int userId, int taskId, int priority)
adds a task with the specified taskId
and priority
to the user with userId
. It is guaranteed that taskId
does not exist in the system.
void edit(int taskId, int newPriority)
updates the priority of the existing taskId
to newPriority
. It is guaranteed that taskId
exists in the system.
void rmv(int taskId)
removes the task identified by taskId
from the system. It is guaranteed that taskId
exists in the system.
int execTop()
executes the task with the highest priority across all users. If there are multiple tasks with the same highest priority, execute the one with the highest taskId
. After executing, the taskId
is removed from the system. Return the userId
associated with the executed task. If no tasks are available, return -1.
Note that a user may be assigned multiple tasks.
\n\n\n
Example 1:
\n\nInput:
\n["TaskManager", "add", "edit", "execTop", "rmv", "add", "execTop"]
\n[[[[1, 101, 10], [2, 102, 20], [3, 103, 15]]], [4, 104, 5], [102, 8], [], [101], [5, 105, 15], []]
Output:
\n[null, null, null, 3, null, null, 5]
Explanation
\nTaskManager taskManager = new TaskManager([[1, 101, 10], [2, 102, 20], [3, 103, 15]]); // Initializes with three tasks for Users 1, 2, and 3.\n
Constraints:
\n\n1 <= tasks.length <= 105
0 <= userId <= 105
0 <= taskId <= 105
0 <= priority <= 109
0 <= newPriority <= 109
2 * 105
calls will be made in total to add
, edit
, rmv
, and execTop
methods.taskId
will be valid.You are given an array of integers nums
.
Your task is to find the length of the longest subsequence seq
of nums
, such that the absolute differences between consecutive elements form a non-increasing sequence of integers. In other words, for a subsequence seq0
, seq1
, seq2
, ..., seqm
of nums
, |seq1 - seq0| >= |seq2 - seq1| >= ... >= |seqm - seqm - 1|
.
Return the length of such a subsequence.
\n\n\n
Example 1:
\n\nInput: nums = [16,6,3]
\n\nOutput: 3
\n\nExplanation:
\n\nThe longest subsequence is [16, 6, 3]
with the absolute adjacent differences [10, 3]
.
Example 2:
\n\nInput: nums = [6,5,3,4,2,1]
\n\nOutput: 4
\n\nExplanation:
\n\nThe longest subsequence is [6, 4, 2, 1]
with the absolute adjacent differences [2, 2, 1]
.
Example 3:
\n\nInput: nums = [10,20,10,19,10,20]
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest subsequence is [10, 20, 10, 19, 10]
with the absolute adjacent differences [10, 10, 9, 9]
.
\n
Constraints:
\n\n2 <= nums.length <= 104
1 <= nums[i] <= 300
You are given an integer array nums
.
You can do the following operation on the array at most once:
\n\nx
such that nums
remains non-empty on removing all occurrences of x
.x
from the array.Return the maximum subarray sum across all possible resulting arrays.
\n\n\n
Example 1:
\n\nInput: nums = [-3,2,-2,-1,3,-2,3]
\n\nOutput: 7
\n\nExplanation:
\n\nWe can have the following arrays after at most one operation:
\n\nnums = [-3, 2, -2, -1, 3, -2, 3]
. The maximum subarray sum is 3 + (-2) + 3 = 4
.x = -3
results in nums = [2, -2, -1, 3, -2, 3]
. The maximum subarray sum is 3 + (-2) + 3 = 4
.x = -2
results in nums = [-3, 2, -1, 3, 3]
. The maximum subarray sum is 2 + (-1) + 3 + 3 = 7
.x = -1
results in nums = [-3, 2, -2, 3, -2, 3]
. The maximum subarray sum is 3 + (-2) + 3 = 4
.x = 3
results in nums = [-3, 2, -2, -1, -2]
. The maximum subarray sum is 2.The output is max(4, 4, 7, 4, 2) = 7
.
Example 2:
\n\nInput: nums = [1,2,3,4]
\n\nOutput: 10
\n\nExplanation:
\n\nIt is optimal to not perform any operations.
\n\n
Constraints:
\n\n1 <= nums.length <= 105
-106 <= nums[i] <= 106
You are given an array of positive integers nums
.
An array arr
is called product equivalent if prod(arr) == lcm(arr) * gcd(arr)
, where:
prod(arr)
is the product of all elements of arr
.gcd(arr)
is the GCD of all elements of arr
.lcm(arr)
is the LCM of all elements of arr
.Return the length of the longest product equivalent subarray of nums
.
\n
Example 1:
\n\nInput: nums = [1,2,1,2,1,1,1]
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest product equivalent subarray is [1, 2, 1, 1, 1]
, where prod([1, 2, 1, 1, 1]) = 2
, gcd([1, 2, 1, 1, 1]) = 1
, and lcm([1, 2, 1, 1, 1]) = 2
.
Example 2:
\n\nInput: nums = [2,3,4,5,6]
\n\nOutput: 3
\n\nExplanation:
\n\nThe longest product equivalent subarray is [3, 4, 5].
Example 3:
\n\nInput: nums = [1,2,3,1,4,5,1]
\n\nOutput: 5
\n\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 10
You are given a string s
.
We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a'
is 'z'
, and the mirror of 'y'
is 'b'
.
Initially, all characters in the string s
are unmarked.
You start with a score of 0, and you perform the following process on the string s
:
i
, find the closest unmarked index j
such that j < i
and s[j]
is the mirror of s[i]
. Then, mark both indices i
and j
, and add the value i - j
to the total score.j
exists for the index i
, move on to the next index without making any changes.Return the total score at the end of the process.
\n\n\n
Example 1:
\n\nInput: s = "aczzx"
\n\nOutput: 5
\n\nExplanation:
\n\ni = 0
. There is no index j
that satisfies the conditions, so we skip.i = 1
. There is no index j
that satisfies the conditions, so we skip.i = 2
. The closest index j
that satisfies the conditions is j = 0
, so we mark both indices 0 and 2, and then add 2 - 0 = 2
to the score.i = 3
. There is no index j
that satisfies the conditions, so we skip.i = 4
. The closest index j
that satisfies the conditions is j = 1
, so we mark both indices 1 and 4, and then add 4 - 1 = 3
to the score.Example 2:
\n\nInput: s = "abcdef"
\n\nOutput: 0
\n\nExplanation:
\n\nFor each index i
, there is no index j
that satisfies the conditions.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.There are an infinite amount of bags on a number line, one bag for each coordinate. Some of these bags contain coins.
\n\nYou are given a 2D array coins
, where coins[i] = [li, ri, ci]
denotes that every bag from li
to ri
contains ci
coins.
The segments that coins
contain are non-overlapping.
You are also given an integer k
.
Return the maximum amount of coins you can obtain by collecting k
consecutive bags.
\n
Example 1:
\n\nInput: coins = [[8,10,1],[1,3,2],[5,6,4]], k = 4
\n\nOutput: 10
\n\nExplanation:
\n\nSelecting bags at positions [3, 4, 5, 6]
gives the maximum number of coins: 2 + 0 + 4 + 4 = 10
.
Example 2:
\n\nInput: coins = [[1,10,3]], k = 2
\n\nOutput: 6
\n\nExplanation:
\n\nSelecting bags at positions [1, 2]
gives the maximum number of coins: 3 + 3 = 6
.
\n
Constraints:
\n\n1 <= coins.length <= 105
1 <= k <= 109
coins[i] == [li, ri, ci]
1 <= li <= ri <= 109
1 <= ci <= 1000
You are given a 2D integer array intervals
, where intervals[i] = [li, ri, weighti]
. Interval i
starts at position li
and ends at ri
, and has a weight of weighti
. You can choose up to 4 non-overlapping intervals. The score of the chosen intervals is defined as the total sum of their weights.
Return the lexicographically smallest array of at most 4 indices from intervals
with maximum score, representing your choice of non-overlapping intervals.
Two intervals are said to be non-overlapping if they do not share any points. In particular, intervals sharing a left or right boundary are considered overlapping.
\n\n\n
Example 1:
\n\nInput: intervals = [[1,3,2],[4,5,2],[1,5,5],[6,9,3],[6,7,1],[8,9,1]]
\n\nOutput: [2,3]
\n\nExplanation:
\n\nYou can choose the intervals with indices 2, and 3 with respective weights of 5, and 3.
\nExample 2:
\n\nInput: intervals = [[5,8,1],[6,7,7],[4,7,3],[9,10,6],[7,8,2],[11,14,3],[3,5,5]]
\n\nOutput: [1,3,5,6]
\n\nExplanation:
\n\nYou can choose the intervals with indices 1, 3, 5, and 6 with respective weights of 7, 6, 3, and 5.
\n\n
Constraints:
\n\n1 <= intevals.length <= 5 * 104
intervals[i].length == 3
intervals[i] = [li, ri, weighti]
1 <= li <= ri <= 109
1 <= weighti <= 109
You are given an m x n
2D array grid
of positive integers.
Your task is to traverse grid
in a zigzag pattern while skipping every alternate cell.
Zigzag pattern traversal is defined as following the below actions:
\n\n(0, 0)
.Note that you must skip every alternate cell during the traversal.
\n\nReturn an array of integers result
containing, in order, the value of the cells visited during the zigzag traversal with skips.
\n
Example 1:
\n\nInput: grid = [[1,2],[3,4]]
\n\nOutput: [1,4]
\n\nExplanation:
\n\nExample 2:
\n\nInput: grid = [[2,1],[2,1],[2,1]]
\n\nOutput: [2,1,2]
\n\nExplanation:
\n\nExample 3:
\n\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]
\n\nOutput: [1,3,5,7,9]
\n\nExplanation:
\n\n\n
Constraints:
\n\n2 <= n == grid.length <= 50
2 <= m == grid[i].length <= 50
1 <= grid[i][j] <= 2500
You are given an m x n
grid. A robot starts at the top-left corner of the grid (0, 0)
and wants to reach the bottom-right corner (m - 1, n - 1)
. The robot can move either right or down at any point in time.
The grid contains a value coins[i][j]
in each cell:
coins[i][j] >= 0
, the robot gains that many coins.coins[i][j] < 0
, the robot encounters a robber, and the robber steals the absolute value of coins[i][j]
coins.The robot has a special ability to neutralize robbers in at most 2 cells on its path, preventing them from stealing coins in those cells.
\n\nNote: The robot's total coins can be negative.
\n\nReturn the maximum profit the robot can gain on the route.
\n\n\n
Example 1:
\n\nInput: coins = [[0,1,-1],[1,-2,3],[2,-3,4]]
\n\nOutput: 8
\n\nExplanation:
\n\nAn optimal path for maximum coins is:
\n\n(0, 0)
with 0
coins (total coins = 0
).(0, 1)
, gaining 1
coin (total coins = 0 + 1 = 1
).(1, 1)
, where there's a robber stealing 2
coins. The robot uses one neutralization here, avoiding the robbery (total coins = 1
).(1, 2)
, gaining 3
coins (total coins = 1 + 3 = 4
).(2, 2)
, gaining 4
coins (total coins = 4 + 4 = 8
).Example 2:
\n\nInput: coins = [[10,10,10],[10,10,10]]
\n\nOutput: 40
\n\nExplanation:
\n\nAn optimal path for maximum coins is:
\n\n(0, 0)
with 10
coins (total coins = 10
).(0, 1)
, gaining 10
coins (total coins = 10 + 10 = 20
).(0, 2)
, gaining another 10
coins (total coins = 20 + 10 = 30
).(1, 2)
, gaining the final 10
coins (total coins = 30 + 10 = 40
).\n
Constraints:
\n\nm == coins.length
n == coins[i].length
1 <= m, n <= 500
-1000 <= coins[i][j] <= 1000
You are given two integers, n
and threshold
, as well as a directed weighted graph of n
nodes numbered from 0 to n - 1
. The graph is represented by a 2D integer array edges
, where edges[i] = [Ai, Bi, Wi]
indicates that there is an edge going from node Ai
to node Bi
with weight Wi
.
You have to remove some edges from this graph (possibly none), so that it satisfies the following conditions:
\n\nthreshold
outgoing edges.Return the minimum possible value of the maximum edge weight after removing the necessary edges. If it is impossible for all conditions to be satisfied, return -1.
\n\n\n
Example 1:
\n\nInput: n = 5, edges = [[1,0,1],[2,0,2],[3,0,1],[4,3,1],[2,1,1]], threshold = 2
\n\nOutput: 1
\n\nExplanation:
\n\nRemove the edge 2 -> 0
. The maximum weight among the remaining edges is 1.
Example 2:
\n\nInput: n = 5, edges = [[0,1,1],[0,2,2],[0,3,1],[0,4,1],[1,2,1],[1,4,1]], threshold = 1
\n\nOutput: -1
\n\nExplanation:
\n\nIt is impossible to reach node 0 from node 2.
\nExample 3:
\n\nInput: n = 5, edges = [[1,2,1],[1,3,3],[1,4,5],[2,3,2],[3,4,2],[4,0,1]], threshold = 1
\n\nOutput: 2
\n\nExplanation:
\n\nRemove the edges 1 -> 3
and 1 -> 4
. The maximum weight among the remaining edges is 2.
Example 4:
\n\nInput: n = 5, edges = [[1,2,1],[1,3,3],[1,4,5],[2,3,2],[4,0,1]], threshold = 1
\n\nOutput: -1
\n\n
Constraints:
\n\n2 <= n <= 105
1 <= threshold <= n - 1
1 <= edges.length <= min(105, n * (n - 1) / 2).
edges[i].length == 3
0 <= Ai, Bi < n
Ai != Bi
1 <= Wi <= 106
You are given an array nums
of n
integers and an integer k
.
For each subarray of nums
, you can apply up to k
operations on it. In each operation, you increment any element of the subarray by 1.
Note that each subarray is considered independently, meaning changes made to one subarray do not persist to another.
\n\nReturn the number of subarrays that you can make non-decreasing \u200b\u200b\u200b\u200b\u200bafter performing at most k
operations.
An array is said to be non-decreasing if each element is greater than or equal to its previous element, if it exists.
\n\n\n
Example 1:
\n\nInput: nums = [6,3,1,2,4,4], k = 7
\n\nOutput: 17
\n\nExplanation:
\n\nOut of all 21 possible subarrays of nums
, only the subarrays [6, 3, 1]
, [6, 3, 1, 2]
, [6, 3, 1, 2, 4]
and [6, 3, 1, 2, 4, 4]
cannot be made non-decreasing after applying up to k = 7 operations. Thus, the number of non-decreasing subarrays is 21 - 4 = 17
.
Example 2:
\n\nInput: nums = [6,3,1,3,6], k = 4
\n\nOutput: 12
\n\nExplanation:
\n\nThe subarray [3, 1, 3, 6]
along with all subarrays of nums
with three or fewer elements, except [6, 3, 1]
, can be made non-decreasing after k
operations. There are 5 subarrays of a single element, 4 subarrays of two elements, and 2 subarrays of three elements except [6, 3, 1]
, so there are 1 + 5 + 4 + 2 = 12
subarrays that can be made non-decreasing.
\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
Table: Scores
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| student_id | int |\n| subject | varchar |\n| score | int |\n| exam_date | varchar |\n+-------------+---------+\n(student_id, subject, exam_date) is the primary key for this table.\nEach row contains information about a student's score in a specific subject on a particular exam date. score is between 0 and 100 (inclusive).\n\n\n
Write a solution to find the students who have shown improvement. A student is considered to have shown improvement if they meet both of these conditions:
\n\nReturn the result table ordered by student_id,
subject
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nScores table:
\n\n\n+------------+----------+-------+------------+\n| student_id | subject | score | exam_date |\n+------------+----------+-------+------------+\n| 101 | Math | 70 | 2023-01-15 |\n| 101 | Math | 85 | 2023-02-15 |\n| 101 | Physics | 65 | 2023-01-15 |\n| 101 | Physics | 60 | 2023-02-15 |\n| 102 | Math | 80 | 2023-01-15 |\n| 102 | Math | 85 | 2023-02-15 |\n| 103 | Math | 90 | 2023-01-15 |\n| 104 | Physics | 75 | 2023-01-15 |\n| 104 | Physics | 85 | 2023-02-15 |\n+------------+----------+-------+------------+\n\n\n
Output:
\n\n\n+------------+----------+-------------+--------------+\n| student_id | subject | first_score | latest_score |\n+------------+----------+-------------+--------------+\n| 101 | Math | 70 | 85 |\n| 102 | Math | 80 | 85 |\n| 104 | Physics | 75 | 85 |\n+------------+----------+-------------+--------------+\n\n\n
Explanation:
\n\nResult table is ordered by student_id, subject.
\nGiven a circular array nums
, find the maximum absolute difference between adjacent elements.
Note: In a circular array, the first and last elements are adjacent.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,4]
\n\nOutput: 3
\n\nExplanation:
\n\nBecause nums
is circular, nums[0]
and nums[2]
are adjacent. They have the maximum absolute difference of |4 - 1| = 3
.
Example 2:
\n\nInput: nums = [-5,-10,-5]
\n\nOutput: 5
\n\nExplanation:
\n\nThe adjacent elements nums[0]
and nums[1]
have the maximum absolute difference of |-5 - (-10)| = 5
.
\n
Constraints:
\n\n2 <= nums.length <= 100
-100 <= nums[i] <= 100
You are given two integer arrays arr
and brr
of length n
, and an integer k
. You can perform the following operations on arr
any number of times:
arr
into any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost of k
.Choose any element in arr
and add or subtract a positive integer x
to it. The cost of this operation is x
.
Return the minimum total cost to make arr
equal to brr
.
\n
Example 1:
\n\nInput: arr = [-7,9,5], brr = [7,-2,-5], k = 2
\n\nOutput: 13
\n\nExplanation:
\n\narr
into two contiguous subarrays: [-7]
and [9, 5]
and rearrange them as [9, 5, -7]
, with a cost of 2.arr[0]
. The array becomes [7, 5, -7]
. The cost of this operation is 2.arr[1]
. The array becomes [7, -2, -7]
. The cost of this operation is 7.arr[2]
. The array becomes [7, -2, -5]
. The cost of this operation is 2.The total cost to make the arrays equal is 2 + 2 + 7 + 2 = 13
.
Example 2:
\n\nInput: arr = [2,1], brr = [2,1], k = 0
\n\nOutput: 0
\n\nExplanation:
\n\nSince the arrays are already equal, no operations are needed, and the total cost is 0.
\n\n
Constraints:
\n\n1 <= arr.length == brr.length <= 105
0 <= k <= 2 * 1010
-105 <= arr[i] <= 105
-105 <= brr[i] <= 105
You are given an undirected tree rooted at node 0
with n
nodes numbered from 0
to n - 1
, represented by a 2D array edges
of length n - 1
, where edges[i] = [ui, vi, lengthi]
indicates an edge between nodes ui
and vi
with length lengthi
. You are also given an integer array nums
, where nums[i]
represents the value at node i
.
A special path is defined as a downward path from an ancestor node to a descendant node such that all the values of the nodes in that path are unique.
\n\nNote that a path may start and end at the same node.
\n\nReturn an array result
of size 2, where result[0]
is the length of the longest special path, and result[1]
is the minimum number of nodes in all possible longest special paths.
\n
Example 1:
\n\nInput: edges = [[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]], nums = [2,1,2,1,3,1]
\n\nOutput: [6,2]
\n\nExplanation:
\n\nnums
The longest special paths are 2 -> 5
and 0 -> 1 -> 4
, both having a length of 6. The minimum number of nodes across all longest special paths is 2.
Example 2:
\n\nInput: edges = [[1,0,8]], nums = [2,2]
\n\nOutput: [0,1]
\n\nExplanation:
\n\nThe longest special paths are 0
and 1
, both having a length of 0. The minimum number of nodes across all longest special paths is 1.
\n
Constraints:
\n\n2 <= n <= 5 * 104
edges.length == n - 1
edges[i].length == 3
0 <= ui, vi < n
1 <= lengthi <= 103
nums.length == n
0 <= nums[i] <= 5 * 104
edges
represents a valid tree.You are given three integers m
, n
, and k
.
There is a rectangular grid of size m × n
containing k
identical pieces. Return the sum of Manhattan distances between every pair of pieces over all valid arrangements of pieces.
A valid arrangement is a placement of all k
pieces on the grid with at most one piece per cell.
Since the answer may be very large, return it modulo 109 + 7
.
The Manhattan Distance between two cells (xi, yi)
and (xj, yj)
is |xi - xj| + |yi - yj|
.
\n
Example 1:
\n\nInput: m = 2, n = 2, k = 2
\n\nOutput: 8
\n\nExplanation:
\n\nThe valid arrangements of pieces on the board are:
\n\nThus, the total Manhattan distance across all valid arrangements is 1 + 1 + 1 + 1 + 2 + 2 = 8
.
Example 2:
\n\nInput: m = 1, n = 4, k = 3
\n\nOutput: 20
\n\nExplanation:
\n\nThe valid arrangements of pieces on the board are:
\n\n1 + 1 + 2 = 4
.1 + 2 + 3 = 6
.The total Manhattan distance between all pairs of pieces across all arrangements is 4 + 6 + 6 + 4 = 20
.
\n
Constraints:
\n\n1 <= m, n <= 105
2 <= m * n <= 105
2 <= k <= m * n
You are given an integer array nums
of size n
. For each index i
where 0 <= i < n
, define a subarray nums[start ... i]
where start = max(0, i - nums[i])
.
Return the total sum of all elements from the subarray defined for each index in the array.
\n\n\n
Example 1:
\n\nInput: nums = [2,3,1]
\n\nOutput: 11
\n\nExplanation:
\n\ni | \n\t\t\tSubarray | \n\t\t\tSum | \n\t\t
---|---|---|
0 | \n\t\t\tnums[0] = [2] | \n\t\t\t2 | \n\t\t
1 | \n\t\t\tnums[0 ... 1] = [2, 3] | \n\t\t\t5 | \n\t\t
2 | \n\t\t\tnums[1 ... 2] = [3, 1] | \n\t\t\t4 | \n\t\t
Total Sum | \n\t\t\t\n\t\t\t | 11 | \n\t\t
The total sum is 11. Hence, 11 is the output.
\nExample 2:
\n\nInput: nums = [3,1,1,2]
\n\nOutput: 13
\n\nExplanation:
\n\ni | \n\t\t\tSubarray | \n\t\t\tSum | \n\t\t
---|---|---|
0 | \n\t\t\tnums[0] = [3] | \n\t\t\t3 | \n\t\t
1 | \n\t\t\tnums[0 ... 1] = [3, 1] | \n\t\t\t4 | \n\t\t
2 | \n\t\t\tnums[1 ... 2] = [1, 1] | \n\t\t\t2 | \n\t\t
3 | \n\t\t\tnums[1 ... 3] = [1, 1, 2] | \n\t\t\t4 | \n\t\t
Total Sum | \n\t\t\t\n\t\t\t | 13 | \n\t\t
The total sum is 13. Hence, 13 is the output.
\n\n
Constraints:
\n\n1 <= n == nums.length <= 100
1 <= nums[i] <= 1000
You are given an integer array nums
and a positive integer k
. Return the sum of the maximum and minimum elements of all subsequences of nums
with at most k
elements.
Since the answer may be very large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [1,2,3], k = 2
\n\nOutput: 24
\n\nExplanation:
\n\nThe subsequences of nums
with at most 2 elements are:
Subsequence | \n\t\t\tMinimum | \n\t\t\tMaximum | \n\t\t\tSum | \n\t\t
---|---|---|---|
[1] | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
[2] | \n\t\t\t2 | \n\t\t\t2 | \n\t\t\t4 | \n\t\t
[3] | \n\t\t\t3 | \n\t\t\t3 | \n\t\t\t6 | \n\t\t
[1, 2] | \n\t\t\t1 | \n\t\t\t2 | \n\t\t\t3 | \n\t\t
[1, 3] | \n\t\t\t1 | \n\t\t\t3 | \n\t\t\t4 | \n\t\t
[2, 3] | \n\t\t\t2 | \n\t\t\t3 | \n\t\t\t5 | \n\t\t
Final Total | \n\t\t\t\n\t\t\t | \n\t\t\t | 24 | \n\t\t
The output would be 24.
\nExample 2:
\n\nInput: nums = [5,0,6], k = 1
\n\nOutput: 22
\n\nExplanation:
\n\nFor subsequences with exactly 1 element, the minimum and maximum values are the element itself. Therefore, the total is 5 + 5 + 0 + 0 + 6 + 6 = 22
.
Example 3:
\n\nInput: nums = [1,1,1], k = 2
\n\nOutput: 12
\n\nExplanation:
\n\nThe subsequences [1, 1]
and [1]
each appear 3 times. For all of them, the minimum and maximum are both 1. Thus, the total is 12.
\n
Constraints:
\n\n1 <= nums.length <= 105
0 <= nums[i] <= 109
1 <= k <= min(70, nums.length)
You are given an even integer n
representing the number of houses arranged in a straight line, and a 2D array cost
of size n x 3
, where cost[i][j]
represents the cost of painting house i
with color j + 1
.
The houses will look beautiful if they satisfy the following conditions:
\n\nn = 6
, houses at positions (0, 5)
, (1, 4)
, and (2, 3)
are considered equidistant.Return the minimum cost to paint the houses such that they look beautiful.
\n\n\n
Example 1:
\n\nInput: n = 4, cost = [[3,5,7],[6,2,9],[4,8,1],[7,3,5]]
\n\nOutput: 9
\n\nExplanation:
\n\nThe optimal painting sequence is [1, 2, 3, 2]
with corresponding costs [3, 2, 1, 3]
. This satisfies the following conditions:
(1 != 2)
.(2 != 3)
.The minimum cost to paint the houses so that they look beautiful is 3 + 2 + 1 + 3 = 9
.
Example 2:
\n\nInput: n = 6, cost = [[2,4,6],[5,3,8],[7,1,9],[4,6,2],[3,5,7],[8,2,4]]
\n\nOutput: 18
\n\nExplanation:
\n\nThe optimal painting sequence is [1, 3, 2, 3, 1, 2]
with corresponding costs [2, 8, 1, 2, 3, 2]
. This satisfies the following conditions:
(1 != 2)
.(3 != 1)
.(2 != 3)
.The minimum cost to paint the houses so that they look beautiful is 2 + 8 + 1 + 2 + 3 + 2 = 18
.
\n
Constraints:
\n\n2 <= n <= 105
n
is even.cost.length == n
cost[i].length == 3
0 <= cost[i][j] <= 105
You are given an integer array nums
and a positive integer k
. Return the sum of the maximum and minimum elements of all subarrays with at most k
elements.
\n
Example 1:
\n\nInput: nums = [1,2,3], k = 2
\n\nOutput: 20
\n\nExplanation:
\n\nThe subarrays of nums
with at most 2 elements are:
Subarray | \n\t\t\tMinimum | \n\t\t\tMaximum | \n\t\t\tSum | \n\t\t
---|---|---|---|
[1] | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
[2] | \n\t\t\t2 | \n\t\t\t2 | \n\t\t\t4 | \n\t\t
[3] | \n\t\t\t3 | \n\t\t\t3 | \n\t\t\t6 | \n\t\t
[1, 2] | \n\t\t\t1 | \n\t\t\t2 | \n\t\t\t3 | \n\t\t
[2, 3] | \n\t\t\t2 | \n\t\t\t3 | \n\t\t\t5 | \n\t\t
Final Total | \n\t\t\t\n\t\t\t | \n\t\t\t | 20 | \n\t\t
The output would be 20.
\nExample 2:
\n\nInput: nums = [1,-3,1], k = 2
\n\nOutput: -6
\n\nExplanation:
\n\nThe subarrays of nums
with at most 2 elements are:
Subarray | \n\t\t\tMinimum | \n\t\t\tMaximum | \n\t\t\tSum | \n\t\t
---|---|---|---|
[1] | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
[-3] | \n\t\t\t-3 | \n\t\t\t-3 | \n\t\t\t-6 | \n\t\t
[1] | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t2 | \n\t\t
[1, -3] | \n\t\t\t-3 | \n\t\t\t1 | \n\t\t\t-2 | \n\t\t
[-3, 1] | \n\t\t\t-3 | \n\t\t\t1 | \n\t\t\t-2 | \n\t\t
Final Total | \n\t\t\t\n\t\t\t | \n\t\t\t | -6 | \n\t\t
The output would be -6.
\n\n
Constraints:
\n\n1 <= nums.length <= 80000
1 <= k <= nums.length
-106 <= nums[i] <= 106
You are given an integer array nums
of length n
.
A partition is defined as an index i
where 0 <= i < n - 1
, splitting the array into two non-empty subarrays such that:
[0, i]
.[i + 1, n - 1]
.Return the number of partitions where the difference between the sum of the left and right subarrays is even.
\n\n\n
Example 1:
\n\nInput: nums = [10,10,3,7,6]
\n\nOutput: 4
\n\nExplanation:
\n\nThe 4 partitions are:
\n\n[10]
, [10, 3, 7, 6]
with a sum difference of 10 - 26 = -16
, which is even.[10, 10]
, [3, 7, 6]
with a sum difference of 20 - 16 = 4
, which is even.[10, 10, 3]
, [7, 6]
with a sum difference of 23 - 13 = 10
, which is even.[10, 10, 3, 7]
, [6]
with a sum difference of 30 - 6 = 24
, which is even.Example 2:
\n\nInput: nums = [1,2,2]
\n\nOutput: 0
\n\nExplanation:
\n\nNo partition results in an even sum difference.
\nExample 3:
\n\nInput: nums = [2,4,6,8]
\n\nOutput: 3
\n\nExplanation:
\n\nAll partitions result in an even sum difference.
\n\n
Constraints:
\n\n2 <= n == nums.length <= 100
1 <= nums[i] <= 100
You are given an integer numberOfUsers
representing the total number of users and an array events
of size n x 3
.
Each events[i]
can be either of the following two types:
["MESSAGE", "timestampi", "mentions_stringi"]
\n\n\ttimestampi
.mentions_stringi
string can contain one of the following tokens:\n\t\tid<number>
: where <number>
is an integer in range [0,numberOfUsers - 1]
. There can be multiple ids separated by a single whitespace and may contain duplicates. This can mention even the offline users.ALL
: mentions all users.HERE
: mentions all online users.["OFFLINE", "timestampi", "idi"]
\n\tidi
had become offline at timestampi
for 60 time units. The user will automatically be online again at time timestampi + 60
.Return an array mentions
where mentions[i]
represents the number of mentions the user with id i
has across all MESSAGE
events.
All users are initially online, and if a user goes offline or comes back online, their status change is processed before handling any message event that occurs at the same timestamp.
\n\nNote that a user can be mentioned multiple times in a single message event, and each mention should be counted separately.
\n\n\n
Example 1:
\n\nInput: numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","71","HERE"]]
\n\nOutput: [2,2]
\n\nExplanation:
\n\nInitially, all users are online.
\n\nAt timestamp 10, id1
and id0
are mentioned. mentions = [1,1]
At timestamp 11, id0
goes offline.
At timestamp 71, id0
comes back online and "HERE"
is mentioned. mentions = [2,2]
Example 2:
\n\nInput: numberOfUsers = 2, events = [["MESSAGE","10","id1 id0"],["OFFLINE","11","0"],["MESSAGE","12","ALL"]]
\n\nOutput: [2,2]
\n\nExplanation:
\n\nInitially, all users are online.
\n\nAt timestamp 10, id1
and id0
are mentioned. mentions = [1,1]
At timestamp 11, id0
goes offline.
At timestamp 12, "ALL"
is mentioned. This includes offline users, so both id0
and id1
are mentioned. mentions = [2,2]
Example 3:
\n\nInput: numberOfUsers = 2, events = [["OFFLINE","10","0"],["MESSAGE","12","HERE"]]
\n\nOutput: [0,1]
\n\nExplanation:
\n\nInitially, all users are online.
\n\nAt timestamp 10, id0
goes offline.
At timestamp 12, "HERE"
is mentioned. Because id0
is still offline, they will not be mentioned. mentions = [0,1]
\n
Constraints:
\n\n1 <= numberOfUsers <= 100
1 <= events.length <= 100
events[i].length == 3
events[i][0]
will be one of MESSAGE
or OFFLINE
.1 <= int(events[i][1]) <= 105
id<number>
mentions in any "MESSAGE"
event is between 1
and 100
.0 <= <number> <= numberOfUsers - 1
OFFLINE
event is online at the time the event occurs.You are given an array nums
of length n
. You are also given an integer k
.
You perform the following operation on nums
once:
nums[i..j]
where 0 <= i <= j <= n - 1
.x
and add x
to all the elements in nums[i..j]
.Find the maximum frequency of the value k
after the operation.
\n
Example 1:
\n\nInput: nums = [1,2,3,4,5,6], k = 1
\n\nOutput: 2
\n\nExplanation:
\n\nAfter adding -5 to nums[2..5]
, 1 has a frequency of 2 in [1, 2, -2, -1, 0, 1]
.
Example 2:
\n\nInput: nums = [10,2,3,4,5,5,4,3,2,2], k = 10
\n\nOutput: 4
\n\nExplanation:
\n\nAfter adding 8 to nums[1..9]
, 10 has a frequency of 4 in [10, 10, 11, 12, 13, 13, 12, 11, 10, 10]
.
\n
Constraints:
\n\n1 <= n == nums.length <= 105
1 <= nums[i] <= 50
1 <= k <= 50
You are given an array of strings words
. Find all shortest common supersequences (SCS) of words
that are not permutations of each other.
A shortest common supersequence is a string of minimum length that contains each string in words
as a subsequence.
Return a 2D array of integers freqs
that represent all the SCSs. Each freqs[i]
is an array of size 26, representing the frequency of each letter in the lowercase English alphabet for a single SCS. You may return the frequency arrays in any order.
\n
Example 1:
\n\nInput: words = ["ab","ba"]
\n\nOutput: [[1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
\n\nExplanation:
\n\nThe two SCSs are "aba"
and "bab"
. The output is the letter frequencies for each one.
Example 2:
\n\nInput: words = ["aa","ac"]
\n\nOutput: [[2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
\n\nExplanation:
\n\nThe two SCSs are "aac"
and "aca"
. Since they are permutations of each other, keep only "aac"
.
Example 3:
\n\nInput: words = ["aa","bb","cc"]
\n\nOutput: [[2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
\n\nExplanation:
\n\n"aabbcc"
and all its permutations are SCSs.
\n
Constraints:
\n\n1 <= words.length <= 256
words[i].length == 2
words
will altogether be composed of no more than 16 unique lowercase letters.words
are unique.Table: Users
\n+-----------------+---------+\n| Column Name | Type |\n+-----------------+---------+\n| user_id | int |\n| email | varchar |\n+-----------------+---------+\n(user_id) is the unique key for this table.\nEach row contains a user's unique ID and email address.\n\n\n
Write a solution to find all the valid email addresses. A valid email address meets the following criteria:
\n\n@
symbol..com
.@
symbol contains only alphanumeric characters and underscores.@
symbol and before .com
contains a domain name that contains only letters.Return the result table ordered by user_id
in ascending order.
\n
Example:
\n\nInput:
\n\nUsers table:
\n\n\n+---------+---------------------+\n| user_id | email |\n+---------+---------------------+\n| 1 | alice@example.com |\n| 2 | bob_at_example.com |\n| 3 | charlie@example.net |\n| 4 | david@domain.com |\n| 5 | eve@invalid |\n+---------+---------------------+\n\n\n
Output:
\n\n\n+---------+-------------------+\n| user_id | email |\n+---------+-------------------+\n| 1 | alice@example.com |\n| 4 | david@domain.com |\n+---------+-------------------+\n\n\n
Explanation:
\n\n@
, alice is alphanumeric, and example.com starts with a letter and ends with .com.@
..com
..com
.Result table is ordered by user_id in ascending order.
\nn
positive integers while ensuring that each added number alternates between odd and even."
@@ -129224,9 +129606,9 @@
"questionFrontendId": "3438",
"title": "Find Valid Pair of Adjacent Digits in String",
"content": "You are given a string s
consisting only of digits. A valid pair is defined as two adjacent digits in s
such that:
s
exactly as many times as its numeric value.Return the first valid pair found in the string s
when traversing from left to right. If no valid pair exists, return an empty string.
\n
Example 1:
\n\nInput: s = "2523533"
\n\nOutput: "23"
\n\nExplanation:
\n\nDigit '2'
appears 2 times and digit '3'
appears 3 times. Each digit in the pair "23"
appears in s
exactly as many times as its numeric value. Hence, the output is "23"
.
Example 2:
\n\nInput: s = "221"
\n\nOutput: "21"
\n\nExplanation:
\n\nDigit '2'
appears 2 times and digit '1'
appears 1 time. Hence, the output is "21"
.
Example 3:
\n\nInput: s = "22"
\n\nOutput: ""
\n\nExplanation:
\n\nThere are no valid adjacent pairs.
\n\n
Constraints:
\n\n2 <= s.length <= 100
s
only consists of digits from '1'
to '9'
.You are given an integer eventTime
denoting the duration of an event, where the event occurs from time t = 0
to time t = eventTime
.
You are also given two integer arrays startTime
and endTime
, each of length n
. These represent the start and end time of n
non-overlapping meetings, where the ith
meeting occurs during the time [startTime[i], endTime[i]]
.
You can reschedule at most k
meetings by moving their start time while maintaining the same duration, to maximize the longest continuous period of free time during the event.
The relative order of all the meetings should stay the same and they should remain non-overlapping.
\n\nReturn the maximum amount of free time possible after rearranging the meetings.
\n\nNote that the meetings can not be rescheduled to a time outside the event.
\n\n\n
Example 1:
\n\nInput: eventTime = 5, k = 1, startTime = [1,3], endTime = [2,5]
\n\nOutput: 2
\n\nExplanation:
\n\nReschedule the meeting at [1, 2]
to [2, 3]
, leaving no meetings during the time [0, 2]
.
Example 2:
\n\nInput: eventTime = 10, k = 1, startTime = [0,2,9], endTime = [1,4,10]
\n\nOutput: 6
\n\nExplanation:
\n\nReschedule the meeting at [2, 4]
to [1, 3]
, leaving no meetings during the time [3, 9]
.
Example 3:
\n\nInput: eventTime = 5, k = 2, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no time during the event not occupied by meetings.
\n\n
Constraints:
\n\n1 <= eventTime <= 109
n == startTime.length == endTime.length
2 <= n <= 105
1 <= k <= n
0 <= startTime[i] < endTime[i] <= eventTime
endTime[i] <= startTime[i + 1]
where i
lies in the range [0, n - 2]
.You are given an integer eventTime
denoting the duration of an event. You are also given two integer arrays startTime
and endTime
, each of length n
.
These represent the start and end times of n
non-overlapping meetings that occur during the event between time t = 0
and time t = eventTime
, where the ith
meeting occurs during the time [startTime[i], endTime[i]].
You can reschedule at most one meeting by moving its start time while maintaining the same duration, such that the meetings remain non-overlapping, to maximize the longest continuous period of free time during the event.
\n\nReturn the maximum amount of free time possible after rearranging the meetings.
\n\nNote that the meetings can not be rescheduled to a time outside the event and they should remain non-overlapping.
\n\nNote: In this version, it is valid for the relative ordering of the meetings to change after rescheduling one meeting.
\n\n\n
Example 1:
\n\nInput: eventTime = 5, startTime = [1,3], endTime = [2,5]
\n\nOutput: 2
\n\nExplanation:
\n\nReschedule the meeting at [1, 2]
to [2, 3]
, leaving no meetings during the time [0, 2]
.
Example 2:
\n\nInput: eventTime = 10, startTime = [0,7,9], endTime = [1,8,10]
\n\nOutput: 7
\n\nExplanation:
\n\nReschedule the meeting at [0, 1]
to [8, 9]
, leaving no meetings during the time [0, 7]
.
Example 3:
\n\nInput: eventTime = 10, startTime = [0,3,7,9], endTime = [1,4,8,10]
\n\nOutput: 6
\n\nExplanation:
\n\nReschedule the meeting at [3, 4]
to [8, 9]
, leaving no meetings during the time [1, 7]
.
Example 4:
\n\nInput: eventTime = 5, startTime = [0,1,2,3,4], endTime = [1,2,3,4,5]
\n\nOutput: 0
\n\nExplanation:
\n\nThere is no time during the event not occupied by meetings.
\n\n
Constraints:
\n\n1 <= eventTime <= 109
n == startTime.length == endTime.length
2 <= n <= 105
0 <= startTime[i] < endTime[i] <= eventTime
endTime[i] <= startTime[i + 1]
where i
lies in the range [0, n - 2]
.You are given a string caption
of length n
. A good caption is a string where every character appears in groups of at least 3 consecutive occurrences.
For example:
\n\n"aaabbb"
and "aaaaccc"
are good captions."aabbb"
and "ccccd"
are not good captions.You can perform the following operation any number of times:
\n\nChoose an index i
(where 0 <= i < n
) and change the character at that index to either:
caption[i] != 'a'
).caption[i] != 'z'
).Your task is to convert the given caption
into a good caption using the minimum number of operations, and return it. If there are multiple possible good captions, return the lexicographically smallest one among them. If it is impossible to create a good caption, return an empty string ""
.
\n
Example 1:
\n\nInput: caption = "cdcd"
\n\nOutput: "cccc"
\n\nExplanation:
\n\nIt can be shown that the given caption cannot be transformed into a good caption with fewer than 2 operations. The possible good captions that can be created using exactly 2 operations are:
\n\n"dddd"
: Change caption[0]
and caption[2]
to their next character 'd'
."cccc"
: Change caption[1]
and caption[3]
to their previous character 'c'
.Since "cccc"
is lexicographically smaller than "dddd"
, return "cccc"
.
Example 2:
\n\nInput: caption = "aca"
\n\nOutput: "aaa"
\n\nExplanation:
\n\nIt can be proven that the given caption requires at least 2 operations to be transformed into a good caption. The only good caption that can be obtained with exactly 2 operations is as follows:
\n\ncaption[1]
to 'b'
. caption = "aba"
.caption[1]
to 'a'
. caption = "aaa"
.Thus, return "aaa"
.
Example 3:
\n\nInput: caption = "bc"
\n\nOutput: ""
\n\nExplanation:
\n\nIt can be shown that the given caption cannot be converted to a good caption by using any number of operations.
\n\n
Constraints:
\n\n1 <= caption.length <= 5 * 104
caption
consists only of lowercase English letters.You are given a string s
consisting of lowercase English letters. Your task is to find the maximum difference between the frequency of two characters in the string such that:
Return the maximum difference, calculated as the frequency of the character with an odd frequency minus the frequency of the character with an even frequency.
\n\n\n
Example 1:
\n\nInput: s = "aaaaabbc"
\n\nOutput: 3
\n\nExplanation:
\n\n'a'
has an odd frequency of 5
, and 'b'
has an even frequency of 2
.5 - 2 = 3
.Example 2:
\n\nInput: s = "abcabcab"
\n\nOutput: 1
\n\nExplanation:
\n\n'a'
has an odd frequency of 3
, and 'c'
has an even frequency of 2.3 - 2 = 1
.\n
Constraints:
\n\n3 <= s.length <= 100
s
consists only of lowercase English letters.s
contains at least one character with an odd frequency and one with an even frequency.You are given a string s
consisting of lowercase English letters.
Your task is to find the maximum difference diff = freq(a1) - freq(a2)
between the frequency of characters a1
and a2
in the string such that:
a1
has an odd frequency in the string.a2
has an even frequency in the string.Return this maximum difference.
\n\n\n
Example 1:
\n\nInput: s = "aaaaabbc"
\n\nOutput: 3
\n\nExplanation:
\n\n'a'
has an odd frequency of 5
, and 'b'
has an even frequency of 2
.5 - 2 = 3
.Example 2:
\n\nInput: s = "abcabcab"
\n\nOutput: 1
\n\nExplanation:
\n\n'a'
has an odd frequency of 3
, and 'c'
has an even frequency of 2.3 - 2 = 1
.\n
Constraints:
\n\n3 <= s.length <= 100
s
consists only of lowercase English letters.s
contains at least one character with an odd frequency and one with an even frequency.You are given a string s
consisting of the characters 'N'
, 'S'
, 'E'
, and 'W'
, where s[i]
indicates movements in an infinite grid:
'N'
: Move north by 1 unit.'S'
: Move south by 1 unit.'E'
: Move east by 1 unit.'W'
: Move west by 1 unit.Initially, you are at the origin (0, 0)
. You can change at most k
characters to any of the four directions.
Find the maximum Manhattan distance from the origin that can be achieved at any time while performing the movements in order.
\nThe Manhattan Distance between two cells(xi, yi)
and (xj, yj)
is |xi - xj| + |yi - yj|
.\n\n
Example 1:
\n\nInput: s = "NWSE", k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nChange s[2]
from 'S'
to 'N'
. The string s
becomes "NWNE"
.
Movement | \n\t\t\tPosition (x, y) | \n\t\t\tManhattan Distance | \n\t\t\tMaximum | \n\t\t
---|---|---|---|
s[0] == 'N' | \n\t\t\t(0, 1) | \n\t\t\t0 + 1 = 1 | \n\t\t\t1 | \n\t\t
s[1] == 'W' | \n\t\t\t(-1, 1) | \n\t\t\t1 + 1 = 2 | \n\t\t\t2 | \n\t\t
s[2] == 'N' | \n\t\t\t(-1, 2) | \n\t\t\t1 + 2 = 3 | \n\t\t\t3 | \n\t\t
s[3] == 'E' | \n\t\t\t(0, 2) | \n\t\t\t0 + 2 = 2 | \n\t\t\t3 | \n\t\t
The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.
\nExample 2:
\n\nInput: s = "NSWWEW", k = 3
\n\nOutput: 6
\n\nExplanation:
\n\nChange s[1]
from 'S'
to 'N'
, and s[4]
from 'E'
to 'W'
. The string s
becomes "NNWWWW"
.
The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.
\n\n
Constraints:
\n\n1 <= s.length <= 105
0 <= k <= s.length
s
consists of only 'N'
, 'S'
, 'E'
, and 'W'
.You are given two arrays, nums
and target
.
In a single operation, you may increment any element of nums
by 1.
Return the minimum number of operations required so that each element in target
has at least one multiple in nums
.
\n
Example 1:
\n\nInput: nums = [1,2,3], target = [4]
\n\nOutput: 1
\n\nExplanation:
\n\nThe minimum number of operations required to satisfy the condition is 1.
\n\nExample 2:
\n\nInput: nums = [8,4], target = [10,5]
\n\nOutput: 2
\n\nExplanation:
\n\nThe minimum number of operations required to satisfy the condition is 2.
\n\nExample 3:
\n\nInput: nums = [7,9,10], target = [7]
\n\nOutput: 0
\n\nExplanation:
\n\nTarget 7 already has a multiple in nums, so no additional operations are needed.
\n\n
Constraints:
\n\n1 <= nums.length <= 5 * 104
1 <= target.length <= 4
target.length <= nums.length
1 <= nums[i], target[i] <= 104
You are given a string s
and an integer k
. Your task is to find the maximum difference between the frequency of two characters, freq[a] - freq[b]
, in a substring subs
of s
, such that:
subs
has a size of at least k
.a
has an odd frequency in subs
.b
has an even frequency in subs
.Return the maximum difference.
\n\nNote that subs
can contain more than 2 distinct characters.
\n
Example 1:
\n\nInput: s = "12233", k = 4
\n\nOutput: -1
\n\nExplanation:
\n\nFor the substring "12233"
, the frequency of '1'
is 1 and the frequency of '3'
is 2. The difference is 1 - 2 = -1
.
Example 2:
\n\nInput: s = "1122211", k = 3
\n\nOutput: 1
\n\nExplanation:
\n\nFor the substring "11222"
, the frequency of '2'
is 3 and the frequency of '1'
is 2. The difference is 3 - 2 = 1
.
Example 3:
\n\nInput: s = "110", k = 3
\n\nOutput: -1
\n\n
Constraints:
\n\n3 <= s.length <= 3 * 104
s
consists only of digits '0'
to '4'
.1 <= k <= s.length
You are given a string s
and an integer k
. Your task is to find the maximum difference between the frequency of two characters, freq[a] - freq[b]
, in a substring subs
of s
, such that:
subs
has a size of at least k
.a
has an odd frequency in subs
.b
has a non-zero even frequency in subs
.Return the maximum difference.
\n\nNote that subs
can contain more than 2 distinct characters.
\n
Example 1:
\n\nInput: s = "12233", k = 4
\n\nOutput: -1
\n\nExplanation:
\n\nFor the substring "12233"
, the frequency of '1'
is 1 and the frequency of '3'
is 2. The difference is 1 - 2 = -1
.
Example 2:
\n\nInput: s = "1122211", k = 3
\n\nOutput: 1
\n\nExplanation:
\n\nFor the substring "11222"
, the frequency of '2'
is 3 and the frequency of '1'
is 2. The difference is 3 - 2 = 1
.
Example 3:
\n\nInput: s = "110", k = 3
\n\nOutput: -1
\n\n
Constraints:
\n\n3 <= s.length <= 3 * 104
s
consists only of digits '0'
to '4'
.1 <= k <= s.length
You are given an n x n
square matrix of integers grid
. Return the matrix such that:
\n
Example 1:
\n\nInput: grid = [[1,7,3],[9,8,2],[4,5,6]]
\n\nOutput: [[8,2,3],[9,6,7],[4,5,1]]
\n\nExplanation:
\n\nThe diagonals with a black arrow (bottom-left triangle) should be sorted in non-increasing order:
\n\n[1, 8, 6]
becomes [8, 6, 1]
.[9, 5]
and [4]
remain unchanged.The diagonals with a blue arrow (top-right triangle) should be sorted in non-decreasing order:
\n\n[7, 2]
becomes [2, 7]
.[3]
remains unchanged.Example 2:
\n\nInput: grid = [[0,1],[1,2]]
\n\nOutput: [[2,1],[1,0]]
\n\nExplanation:
\n\nThe diagonals with a black arrow must be non-increasing, so [0, 2]
is changed to [2, 0]
. The other diagonals are already in the correct order.
Example 3:
\n\nInput: grid = [[1]]
\n\nOutput: [[1]]
\n\nExplanation:
\n\nDiagonals with exactly one element are already in order, so no changes are needed.
\n\n
Constraints:
\n\ngrid.length == grid[i].length == n
1 <= n <= 10
-105 <= grid[i][j] <= 105
You are given an integer array groups
, where groups[i]
represents the size of the ith
group. You are also given an integer array elements
.
Your task is to assign one element to each group based on the following rules:
\n\nj
can be assigned to a group i
if groups[i]
is divisible by elements[j]
.j
.Return an integer array assigned
, where assigned[i]
is the index of the element chosen for group i
, or -1 if no suitable element exists.
Note: An element may be assigned to more than one group.
\n\n\n
Example 1:
\n\nInput: groups = [8,4,3,2,4], elements = [4,2]
\n\nOutput: [0,0,-1,1,0]
\n\nExplanation:
\n\nelements[0] = 4
is assigned to groups 0, 1, and 4.elements[1] = 2
is assigned to group 3.Example 2:
\n\nInput: groups = [2,3,5,7], elements = [5,3,3]
\n\nOutput: [-1,1,0,-1]
\n\nExplanation:
\n\nelements[1] = 3
is assigned to group 1.elements[0] = 5
is assigned to group 2.Example 3:
\n\nInput: groups = [10,21,30,41], elements = [2,1]
\n\nOutput: [0,1,0,1]
\n\nExplanation:
\n\nelements[0] = 2
is assigned to the groups with even values, and elements[1] = 1
is assigned to the groups with odd values.
\n
Constraints:
\n\n1 <= groups.length <= 105
1 <= elements.length <= 105
1 <= groups[i] <= 105
1 <= elements[i] <= 105
You are given a string s
consisting of digits.
Return the number of substrings of s
divisible by their non-zero last digit.
Note: A substring may contain leading zeros.
\n\n\n
Example 1:
\n\nInput: s = "12936"
\n\nOutput: 11
\n\nExplanation:
\n\nSubstrings "29"
, "129"
, "293"
and "2936"
are not divisible by their last digit. There are 15 substrings in total, so the answer is 15 - 4 = 11
.
Example 2:
\n\nInput: s = "5701283"
\n\nOutput: 18
\n\nExplanation:
\n\nSubstrings "01"
, "12"
, "701"
, "012"
, "128"
, "5701"
, "7012"
, "0128"
, "57012"
, "70128"
, "570128"
, and "701283"
are all divisible by their last digit. Additionally, all substrings that are just 1 non-zero digit are divisible by themselves. Since there are 6 such digits, the answer is 12 + 6 = 18
.
Example 3:
\n\nInput: s = "1010101010"
\n\nOutput: 25
\n\nExplanation:
\n\nOnly substrings that end with digit '1'
are divisible by their last digit. There are 25 such substrings.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of digits only.dp[index][i][j]
be the number of subarrays s[start...index]
such that s[start...index] % i == j
.",
+ "For every pair (i, j)
, add dp[index - 1][i][j]
to dp[index][i][(j * 10 + x)%i)]
.",
+ "You should optimize this solution so that it can fit into the memory limit.",
+ "In order to find dp[index][i][j]
we use values from dp[index - 1][i][j]
. Hence, we can keep only dp[index][i][j]
and dp[index - 1][i][j]
at every iteration of the loop."
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
"solution": null,
"hasSolution": false,
"hasVideoSolution": false,
- "url": "https://leetcode.com/problems/maximum-difference-between-even-and-odd-frequency-ii/"
+ "url": "https://leetcode.com/problems/count-substrings-divisible-by-last-digit/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3762",
+ "questionFrontendId": "3449",
+ "title": "Maximize the Minimum Game Score",
+ "content": "You are given an array points
of size n
and an integer m
. There is another array gameScore
of size n
, where gameScore[i]
represents the score achieved at the ith
game. Initially, gameScore[i] == 0
for all i
.
You start at index -1, which is outside the array (before the first position at index 0). You can make at most m
moves. In each move, you can either:
points[i]
to gameScore[i]
.points[i]
to gameScore[i]
.Note that the index must always remain within the bounds of the array after the first move.
\n\nReturn the maximum possible minimum value in gameScore
after at most m
moves.
\n
Example 1:
\n\nInput: points = [2,4], m = 3
\n\nOutput: 4
\n\nExplanation:
\n\nInitially, index i = -1
and gameScore = [0, 0]
.
Move | \n\t\t\tIndex | \n\t\t\tgameScore | \n\t\t
---|---|---|
Increase i | \n\t\t\t0 | \n\t\t\t[2, 0] | \n\t\t
Increase i | \n\t\t\t1 | \n\t\t\t[2, 4] | \n\t\t
Decrease i | \n\t\t\t0 | \n\t\t\t[4, 4] | \n\t\t
The minimum value in gameScore
is 4, and this is the maximum possible minimum among all configurations. Hence, 4 is the output.
Example 2:
\n\nInput: points = [1,2,3], m = 5
\n\nOutput: 2
\n\nExplanation:
\n\nInitially, index i = -1
and gameScore = [0, 0, 0]
.
Move | \n\t\t\tIndex | \n\t\t\tgameScore | \n\t\t
---|---|---|
Increase i | \n\t\t\t0 | \n\t\t\t[1, 0, 0] | \n\t\t
Increase i | \n\t\t\t1 | \n\t\t\t[1, 2, 0] | \n\t\t
Decrease i | \n\t\t\t0 | \n\t\t\t[2, 2, 0] | \n\t\t
Increase i | \n\t\t\t1 | \n\t\t\t[2, 4, 0] | \n\t\t
Increase i | \n\t\t\t2 | \n\t\t\t[2, 4, 3] | \n\t\t
The minimum value in gameScore
is 2, and this is the maximum possible minimum among all configurations. Hence, 2 is the output.
\n
Constraints:
\n\n2 <= n == points.length <= 5 * 104
1 <= points[i] <= 106
1 <= m <= 109
Table: logs
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| log_id | int |\n| ip | varchar |\n| status_code | int |\n+-------------+---------+\nlog_id is the unique key for this table.\nEach row contains server access log information including IP address and HTTP status code.\n\n\n
Write a solution to find invalid IP addresses. An IPv4 address is invalid if it meets any of these conditions:
\n\n255
in any octet01.02.03.04
)4
octetsReturn the result table ordered by invalid_count
, ip
in descending order respectively.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nlogs table:
\n\n\n+--------+---------------+-------------+\n| log_id | ip | status_code | \n+--------+---------------+-------------+\n| 1 | 192.168.1.1 | 200 | \n| 2 | 256.1.2.3 | 404 | \n| 3 | 192.168.001.1 | 200 | \n| 4 | 192.168.1.1 | 200 | \n| 5 | 192.168.1 | 500 | \n| 6 | 256.1.2.3 | 404 | \n| 7 | 192.168.001.1 | 200 | \n+--------+---------------+-------------+\n\n\n
Output:
\n\n\n+---------------+--------------+\n| ip | invalid_count|\n+---------------+--------------+\n| 256.1.2.3 | 2 |\n| 192.168.001.1 | 2 |\n| 192.168.1 | 1 |\n+---------------+--------------+\n\n\n
Explanation:
\n\nThe output table is ordered by invalid_count, ip in descending order respectively.
\nGiven an array of integers nums
and an integer k
, an element nums[i]
is considered good if it is strictly greater than the elements at indices i - k
and i + k
(if those indices exist). If neither of these indices exists, nums[i]
is still considered good.
Return the sum of all the good elements in the array.
\n\n\n
Example 1:
\n\nInput: nums = [1,3,2,1,5,4], k = 2
\n\nOutput: 12
\n\nExplanation:
\n\nThe good numbers are nums[1] = 3
, nums[4] = 5
, and nums[5] = 4
because they are strictly greater than the numbers at indices i - k
and i + k
.
Example 2:
\n\nInput: nums = [2,1], k = 1
\n\nOutput: 2
\n\nExplanation:
\n\nThe only good number is nums[0] = 2
because it is strictly greater than nums[1]
.
\n
Constraints:
\n\n2 <= nums.length <= 100
1 <= nums[i] <= 1000
1 <= k <= floor(nums.length / 2)
nums[i]
is strictly greater than nums[i - k]
and nums[i + k]
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/sum-of-good-numbers/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3763",
+ "questionFrontendId": "3453",
+ "title": "Separate Squares I",
+ "content": "You are given a 2D integer array squares
. Each squares[i] = [xi, yi, li]
represents the coordinates of the bottom-left point and the side length of a square parallel to the x-axis.
Find the minimum y-coordinate value of a horizontal line such that the total area of the squares above the line equals the total area of the squares below the line.
\n\nAnswers within 10-5
of the actual answer will be accepted.
Note: Squares may overlap. Overlapping areas should be counted multiple times.
\n\n\n
Example 1:
\n\nInput: squares = [[0,0,1],[2,2,1]]
\n\nOutput: 1.00000
\n\nExplanation:
\n\nAny horizontal line between y = 1
and y = 2
will have 1 square unit above it and 1 square unit below it. The lowest option is 1.
Example 2:
\n\nInput: squares = [[0,0,2],[1,1,1]]
\n\nOutput: 1.16667
\n\nExplanation:
\n\nThe areas are:
\n\n7/6 * 2 (Red) + 1/6 (Blue) = 15/6 = 2.5
.5/6 * 2 (Red) + 5/6 (Blue) = 15/6 = 2.5
.Since the areas above and below the line are equal, the output is 7/6 = 1.16667
.
\n
Constraints:
\n\n1 <= squares.length <= 5 * 104
squares[i] = [xi, yi, li]
squares[i].length == 3
0 <= xi, yi <= 109
1 <= li <= 109
1012
.You are given a 2D integer array squares
. Each squares[i] = [xi, yi, li]
represents the coordinates of the bottom-left point and the side length of a square parallel to the x-axis.
Find the minimum y-coordinate value of a horizontal line such that the total area covered by squares above the line equals the total area covered by squares below the line.
\n\nAnswers within 10-5
of the actual answer will be accepted.
Note: Squares may overlap. Overlapping areas should be counted only once in this version.
\n\n\n
Example 1:
\n\nInput: squares = [[0,0,1],[2,2,1]]
\n\nOutput: 1.00000
\n\nExplanation:
\n\nAny horizontal line between y = 1
and y = 2
results in an equal split, with 1 square unit above and 1 square unit below. The minimum y-value is 1.
Example 2:
\n\nInput: squares = [[0,0,2],[1,1,1]]
\n\nOutput: 1.00000
\n\nExplanation:
\n\nSince the blue square overlaps with the red square, it will not be counted again. Thus, the line y = 1
splits the squares into two equal parts.
\n
Constraints:
\n\n1 <= squares.length <= 5 * 104
squares[i] = [xi, yi, li]
squares[i].length == 3
0 <= xi, yi <= 109
1 <= li <= 109
1015
.You are given a string s
and a pattern string p
, where p
contains exactly two '*'
characters.
The '*'
in p
matches any sequence of zero or more characters.
Return the length of the shortest substring in s
that matches p
. If there is no such substring, return -1.
\n
Example 1:
\n\nInput: s = "abaacbaecebce", p = "ba*c*ce"
\n\nOutput: 8
\n\nExplanation:
\n\nThe shortest matching substring of p
in s
is "baecebce"
.
Example 2:
\n\nInput: s = "baccbaadbc", p = "cc*baa*adb"
\n\nOutput: -1
\n\nExplanation:
\n\nThere is no matching substring in s
.
Example 3:
\n\nInput: s = "a", p = "**"
\n\nOutput: 0
\n\nExplanation:
\n\nThe empty substring is the shortest matching substring.
\nExample 4:
\n\nInput: s = "madlogic", p = "*adlogi*"
\n\nOutput: 6
\n\nExplanation:
\n\nThe shortest matching substring of p
in s
is "adlogi"
.
\n
Constraints:
\n\n1 <= s.length <= 105
2 <= p.length <= 105
s
contains only lowercase English letters.p
contains only lowercase English letters and exactly two '*'
.p
can be divided into three segments.",
+ "Use the KMP algorithm to locate all occurrences of each segment in s
."
+ ],
+ "topicTags": [
+ {
+ "name": "Two Pointers"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Binary Search"
+ },
+ {
+ "name": "String Matching"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/shortest-matching-substring/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3709",
+ "questionFrontendId": "3456",
+ "title": "Find Special Substring of Length K",
+ "content": "You are given a string s
and an integer k
.
Determine if there exists a substring of length exactly k
in s
that satisfies the following conditions:
"aaa"
or "bbb"
).Return true
if such a substring exists. Otherwise, return false
.
\n
Example 1:
\n\nInput: s = "aaabaaa", k = 3
\n\nOutput: true
\n\nExplanation:
\n\nThe substring s[4..6] == "aaa"
satisfies the conditions.
"aaa"
is 'b'
, which is different from 'a'
."aaa"
.Example 2:
\n\nInput: s = "abc", k = 2
\n\nOutput: false
\n\nExplanation:
\n\nThere is no substring of length 2 that consists of one distinct character and satisfies the conditions.
\n\n
Constraints:
\n\n1 <= k <= s.length <= 100
s
consists of lowercase English letters only.true
if there is a sequence of consecutive characters of length k
"
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-special-substring-of-length-k/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3779",
+ "questionFrontendId": "3457",
+ "title": "Eat Pizzas!",
+ "content": "You are given an integer array pizzas
of size n
, where pizzas[i]
represents the weight of the ith
pizza. Every day, you eat exactly 4 pizzas. Due to your incredible metabolism, when you eat pizzas of weights W
, X
, Y
, and Z
, where W <= X <= Y <= Z
, you gain the weight of only 1 pizza!
Z
.Y
.Find the maximum total weight you can gain by eating all pizzas optimally.
\n\nNote: It is guaranteed that n
is a multiple of 4, and each pizza can be eaten only once.
\n
Example 1:
\n\nInput: pizzas = [1,2,3,4,5,6,7,8]
\n\nOutput: 14
\n\nExplanation:
\n\n[1, 2, 4, 7] = [2, 3, 5, 8]
. You gain a weight of 8.[0, 3, 5, 6] = [1, 4, 6, 7]
. You gain a weight of 6.The total weight gained after eating all the pizzas is 8 + 6 = 14
.
Example 2:
\n\nInput: pizzas = [2,1,1,1,1,1,1,1]
\n\nOutput: 3
\n\nExplanation:
\n\n[4, 5, 6, 0] = [1, 1, 1, 2]
. You gain a weight of 2.[1, 2, 3, 7] = [1, 1, 1, 1]
. You gain a weight of 1.The total weight gained after eating all the pizzas is 2 + 1 = 3.
\n
Constraints:
\n\n4 <= n == pizzas.length <= 2 * 105
1 <= pizzas[i] <= 105
n
is a multiple of 4.Given a string s
of length n
and an integer k
, determine whether it is possible to select k
disjoint special substrings.
A special substring is a substring where:
\n\ns
.Note that all k
substrings must be disjoint, meaning they cannot overlap.
Return true
if it is possible to select k
such disjoint special substrings; otherwise, return false
.
\n
Example 1:
\n\nInput: s = "abcdbaefab", k = 2
\n\nOutput: true
\n\nExplanation:
\n\n"cd"
and "ef"
."cd"
contains the characters 'c'
and 'd'
, which do not appear elsewhere in s
."ef"
contains the characters 'e'
and 'f'
, which do not appear elsewhere in s
.Example 2:
\n\nInput: s = "cdefdc", k = 3
\n\nOutput: false
\n\nExplanation:
\n\nThere can be at most 2 disjoint special substrings: "e"
and "f"
. Since k = 3
, the output is false
.
Example 3:
\n\nInput: s = "abeabe", k = 0
\n\nOutput: true
\n\n
Constraints:
\n\n2 <= n == s.length <= 5 * 104
0 <= k <= 26
s
consists only of lowercase English letters.k
disjoint intervals."
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Sorting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/select-k-disjoint-special-substrings/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3733",
+ "questionFrontendId": "3459",
+ "title": "Length of Longest V-Shaped Diagonal Segment",
+ "content": "You are given a 2D integer matrix grid
of size n x m
, where each element is either 0
, 1
, or 2
.
A V-shaped diagonal segment is defined as:
\n\n1
.2, 0, 2, 0, ...
.Return the length of the longest V-shaped diagonal segment. If no valid segment exists, return 0.
\n\n\n
Example 1:
\n\nInput: grid = [[2,2,1,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest V-shaped diagonal segment has a length of 5 and follows these coordinates: (0,2) → (1,3) → (2,4)
, takes a 90-degree clockwise turn at (2,4)
, and continues as (3,3) → (4,2)
.
Example 2:
\n\nInput: grid = [[2,2,2,2,2],[2,0,2,2,0],[2,0,1,1,0],[1,0,2,2,2],[2,0,0,2,2]]
\n\nOutput: 4
\n\nExplanation:
\n\nThe longest V-shaped diagonal segment has a length of 4 and follows these coordinates: (2,3) → (3,2)
, takes a 90-degree clockwise turn at (3,2)
, and continues as (2,1) → (1,0)
.
Example 3:
\n\nInput: grid = [[1,2,2,2,2],[2,2,2,2,0],[2,0,0,0,0],[0,0,2,2,2],[2,0,0,2,0]]
\n\nOutput: 5
\n\nExplanation:
\n\nThe longest V-shaped diagonal segment has a length of 5 and follows these coordinates: (0,0) → (1,1) → (2,2) → (3,3) → (4,4)
.
Example 4:
\n\nInput: grid = [[1]]
\n\nOutput: 1
\n\nExplanation:
\n\nThe longest V-shaped diagonal segment has a length of 1 and follows these coordinates: (0,0)
.
\n
Constraints:
\n\nn == grid.length
m == grid[i].length
1 <= n, m <= 500
grid[i][j]
is either 0
, 1
or 2
.(row, col, currentDirection, hasMadeTurnYet)
. Track the current position, direction of traversal, and whether a turn has already been made, and take transitions accordingly to find the longest V-shaped diagonal segment."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Memoization"
+ },
+ {
+ "name": "Matrix"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/length-of-longest-v-shaped-diagonal-segment/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3796",
+ "questionFrontendId": "3460",
+ "title": "Longest Common Prefix After at Most One Removal",
+ "content": null,
+ "likes": 5,
+ "dislikes": 1,
+ "stats": "{\"totalAccepted\": \"689\", \"totalSubmission\": \"1K\", \"totalAcceptedRaw\": 689, \"totalSubmissionRaw\": 1016, \"acRate\": \"67.8%\"}",
+ "similarQuestions": "[{\"title\": \"Longest Common Prefix\", \"titleSlug\": \"longest-common-prefix\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "Maintain pointers to the beginning of both strings and remove the first position where they differ in s
(if any)."
+ ],
+ "topicTags": [
+ {
+ "name": "Two Pointers"
+ },
+ {
+ "name": "String"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/longest-common-prefix-after-at-most-one-removal/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3768",
+ "questionFrontendId": "3461",
+ "title": "Check If Digits Are Equal in String After Operations I",
+ "content": "You are given a string s
consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:
s
, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.s
with the sequence of newly calculated digits, maintaining the order in which they are computed.Return true
if the final two digits in s
are the same; otherwise, return false
.
\n
Example 1:
\n\nInput: s = "3902"
\n\nOutput: true
\n\nExplanation:
\n\ns = "3902"
(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2
(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9
(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2
s
becomes "292"
(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1
(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1
s
becomes "11"
"11"
are the same, the output is true
.Example 2:
\n\nInput: s = "34789"
\n\nOutput: false
\n\nExplanation:
\n\ns = "34789"
.s = "7157"
.s = "862"
.s = "48"
.'4' != '8'
, the output is false
.\n
Constraints:
\n\n3 <= s.length <= 100
s
consists of only digits.You are given a 2D integer matrix grid
of size n x m
, an integer array limits
of length n
, and an integer k
. The task is to find the maximum sum of at most k
elements from the matrix grid
such that:
The number of elements taken from the ith
row of grid
does not exceed limits[i]
.
Return the maximum sum.
\n\n\n
Example 1:
\n\nInput: grid = [[1,2],[3,4]], limits = [1,2], k = 2
\n\nOutput: 7
\n\nExplanation:
\n\n4 + 3 = 7
.Example 2:
\n\nInput: grid = [[5,3,7],[8,2,6]], limits = [2,2], k = 3
\n\nOutput: 21
\n\nExplanation:
\n\n7 + 8 + 6 = 21
.\n
Constraints:
\n\nn == grid.length == limits.length
m == grid[i].length
1 <= n, m <= 500
0 <= grid[i][j] <= 105
0 <= limits[i] <= m
0 <= k <= min(n * m, sum(limits))
limits[i]
elements.",
+ "Use a max-heap to efficiently pick the largest k
elements across all rows."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Heap (Priority Queue)"
+ },
+ {
+ "name": "Matrix"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-sum-with-at-most-k-elements/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3774",
+ "questionFrontendId": "3463",
+ "title": "Check If Digits Are Equal in String After Operations II",
+ "content": "You are given a string s
consisting of digits. Perform the following operation repeatedly until the string has exactly two digits:
s
, starting from the first digit, calculate a new digit as the sum of the two digits modulo 10.s
with the sequence of newly calculated digits, maintaining the order in which they are computed.Return true
if the final two digits in s
are the same; otherwise, return false
.
\n
Example 1:
\n\nInput: s = "3902"
\n\nOutput: true
\n\nExplanation:
\n\ns = "3902"
(s[0] + s[1]) % 10 = (3 + 9) % 10 = 2
(s[1] + s[2]) % 10 = (9 + 0) % 10 = 9
(s[2] + s[3]) % 10 = (0 + 2) % 10 = 2
s
becomes "292"
(s[0] + s[1]) % 10 = (2 + 9) % 10 = 1
(s[1] + s[2]) % 10 = (9 + 2) % 10 = 1
s
becomes "11"
"11"
are the same, the output is true
.Example 2:
\n\nInput: s = "34789"
\n\nOutput: false
\n\nExplanation:
\n\ns = "34789"
.s = "7157"
.s = "862"
.s = "48"
.'4' != '8'
, the output is false
.\n
Constraints:
\n\n3 <= s.length <= 105
s
consists of only digits.nCr
and use Pascal's triangle values here?",
+ "nCr mod 10
can be uniquely determined from nCr mod 2
and nCr mod 5
.",
+ "Use Lucas's theorem."
+ ],
+ "topicTags": [
+ {
+ "name": "Math"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Combinatorics"
+ },
+ {
+ "name": "Number Theory"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/check-if-digits-are-equal-in-string-after-operations-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3781",
+ "questionFrontendId": "3464",
+ "title": "Maximize the Distance Between Points on a Square",
+ "content": "You are given an integer side
, representing the edge length of a square with corners at (0, 0)
, (0, side)
, (side, 0)
, and (side, side)
on a Cartesian plane.
You are also given a positive integer k
and a 2D integer array points
, where points[i] = [xi, yi]
represents the coordinate of a point lying on the boundary of the square.
You need to select k
elements among points
such that the minimum Manhattan distance between any two points is maximized.
Return the maximum possible minimum Manhattan distance between the selected k
points.
The Manhattan Distance between two cells (xi, yi)
and (xj, yj)
is |xi - xj| + |yi - yj|
.
\n
Example 1:
\n\nInput: side = 2, points = [[0,2],[2,0],[2,2],[0,0]], k = 4
\n\nOutput: 2
\n\nExplanation:
\n\nSelect all four points.
\nExample 2:
\n\nInput: side = 2, points = [[0,0],[1,2],[2,0],[2,2],[2,1]], k = 4
\n\nOutput: 1
\n\nExplanation:
\n\nSelect the points (0, 0)
, (2, 0)
, (2, 2)
, and (2, 1)
.
Example 3:
\n\nInput: side = 2, points = [[0,0],[0,1],[0,2],[1,2],[2,0],[2,2],[2,1]], k = 5
\n\nOutput: 1
\n\nExplanation:
\n\nSelect the points (0, 0)
, (0, 1)
, (0, 2)
, (1, 2)
, and (2, 2)
.
\n
Constraints:
\n\n1 <= side <= 109
4 <= points.length <= min(4 * side, 15 * 103)
points[i] == [xi, yi]
points[i]
lies on the boundary of the square.points[i]
are unique.4 <= k <= min(25, points.length)
x
.",
+ "During the binary search, for each coordinate, find the immediate next coordinate with distance >= x
.",
+ "Greedily select up to k
coordinates."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Binary Search"
+ },
+ {
+ "name": "Greedy"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-the-distance-between-points-on-a-square/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3803",
+ "questionFrontendId": "3465",
+ "title": "Find Products with Valid Serial Numbers",
+ "content": "Table: products
\n+--------------+------------+\n| Column Name | Type |\n+--------------+------------+\n| product_id | int |\n| product_name | varchar |\n| description | varchar |\n+--------------+------------+\n(product_id) is the unique key for this table.\nEach row in the table represents a product with its unique ID, name, and description.\n\n\n
Write a solution to find all products whose description contains a valid serial number pattern. A valid serial number follows these rules:
\n\n4
digits.4
digits.Return the result table ordered by product_id
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nproducts table:
\n\n\n+------------+--------------+------------------------------------------------------+\n| product_id | product_name | description |\n+------------+--------------+------------------------------------------------------+\n| 1 | Widget A | This is a sample product with SN1234-5678 |\n| 2 | Widget B | A product with serial SN9876-1234 in the description |\n| 3 | Widget C | Product SN1234-56789 is available now |\n| 4 | Widget D | No serial number here |\n| 5 | Widget E | Check out SN4321-8765 in this description |\n+------------+--------------+------------------------------------------------------+\n\n\n
Output:
\n\n\n+------------+--------------+------------------------------------------------------+\n| product_id | product_name | description |\n+------------+--------------+------------------------------------------------------+\n| 1 | Widget A | This is a sample product with SN1234-5678 |\n| 2 | Widget B | A product with serial SN9876-1234 in the description |\n| 5 | Widget E | Check out SN4321-8765 in this description |\n+------------+--------------+------------------------------------------------------+\n\n\n
Explanation:
\n\nThe result table is ordered by product_id in ascending order.
\ndp[i][lane][rem]
= the maximum number of coins you can obtain when you are at mile i
in the given lane
with rem
switches remaining."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-coin-collection/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3778",
+ "questionFrontendId": "3467",
+ "title": "Transform Array by Parity",
+ "content": "You are given an integer array nums
. Transform nums
by performing the following operations in the exact order specified:
Return the resulting array after performing these operations.
\n\n\n
Example 1:
\n\nInput: nums = [4,3,2,1]
\n\nOutput: [0,0,1,1]
\n\nExplanation:
\n\nnums = [0, 1, 0, 1]
.nums
in non-descending order, nums = [0, 0, 1, 1]
.Example 2:
\n\nInput: nums = [1,5,1,4,2]
\n\nOutput: [0,0,1,1,1]
\n\nExplanation:
\n\nnums = [1, 1, 1, 0, 0]
.nums
in non-descending order, nums = [0, 0, 1, 1, 1]
.\n
Constraints:
\n\n1 <= nums.length <= 100
1 <= nums[i] <= 1000
x
be the number of even numbers, and y
be the number of odd numbers. Output 0
x
times, followed by 1
y
times."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Counting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/transform-array-by-parity/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3785",
+ "questionFrontendId": "3468",
+ "title": "Find the Number of Copy Arrays",
+ "content": "You are given an array original
of length n
and a 2D array bounds
of length n x 2
, where bounds[i] = [ui, vi]
.
You need to find the number of possible arrays copy
of length n
such that:
(copy[i] - copy[i - 1]) == (original[i] - original[i - 1])
for 1 <= i <= n - 1
.ui <= copy[i] <= vi
for 0 <= i <= n - 1
.Return the number of such arrays.
\n\n\n
Example 1:
\n\nInput: original = [1,2,3,4], bounds = [[1,2],[2,3],[3,4],[4,5]]
\n\nOutput: 2
\n\nExplanation:
\n\nThe possible arrays are:
\n\n[1, 2, 3, 4]
[2, 3, 4, 5]
Example 2:
\n\nInput: original = [1,2,3,4], bounds = [[1,10],[2,9],[3,8],[4,7]]
\n\nOutput: 4
\n\nExplanation:
\n\nThe possible arrays are:
\n\n[1, 2, 3, 4]
[2, 3, 4, 5]
[3, 4, 5, 6]
[4, 5, 6, 7]
Example 3:
\n\nInput: original = [1,2,1,2], bounds = [[1,1],[2,3],[3,3],[2,3]]
\n\nOutput: 0
\n\nExplanation:
\n\nNo array is possible.
\n\n
Constraints:
\n\n2 <= n == original.length <= 105
1 <= original[i] <= 109
bounds.length == n
bounds[i].length == 2
1 <= bounds[i][0] <= bounds[i][1] <= 109
copy[0]
uniquely determines all other values.",
+ "Possible values for copy[0]
are in [u[0], v[0]]
.",
+ "From left to right, compute valid ranges for each index by intersecting bounds with the previous range.",
+ "The answer is the size of the valid range for the last index."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-the-number-of-copy-arrays/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3776",
+ "questionFrontendId": "3469",
+ "title": "Find Minimum Cost to Remove Array Elements",
+ "content": "You are given an integer array nums
. Your task is to remove all elements from the array by performing one of the following operations at each step until nums
is empty:
nums
and remove them. The cost of this operation is the maximum of the two elements removed.nums
, remove all the remaining elements in a single operation. The cost of this operation is the maximum of the remaining elements.Return the minimum cost required to remove all the elements.
\n\n\n
Example 1:
\n\nInput: nums = [6,2,8,4]
\n\nOutput: 12
\n\nExplanation:
\n\nInitially, nums = [6, 2, 8, 4]
.
nums[0] = 6
and nums[2] = 8
with a cost of max(6, 8) = 8
. Now, nums = [2, 4]
.max(2, 4) = 4
.The cost to remove all elements is 8 + 4 = 12
. This is the minimum cost to remove all elements in nums
. Hence, the output is 12.
Example 2:
\n\nInput: nums = [2,1,3,3]
\n\nOutput: 5
\n\nExplanation:
\n\nInitially, nums = [2, 1, 3, 3]
.
nums[0] = 2
and nums[1] = 1
with a cost of max(2, 1) = 2
. Now, nums = [3, 3]
.max(3, 3) = 3
.The cost to remove all elements is 2 + 3 = 5
. This is the minimum cost to remove all elements in nums
. Hence, the output is 5.
\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 106
dp[i][j]
, where i
represents the last remaining element and j
represents the starting index of the current prefix."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-minimum-cost-to-remove-array-elements/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3783",
+ "questionFrontendId": "3470",
+ "title": "Permutations IV",
+ "content": "Given two integers, n
and k
, an alternating permutation is a permutation of the first n
positive integers such that no two adjacent elements are both odd or both even.
Return the k-th alternating permutation sorted in lexicographical order. If there are fewer than k
valid alternating permutations, return an empty list.
\n
Example 1:
\n\nInput: n = 4, k = 6
\n\nOutput: [3,4,1,2]
\n\nExplanation:
\n\nThe lexicographically-sorted alternating permutations of [1, 2, 3, 4]
are:
[1, 2, 3, 4]
[1, 4, 3, 2]
[2, 1, 4, 3]
[2, 3, 4, 1]
[3, 2, 1, 4]
[3, 4, 1, 2]
← 6th permutation[4, 1, 2, 3]
[4, 3, 2, 1]
Since k = 6
, we return [3, 4, 1, 2]
.
Example 2:
\n\nInput: n = 3, k = 2
\n\nOutput: [3,2,1]
\n\nExplanation:
\n\nThe lexicographically-sorted alternating permutations of [1, 2, 3]
are:
[1, 2, 3]
[3, 2, 1]
← 2nd permutationSince k = 2
, we return [3, 2, 1]
.
Example 3:
\n\nInput: n = 2, k = 3
\n\nOutput: []
\n\nExplanation:
\n\nThe lexicographically-sorted alternating permutations of [1, 2]
are:
[1, 2]
[2, 1]
There are only 2 alternating permutations, but k = 3
, which is out of range. Thus, we return an empty list []
.
\n
Constraints:
\n\n1 <= n <= 100
1 <= k <= 1015
n
is odd, the first number must be odd.",
+ "If n
is even, the first number can be either odd or even.",
+ "From smallest to largest, place each number and subtract the number of permutations from k
.",
+ "The number of permutations can be calculated using factorials."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Combinatorics"
+ },
+ {
+ "name": "Enumeration"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/permutations-iv/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3705",
+ "questionFrontendId": "3471",
+ "title": "Find the Largest Almost Missing Integer",
+ "content": "You are given an integer array nums
and an integer k
.
An integer x
is almost missing from nums
if x
appears in exactly one subarray of size k
within nums
.
Return the largest almost missing integer from nums
. If no such integer exists, return -1
.
\n
Example 1:
\n\nInput: nums = [3,9,2,1,7], k = 3
\n\nOutput: 7
\n\nExplanation:
\n\n[9, 2, 1]
and [2, 1, 7]
.[3, 9, 2]
, [9, 2, 1]
, [2, 1, 7]
.[3, 9, 2]
.[2, 1, 7]
.[3, 9, 2]
, and [9, 2, 1]
.We return 7 since it is the largest integer that appears in exactly one subarray of size k
.
Example 2:
\n\nInput: nums = [3,9,7,2,1,7], k = 4
\n\nOutput: 3
\n\nExplanation:
\n\n[9, 7, 2, 1]
, [7, 2, 1, 7]
.[3, 9, 7, 2]
, [9, 7, 2, 1]
, [7, 2, 1, 7]
.[3, 9, 7, 2]
.[3, 9, 7, 2]
, [9, 7, 2, 1]
, [7, 2, 1, 7]
.[3, 9, 7, 2]
, [9, 7, 2, 1]
.We return 3 since it is the largest and only integer that appears in exactly one subarray of size k
.
Example 3:
\n\nInput: nums = [0,0], k = 1
\n\nOutput: -1
\n\nExplanation:
\n\nThere is no integer that appears in only one subarray of size 1.
\n\n
Constraints:
\n\n1 <= nums.length <= 50
0 <= nums[i] <= 50
1 <= k <= nums.length
k = 1
, k = n
, and 1 < k < n
",
+ "If k = 1
, return the largest element that occurs exactly once in nums
",
+ "If k = n
, return the largest element in nums
",
+ "If 1 < k < n
, all elements different from nums[0]
and nums[n - 1]
will occur in more than one subarray of size k
. Hence, the answer is the largest of nums[0]
and nums[n - 1]
if they both occur exactly once in the array. If one of them occurs more than once, return the other. If both of them occur more than once, return -1."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-the-largest-almost-missing-integer/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3786",
+ "questionFrontendId": "3472",
+ "title": "Longest Palindromic Subsequence After at Most K Operations",
+ "content": "You are given a string s
and an integer k
.
In one operation, you can replace the character at any position with the next or previous letter in the alphabet (wrapping around so that 'a'
is after 'z'
). For example, replacing 'a'
with the next letter results in 'b'
, and replacing 'a'
with the previous letter results in 'z'
. Similarly, replacing 'z'
with the next letter results in 'a'
, and replacing 'z'
with the previous letter results in 'y'
.
Return the length of the longest palindromic subsequence of s
that can be obtained after performing at most k
operations.
\n
Example 1:
\n\nInput: s = "abced", k = 2
\n\nOutput: 3
\n\nExplanation:
\n\ns[1]
with the next letter, and s
becomes "acced"
.s[4]
with the previous letter, and s
becomes "accec"
.The subsequence "ccc"
forms a palindrome of length 3, which is the maximum.
Example 2:
\n\nInput: s = "aaazzz", k = 4
\n\nOutput: 6
\n\nExplanation:
\n\ns[0]
with the previous letter, and s
becomes "zaazzz"
.s[4]
with the next letter, and s
becomes "zaazaz"
.s[3]
with the next letter, and s
becomes "zaaaaz"
.The entire string forms a palindrome of length 6.
\n\n
Constraints:
\n\n1 <= s.length <= 200
1 <= k <= 200
s
consists of only lowercase English letters.dp[i][j][k]
is the length of the longest palindromic subsequence in substring [i..j]
with cost at most k
.",
+ "dp[i][j][k] = max(dp[i + 1][j][k], dp[i][j - 1][k], dp[i + 1][j - 1][k - dist(s[i], s[j])] + 2)
, where dist(x, y)
is the minimum cyclic distance between x
and y
."
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/longest-palindromic-subsequence-after-at-most-k-operations/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3722",
+ "questionFrontendId": "3473",
+ "title": "Sum of K Subarrays With Length at Least M",
+ "content": "You are given an integer array nums
and two integers, k
and m
.
Return the maximum sum of k
non-overlapping subarrays of nums
, where each subarray has a length of at least m
.
\n
Example 1:
\n\nInput: nums = [1,2,-1,3,3,4], k = 2, m = 2
\n\nOutput: 13
\n\nExplanation:
\n\nThe optimal choice is:
\n\nnums[3..5]
with sum 3 + 3 + 4 = 10
(length is 3 >= m
).nums[0..1]
with sum 1 + 2 = 3
(length is 2 >= m
).The total sum is 10 + 3 = 13
.
Example 2:
\n\nInput: nums = [-10,3,-1,-2], k = 4, m = 1
\n\nOutput: -10
\n\nExplanation:
\n\nThe optimal choice is choosing each element as a subarray. The output is (-10) + 3 + (-1) + (-2) = -10
.
\n
Constraints:
\n\n1 <= nums.length <= 2000
-104 <= nums[i] <= 104
1 <= k <= floor(nums.length / m)
1 <= m <= 3
dp[i][j]
be the maximum sum with i
subarrays for the first j
elements"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/sum-of-k-subarrays-with-length-at-least-m/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3770",
+ "questionFrontendId": "3474",
+ "title": "Lexicographically Smallest Generated String",
+ "content": "You are given two strings, str1
and str2
, of lengths n
and m
, respectively.
A string word
of length n + m - 1
is defined to be generated by str1
and str2
if it satisfies the following conditions for each index 0 <= i <= n - 1
:
str1[i] == 'T'
, the substring of word
with size m
starting at index i
is equal to str2
, i.e., word[i..(i + m - 1)] == str2
.str1[i] == 'F'
, the substring of word
with size m
starting at index i
is not equal to str2
, i.e., word[i..(i + m - 1)] != str2
.Return the lexicographically smallest possible string that can be generated by str1
and str2
. If no string can be generated, return an empty string ""
.
\n
Example 1:
\n\nInput: str1 = "TFTF", str2 = "ab"
\n\nOutput: "ababa"
\n\nExplanation:
\n\n"ababa"
Index | \n\t\t\tT/F | \n\t\t\tSubstring of length m | \n\t\t
---|---|---|
0 | \n\t\t\t'T' | \n\t\t\t"ab" | \n\t\t
1 | \n\t\t\t'F' | \n\t\t\t"ba" | \n\t\t
2 | \n\t\t\t'T' | \n\t\t\t"ab" | \n\t\t
3 | \n\t\t\t'F' | \n\t\t\t"ba" | \n\t\t
The strings "ababa"
and "ababb"
can be generated by str1
and str2
.
Return "ababa"
since it is the lexicographically smaller string.
Example 2:
\n\nInput: str1 = "TFTF", str2 = "abc"
\n\nOutput: ""
\n\nExplanation:
\n\nNo string that satisfies the conditions can be generated.
\nExample 3:
\n\nInput: str1 = "F", str2 = "d"
\n\nOutput: "a"
\n\n
Constraints:
\n\n1 <= n == str1.length <= 104
1 <= m == str2.length <= 500
str1
consists only of 'T'
or 'F'
.str2
consists only of lowercase English characters.['a', 'b']
.",
+ "Can you think of a greedy approach?"
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "String Matching"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/lexicographically-smallest-generated-string/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3816",
+ "questionFrontendId": "3475",
+ "title": "DNA Pattern Recognition ",
+ "content": "Table: Samples
\n+----------------+---------+\n| Column Name | Type | \n+----------------+---------+\n| sample_id | int |\n| dna_sequence | varchar |\n| species | varchar |\n+----------------+---------+\nsample_id is the unique key for this table.\nEach row contains a DNA sequence represented as a string of characters (A, T, G, C) and the species it was collected from.\n\n\n
Biologists are studying basic patterns in DNA sequences. Write a solution to identify sample_id
with the following patterns:
3
consecutive G (like GGG or GGGG)Return the result table ordered by sample_id in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nSamples table:
\n\n\n+-----------+------------------+-----------+\n| sample_id | dna_sequence | species |\n+-----------+------------------+-----------+\n| 1 | ATGCTAGCTAGCTAA | Human |\n| 2 | GGGTCAATCATC | Human |\n| 3 | ATATATCGTAGCTA | Human |\n| 4 | ATGGGGTCATCATAA | Mouse |\n| 5 | TCAGTCAGTCAG | Mouse |\n| 6 | ATATCGCGCTAG | Zebrafish |\n| 7 | CGTATGCGTCGTA | Zebrafish |\n+-----------+------------------+-----------+\n\n\n
Output:
\n\n\n+-----------+------------------+-------------+-------------+------------+------------+------------+\n| sample_id | dna_sequence | species | has_start | has_stop | has_atat | has_ggg |\n+-----------+------------------+-------------+-------------+------------+------------+------------+\n| 1 | ATGCTAGCTAGCTAA | Human | 1 | 1 | 0 | 0 |\n| 2 | GGGTCAATCATC | Human | 0 | 0 | 0 | 1 |\n| 3 | ATATATCGTAGCTA | Human | 0 | 0 | 1 | 0 |\n| 4 | ATGGGGTCATCATAA | Mouse | 1 | 1 | 0 | 1 |\n| 5 | TCAGTCAGTCAG | Mouse | 0 | 0 | 0 | 0 |\n| 6 | ATATCGCGCTAG | Zebrafish | 0 | 1 | 1 | 0 |\n| 7 | CGTATGCGTCGTA | Zebrafish | 0 | 0 | 0 | 0 |\n+-----------+------------------+-------------+-------------+------------+------------+------------+\n\n\n
Explanation:
\n\nNote:
\n\ntasks[i][0]
",
+ "For each worker, assign the highest profit task from the hashmap that matches their exact skill requirement",
+ "Assign the task with the maximum profit among the unassigned tasks to the extra worker"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Heap (Priority Queue)"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-profit-from-task-assignment/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3790",
+ "questionFrontendId": "3477",
+ "title": "Fruits Into Baskets II",
+ "content": "You are given two arrays of integers, fruits
and baskets
, each of length n
, where fruits[i]
represents the quantity of the ith
type of fruit, and baskets[j]
represents the capacity of the jth
basket.
From left to right, place the fruits according to these rules:
\n\nReturn the number of fruit types that remain unplaced after all possible allocations are made.
\n\n\n
Example 1:
\n\nInput: fruits = [4,2,5], baskets = [3,5,4]
\n\nOutput: 1
\n\nExplanation:
\n\nfruits[0] = 4
is placed in baskets[1] = 5
.fruits[1] = 2
is placed in baskets[0] = 3
.fruits[2] = 5
cannot be placed in baskets[2] = 4
.Since one fruit type remains unplaced, we return 1.
\nExample 2:
\n\nInput: fruits = [3,6,1], baskets = [6,4,7]
\n\nOutput: 0
\n\nExplanation:
\n\nfruits[0] = 3
is placed in baskets[0] = 6
.fruits[1] = 6
cannot be placed in baskets[1] = 4
(insufficient capacity) but can be placed in the next available basket, baskets[2] = 7
.fruits[2] = 1
is placed in baskets[1] = 4
.Since all fruits are successfully placed, we return 0.
\n\n
Constraints:
\n\nn == fruits.length == baskets.length
1 <= n <= 100
1 <= fruits[i], baskets[i] <= 1000
You are given two integer arrays, nums1
and nums2
, both of length n
, along with a positive integer k
.
For each index i
from 0
to n - 1
, perform the following:
j
where nums1[j]
is less than nums1[i]
.k
values of nums2[j]
at these indices to maximize the total sum.Return an array answer
of size n
, where answer[i]
represents the result for the corresponding index i
.
\n
Example 1:
\n\nInput: nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2
\n\nOutput: [80,30,0,80,50]
\n\nExplanation:
\n\ni = 0
: Select the 2 largest values from nums2
at indices [1, 2, 4]
where nums1[j] < nums1[0]
, resulting in 50 + 30 = 80
.i = 1
: Select the 2 largest values from nums2
at index [2]
where nums1[j] < nums1[1]
, resulting in 30.i = 2
: No indices satisfy nums1[j] < nums1[2]
, resulting in 0.i = 3
: Select the 2 largest values from nums2
at indices [0, 1, 2, 4]
where nums1[j] < nums1[3]
, resulting in 50 + 30 = 80
.i = 4
: Select the 2 largest values from nums2
at indices [1, 2]
where nums1[j] < nums1[4]
, resulting in 30 + 20 = 50
.Example 2:
\n\nInput: nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1
\n\nOutput: [0,0,0,0]
\n\nExplanation:
\n\nSince all elements in nums1
are equal, no indices satisfy the condition nums1[j] < nums1[i]
for any i
, resulting in 0 for all positions.
\n
Constraints:
\n\nn == nums1.length == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 106
1 <= k <= n
nums1
and its corresponding nums2
values together based on nums1
.",
+ "Use a max heap to track the top k
values of nums2
as you process each element in the sorted order."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Heap (Priority Queue)"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/choose-k-elements-with-maximum-sum/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3791",
+ "questionFrontendId": "3479",
+ "title": "Fruits Into Baskets III",
+ "content": "You are given two arrays of integers, fruits
and baskets
, each of length n
, where fruits[i]
represents the quantity of the ith
type of fruit, and baskets[j]
represents the capacity of the jth
basket.
From left to right, place the fruits according to these rules:
\n\nReturn the number of fruit types that remain unplaced after all possible allocations are made.
\n\n\n
Example 1:
\n\nInput: fruits = [4,2,5], baskets = [3,5,4]
\n\nOutput: 1
\n\nExplanation:
\n\nfruits[0] = 4
is placed in baskets[1] = 5
.fruits[1] = 2
is placed in baskets[0] = 3
.fruits[2] = 5
cannot be placed in baskets[2] = 4
.Since one fruit type remains unplaced, we return 1.
\nExample 2:
\n\nInput: fruits = [3,6,1], baskets = [6,4,7]
\n\nOutput: 0
\n\nExplanation:
\n\nfruits[0] = 3
is placed in baskets[0] = 6
.fruits[1] = 6
cannot be placed in baskets[1] = 4
(insufficient capacity) but can be placed in the next available basket, baskets[2] = 7
.fruits[2] = 1
is placed in baskets[1] = 4
.Since all fruits are successfully placed, we return 0.
\n\n
Constraints:
\n\nn == fruits.length == baskets.length
1 <= n <= 105
1 <= fruits[i], baskets[i] <= 109
(basket[i], i)
in the array.",
+ "For each fruit from left to right, use binary search to find the first index in the sorted array such that basket[i] >= fruit
.",
+ "Use a segment tree to maintain the smallest original indices where basket[i] >= fruit
.",
+ "When a valid index is found, set the corresponding point to infinity to mark it as used."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Binary Search"
+ },
+ {
+ "name": "Segment Tree"
+ },
+ {
+ "name": "Ordered Set"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/fruits-into-baskets-iii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3789",
+ "questionFrontendId": "3480",
+ "title": "Maximize Subarrays After Removing One Conflicting Pair",
+ "content": "You are given an integer n
which represents an array nums
containing the numbers from 1 to n
in order. Additionally, you are given a 2D array conflictingPairs
, where conflictingPairs[i] = [a, b]
indicates that a
and b
form a conflicting pair.
Remove exactly one element from conflictingPairs
. Afterward, count the number of non-empty subarrays of nums
which do not contain both a
and b
for any remaining conflicting pair [a, b]
.
Return the maximum number of subarrays possible after removing exactly one conflicting pair.
\n\n\n
Example 1:
\n\nInput: n = 4, conflictingPairs = [[2,3],[1,4]]
\n\nOutput: 9
\n\nExplanation:
\n\n[2, 3]
from conflictingPairs
. Now, conflictingPairs = [[1, 4]]
.nums
where [1, 4]
do not appear together. They are [1]
, [2]
, [3]
, [4]
, [1, 2]
, [2, 3]
, [3, 4]
, [1, 2, 3]
and [2, 3, 4]
.conflictingPairs
is 9.Example 2:
\n\nInput: n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]
\n\nOutput: 12
\n\nExplanation:
\n\n[1, 2]
from conflictingPairs
. Now, conflictingPairs = [[2, 5], [3, 5]]
.nums
where [2, 5]
and [3, 5]
do not appear together.conflictingPairs
is 12.\n
Constraints:
\n\n2 <= n <= 105
1 <= conflictingPairs.length <= 2 * n
conflictingPairs[i].length == 2
1 <= conflictingPairs[i][j] <= n
conflictingPairs[i][0] != conflictingPairs[i][1]
f[i]
(where i = 1, 2, 3, ..., n
) be the end index of the longest valid subarray (without any conflicting pair) starting at index i
.",
+ "The answer is: sigma(f[i] - i + 1) for i in [1..n]
, which simplifies to: sigma(f[i]) - n * (n + 1) / 2 + n
.",
+ "Focus on maintaining f[i]
.",
+ "If we have a conflicting pair (x, y)
with x < y
: 1. Sort the conflicting pairs by y
values in non-increasing order. 2. Update each prefix of the f
array accordingly.",
+ "Use a segment tree or another suitable data structure to maintain the range update and sum query efficiently."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Segment Tree"
+ },
+ {
+ "name": "Enumeration"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-subarrays-after-removing-one-conflicting-pair/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3825",
+ "questionFrontendId": "3481",
+ "title": "Apply Substitutions",
+ "content": null,
+ "likes": 35,
+ "dislikes": 4,
+ "stats": "{\"totalAccepted\": \"7K\", \"totalSubmission\": \"8.9K\", \"totalAcceptedRaw\": 7018, \"totalSubmissionRaw\": 8933, \"acRate\": \"78.6%\"}",
+ "similarQuestions": "[{\"title\": \"Evaluate the Bracket Pairs of a String\", \"titleSlug\": \"evaluate-the-bracket-pairs-of-a-string\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "Build a dependency graph where each key is a node, and add an edge from key X
to key Y
if the replacement value for Y
contains the placeholder %X%
. Then perform a topological sort to determine a valid order for substitution.",
+ "Process the keys in the topologically sorted order by replacing placeholders in each replacement value with its fully expanded value. Finally, substitute the placeholders in the text using these computed values."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Depth-First Search"
+ },
+ {
+ "name": "Breadth-First Search"
+ },
+ {
+ "name": "Graph"
+ },
+ {
+ "name": "Topological Sort"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/apply-substitutions/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3828",
+ "questionFrontendId": "3482",
+ "title": "Analyze Organization Hierarchy",
+ "content": "Table: Employees
\n+----------------+---------+\n| Column Name | Type | \n+----------------+---------+\n| employee_id | int |\n| employee_name | varchar |\n| manager_id | int |\n| salary | int |\n| department | varchar |\n+----------------+----------+\nemployee_id is the unique key for this table.\nEach row contains information about an employee, including their ID, name, their manager's ID, salary, and department.\nmanager_id is null for the top-level manager (CEO).\n\n\n
Write a solution to analyze the organizational hierarchy and answer the following:
\n\n1
, employees reporting directly to the CEO are level 2
, and so on).Return the result table ordered by the result ordered by level in ascending order, then by budget in descending order, and finally by employee_name in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nEmployees table:
\n\n\n+-------------+---------------+------------+--------+-------------+\n| employee_id | employee_name | manager_id | salary | department |\n+-------------+---------------+------------+--------+-------------+\n| 1 | Alice | null | 12000 | Executive |\n| 2 | Bob | 1 | 10000 | Sales |\n| 3 | Charlie | 1 | 10000 | Engineering |\n| 4 | David | 2 | 7500 | Sales |\n| 5 | Eva | 2 | 7500 | Sales |\n| 6 | Frank | 3 | 9000 | Engineering |\n| 7 | Grace | 3 | 8500 | Engineering |\n| 8 | Hank | 4 | 6000 | Sales |\n| 9 | Ivy | 6 | 7000 | Engineering |\n| 10 | Judy | 6 | 7000 | Engineering |\n+-------------+---------------+------------+--------+-------------+\n\n\n
Output:
\n\n\n+-------------+---------------+-------+-----------+--------+\n| employee_id | employee_name | level | team_size | budget |\n+-------------+---------------+-------+-----------+--------+\n| 1 | Alice | 1 | 9 | 84500 |\n| 3 | Charlie | 2 | 4 | 41500 |\n| 2 | Bob | 2 | 3 | 31000 |\n| 6 | Frank | 3 | 2 | 23000 |\n| 4 | David | 3 | 1 | 13500 |\n| 7 | Grace | 3 | 0 | 8500 |\n| 5 | Eva | 3 | 0 | 7500 |\n| 9 | Ivy | 4 | 0 | 7000 |\n| 10 | Judy | 4 | 0 | 7000 |\n| 8 | Hank | 4 | 0 | 6000 |\n+-------------+---------------+-------+-----------+--------+\n\n\n
Explanation:
\n\nNote:
\n\nYou are given an array of digits called digits
. Your task is to determine the number of distinct three-digit even numbers that can be formed using these digits.
Note: Each copy of a digit can only be used once per number, and there may not be leading zeros.
\n\n\n
Example 1:
\n\nInput: digits = [1,2,3,4]
\n\nOutput: 12
\n\nExplanation: The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.
\nExample 2:
\n\nInput: digits = [0,2,2]
\n\nOutput: 2
\n\nExplanation: The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.
\nExample 3:
\n\nInput: digits = [6,6,6]
\n\nOutput: 1
\n\nExplanation: Only 666 can be formed.
\nExample 4:
\n\nInput: digits = [1,3,5]
\n\nOutput: 0
\n\nExplanation: No even 3-digit numbers can be formed.
\n\n
Constraints:
\n\n3 <= digits.length <= 10
0 <= digits[i] <= 9
A spreadsheet is a grid with 26 columns (labeled from 'A'
to 'Z'
) and a given number of rows
. Each cell in the spreadsheet can hold an integer value between 0 and 105.
Implement the Spreadsheet
class:
Spreadsheet(int rows)
Initializes a spreadsheet with 26 columns (labeled 'A'
to 'Z'
) and the specified number of rows. All cells are initially set to 0.void setCell(String cell, int value)
Sets the value of the specified cell
. The cell reference is provided in the format "AX"
(e.g., "A1"
, "B10"
), where the letter represents the column (from 'A'
to 'Z'
) and the number represents a 1-indexed row.void resetCell(String cell)
Resets the specified cell to 0.int getValue(String formula)
Evaluates a formula of the form "=X+Y"
, where X
and Y
are either cell references or non-negative integers, and returns the computed sum.Note: If getValue
references a cell that has not been explicitly set using setCell
, its value is considered 0.
\n
Example 1:
\n\nInput:
\n["Spreadsheet", "getValue", "setCell", "getValue", "setCell", "getValue", "resetCell", "getValue"]
\n[[3], ["=5+7"], ["A1", 10], ["=A1+6"], ["B2", 15], ["=A1+B2"], ["A1"], ["=A1+B2"]]
Output:
\n[null, 12, null, 16, null, 25, null, 15]
Explanation
\nSpreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns\n
Constraints:
\n\n1 <= rows <= 103
0 <= value <= 105
"=X+Y"
, where X
and Y
are either valid cell references or non-negative integers with values less than or equal to 105
.'A'
to 'Z'
followed by a row number between 1
and rows
.104
calls will be made in total to setCell
, resetCell
, and getValue
.\"A1\"
) and the value is the integer stored in the cell.",
+ "For setCell
, simply assign the given value to the specified cell in the hashmap.",
+ "For resetCell
, set the value of the specified cell to 0
in the hashmap.",
+ "For getValue
, find the values of the operands from the hashmap and return their sum."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Design"
+ },
+ {
+ "name": "Matrix"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/design-spreadsheet/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3784",
+ "questionFrontendId": "3485",
+ "title": "Longest Common Prefix of K Strings After Removal",
+ "content": "You are given an array of strings words
and an integer k
.
For each index i
in the range [0, words.length - 1]
, find the length of the longest common prefix among any k
strings (selected at distinct indices) from the remaining array after removing the ith
element.
Return an array answer
, where answer[i]
is the answer for ith
element. If removing the ith
element leaves the array with fewer than k
strings, answer[i]
is 0.
\n
Example 1:
\n\nInput: words = ["jump","run","run","jump","run"], k = 2
\n\nOutput: [3,4,4,3,4]
\n\nExplanation:
\n\n"jump"
):\n\n\twords
becomes: ["run", "run", "jump", "run"]
. "run"
occurs 3 times. Choosing any two gives the longest common prefix "run"
(length 3)."run"
):\n\twords
becomes: ["jump", "run", "jump", "run"]
. "jump"
occurs twice. Choosing these two gives the longest common prefix "jump"
(length 4)."run"
):\n\twords
becomes: ["jump", "run", "jump", "run"]
. "jump"
occurs twice. Choosing these two gives the longest common prefix "jump"
(length 4)."jump"
):\n\twords
becomes: ["jump", "run", "run", "run"]
. "run"
occurs 3 times. Choosing any two gives the longest common prefix "run"
(length 3).words
becomes: ["jump", "run", "run", "jump"]
. "jump"
occurs twice. Choosing these two gives the longest common prefix "jump"
(length 4).Example 2:
\n\nInput: words = ["dog","racer","car"], k = 2
\n\nOutput: [0,0,0]
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= k <= words.length <= 105
1 <= words[i].length <= 104
words[i]
consists of lowercase English letters.words[i].length
is smaller than or equal 105
.arr[i]
, remove it from the trie and update the counts.",
+ "During evaluation, find the innermost node with at least k
paths ending there.",
+ "Use a multiset or similar structure to handle updates efficiently."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Trie"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/longest-common-prefix-of-k-strings-after-removal/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3798",
+ "questionFrontendId": "3486",
+ "title": "Longest Special Path II",
+ "content": "You are given an undirected tree rooted at node 0
, with n
nodes numbered from 0
to n - 1
. This is represented by a 2D array edges
of length n - 1
, where edges[i] = [ui, vi, lengthi]
indicates an edge between nodes ui
and vi
with length lengthi
. You are also given an integer array nums
, where nums[i]
represents the value at node i
.
A special path is defined as a downward path from an ancestor node to a descendant node in which all node values are distinct, except for at most one value that may appear twice.
\n\nReturn an array result
of size 2, where result[0]
is the length of the longest special path, and result[1]
is the minimum number of nodes in all possible longest special paths.
\n
Example 1:
\n\nInput: edges = [[0,1,1],[1,2,3],[1,3,1],[2,4,6],[4,7,2],[3,5,2],[3,6,5],[6,8,3]], nums = [1,1,0,3,1,2,1,1,0]
\n\nOutput: [9,3]
\n\nExplanation:
\n\nIn the image below, nodes are colored by their corresponding values in nums
.
The longest special paths are 1 -> 2 -> 4
and 1 -> 3 -> 6 -> 8
, both having a length of 9. The minimum number of nodes across all longest special paths is 3.
Example 2:
\n\nInput: edges = [[1,0,3],[0,2,4],[0,3,5]], nums = [1,1,0,2]
\n\nOutput: [5,2]
\n\nExplanation:
\n\nThe longest path is 0 -> 3
consisting of 2 nodes with a length of 5.
\n
Constraints:
\n\n2 <= n <= 5 * 104
edges.length == n - 1
edges[i].length == 3
0 <= ui, vi < n
1 <= lengthi <= 103
nums.length == n
0 <= nums[i] <= 5 * 104
edges
represents a valid tree.You are given an integer array nums
.
You are allowed to delete any number of elements from nums
without making it empty. After performing the deletions, select a subarray of nums
such that:
Return the maximum sum of such a subarray.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,4,5]
\n\nOutput: 15
\n\nExplanation:
\n\nSelect the entire array without deleting any element to obtain the maximum sum.
\nExample 2:
\n\nInput: nums = [1,1,0,1,1]
\n\nOutput: 1
\n\nExplanation:
\n\nDelete the element nums[0] == 1
, nums[1] == 1
, nums[2] == 0
, and nums[3] == 1
. Select the entire array [1]
to obtain the maximum sum.
Example 3:
\n\nInput: nums = [1,2,-1,-2,1,0,-1]
\n\nOutput: 3
\n\nExplanation:
\n\nDelete the elements nums[2] == -1
and nums[3] == -2
, and select the subarray [2, 1]
from [1, 2, 1, 0, -1]
to obtain the maximum sum.
\n
Constraints:
\n\n1 <= nums.length <= 100
-100 <= nums[i] <= 100
You are given a circular array nums
and an array queries
.
For each query i
, you have to find the following:
queries[i]
and any other index j
in the circular array, where nums[j] == nums[queries[i]]
. If no such index exists, the answer for that query should be -1.Return an array answer
of the same size as queries
, where answer[i]
represents the result for query i
.
\n
Example 1:
\n\nInput: nums = [1,3,1,4,1,3,2], queries = [0,3,5]
\n\nOutput: [2,-1,3]
\n\nExplanation:
\n\nqueries[0] = 0
is nums[0] = 1
. The nearest index with the same value is 2, and the distance between them is 2.queries[1] = 3
is nums[3] = 4
. No other index contains 4, so the result is -1.queries[2] = 5
is nums[5] = 3
. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: 5 -> 6 -> 0 -> 1
).Example 2:
\n\nInput: nums = [1,2,3,4], queries = [0,1,2,3]
\n\nOutput: [-1,-1,-1,-1]
\n\nExplanation:
\n\nEach value in nums
is unique, so no index shares the same value as the queried element. This results in -1 for all queries.
\n
Constraints:
\n\n1 <= queries.length <= nums.length <= 105
1 <= nums[i] <= 106
0 <= queries[i] < nums.length
You are given an integer array nums
of length n
and a 2D array queries
, where queries[i] = [li, ri, vali]
.
Each queries[i]
represents the following action on nums
:
[li, ri]
from nums
.vali
.A Zero Array is an array with all its elements equal to 0.
\n\nReturn the minimum possible non-negative value of k
, such that after processing the first k
queries in sequence, nums
becomes a Zero Array. If no such k
exists, return -1.
\n
Example 1:
\n\nInput: nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]]
\n\nOutput: 2
\n\nExplanation:
\n\n[0, 2]
by 1.[1, 0, 1]
.[0, 2]
by 1.[0, 0, 0]
, which is a Zero Array. Therefore, the minimum value of k
is 2.Example 2:
\n\nInput: nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]]
\n\nOutput: -1
\n\nExplanation:
\n\nIt is impossible to make nums a Zero Array even after all the queries.
\nExample 3:
\n\nInput: nums = [1,2,3,2,1], queries = [[0,1,1],[1,2,1],[2,3,2],[3,4,1],[4,4,1]]
\n\nOutput: 4
\n\nExplanation:
\n\n[0, 1]
by 1
.[0, 1, 3, 2, 1]
.[1, 2]
by 1.[0, 0, 2, 2, 1]
.[2, 3]
by 2.[0, 0, 0, 0, 1]
.[0, 0, 0, 0, 0]
. Therefore, the minimum value of k
is 4.Example 4:
\n\nInput: nums = [1,2,3,2,6], queries = [[0,1,1],[0,2,1],[1,4,2],[4,4,4],[3,4,1],[4,4,5]]
\n\nOutput: 4
\n\n
Constraints:
\n\n1 <= nums.length <= 10
0 <= nums[i] <= 1000
1 <= queries.length <= 1000
queries[i] = [li, ri, vali]
0 <= li <= ri < nums.length
1 <= vali <= 10
nums[i]
, use DP to check whether the queries[.][2]
values (i.e., the val
values) of the queries that affect it can form a combination with a sum equal to nums[i]
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/zero-array-transformation-iv/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3801",
+ "questionFrontendId": "3490",
+ "title": "Count Beautiful Numbers",
+ "content": "You are given two positive integers, l
and r
. A positive integer is called beautiful if the product of its digits is divisible by the sum of its digits.
Return the count of beautiful numbers between l
and r
, inclusive.
\n
Example 1:
\n\nInput: l = 10, r = 20
\n\nOutput: 2
\n\nExplanation:
\n\nThe beautiful numbers in the range are 10 and 20.
\nExample 2:
\n\nInput: l = 1, r = 15
\n\nOutput: 10
\n\nExplanation:
\n\nThe beautiful numbers in the range are 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
\n\n
Constraints:
\n\n1 <= l <= r < 109
You are given a positive integer n
representing an n x n
cargo deck on a ship. Each cell on the deck can hold one container with a weight of exactly w
.
However, the total weight of all containers, if loaded onto the deck, must not exceed the ship's maximum weight capacity, maxWeight
.
Return the maximum number of containers that can be loaded onto the ship.
\n\n\n
Example 1:
\n\nInput: n = 2, w = 3, maxWeight = 15
\n\nOutput: 4
\n\nExplanation:
\n\nThe deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed maxWeight
.
Example 2:
\n\nInput: n = 3, w = 5, maxWeight = 20
\n\nOutput: 4
\n\nExplanation:
\n\nThe deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding maxWeight
is 4.
\n
Constraints:
\n\n1 <= n <= 1000
1 <= w <= 1000
1 <= maxWeight <= 109
min(n * n, maxWeight / w)
containers."
+ ],
+ "topicTags": [
+ {
+ "name": "Math"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-containers-on-a-ship/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3809",
+ "questionFrontendId": "3493",
+ "title": "Properties Graph",
+ "content": "You are given a 2D integer array properties
having dimensions n x m
and an integer k
.
Define a function intersect(a, b)
that returns the number of distinct integers common to both arrays a
and b
.
Construct an undirected graph where each index i
corresponds to properties[i]
. There is an edge between node i
and node j
if and only if intersect(properties[i], properties[j]) >= k
, where i
and j
are in the range [0, n - 1]
and i != j
.
Return the number of connected components in the resulting graph.
\n\n\n
Example 1:
\n\nInput: properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1
\n\nOutput: 3
\n\nExplanation:
\n\nThe graph formed has 3 connected components:
\n\nExample 2:
\n\nInput: properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2
\n\nOutput: 1
\n\nExplanation:
\n\nThe graph formed has 1 connected component:
\n\nExample 3:
\n\nInput: properties = [[1,1],[1,1]], k = 2
\n\nOutput: 2
\n\nExplanation:
\n\nintersect(properties[0], properties[1]) = 1
, which is less than k
. This means there is no edge between properties[0]
and properties[1]
in the graph.
\n
Constraints:
\n\n1 <= n == properties.length <= 100
1 <= m == properties[i].length <= 100
1 <= properties[i][j] <= 100
1 <= k <= m
len(set(a) & set(b))
.",
+ "For connected components, think about using DFS, BFS, or DSU."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Depth-First Search"
+ },
+ {
+ "name": "Breadth-First Search"
+ },
+ {
+ "name": "Union Find"
+ },
+ {
+ "name": "Graph"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/properties-graph/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3794",
+ "questionFrontendId": "3494",
+ "title": "Find the Minimum Amount of Time to Brew Potions",
+ "content": "You are given two integer arrays, skill
and mana
, of length n
and m
, respectively.
In a laboratory, n
wizards must brew m
potions in order. Each potion has a mana capacity mana[j]
and must pass through all the wizards sequentially to be brewed properly. The time taken by the ith
wizard on the jth
potion is timeij = skill[i] * mana[j]
.
Since the brewing process is delicate, a potion must be passed to the next wizard immediately after the current wizard completes their work. This means the timing must be synchronized so that each wizard begins working on a potion exactly when it arrives. \u200b
\n\nReturn the minimum amount of time required for the potions to be brewed properly.
\n\n\n
Example 1:
\n\nInput: skill = [1,5,2,4], mana = [5,1,4,2]
\n\nOutput: 110
\n\nExplanation:
\n\nPotion Number | \n\t\t\tStart time | \n\t\t\tWizard 0 done by | \n\t\t\tWizard 1 done by | \n\t\t\tWizard 2 done by | \n\t\t\tWizard 3 done by | \n\t\t
---|---|---|---|---|---|
0 | \n\t\t\t0 | \n\t\t\t5 | \n\t\t\t30 | \n\t\t\t40 | \n\t\t\t60 | \n\t\t
1 | \n\t\t\t52 | \n\t\t\t53 | \n\t\t\t58 | \n\t\t\t60 | \n\t\t\t64 | \n\t\t
2 | \n\t\t\t54 | \n\t\t\t58 | \n\t\t\t78 | \n\t\t\t86 | \n\t\t\t102 | \n\t\t
3 | \n\t\t\t86 | \n\t\t\t88 | \n\t\t\t98 | \n\t\t\t102 | \n\t\t\t110 | \n\t\t
As an example for why wizard 0 cannot start working on the 1st potion before time t = 52
, consider the case where the wizards started preparing the 1st potion at time t = 50
. At time t = 58
, wizard 2 is done with the 1st potion, but wizard 3 will still be working on the 0th potion till time t = 60
.
Example 2:
\n\nInput: skill = [1,1,1], mana = [1,1,1]
\n\nOutput: 5
\n\nExplanation:
\n\nt = 0
, and is completed by time t = 3
.t = 1
, and is completed by time t = 4
.t = 2
, and is completed by time t = 5
.Example 3:
\n\nInput: skill = [1,2,3,4], mana = [1,2]
\n\nOutput: 21
\n\n
Constraints:
\n\nn == skill.length
m == mana.length
1 <= n, m <= 5000
1 <= mana[i], skill[i] <= 5000
f[i]
.",
+ "Let x
be the current mana value. Starting from now = f[0]
, update now = max(now + skill[i - 1] * x, f[i])
for i in [1..n]
. Then, the final f[n - 1] = now + skill[n - 1] * x
for this potion.",
+ "Update all other f
values by f[i] = f[i + 1] - skill[i + 1] * x
for i in [0..n - 2]
(in reverse order)."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Simulation"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-the-minimum-amount-of-time-to-brew-potions/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3744",
+ "questionFrontendId": "3495",
+ "title": "Minimum Operations to Make Array Elements Zero",
+ "content": "You are given a 2D array queries
, where queries[i]
is of the form [l, r]
. Each queries[i]
defines an array of integers nums
consisting of elements ranging from l
to r
, both inclusive.
In one operation, you can:
\n\na
and b
from the array.floor(a / 4)
and floor(b / 4)
.Your task is to determine the minimum number of operations required to reduce all elements of the array to zero for each query. Return the sum of the results for all queries.
\n\n\n
Example 1:
\n\nInput: queries = [[1,2],[2,4]]
\n\nOutput: 3
\n\nExplanation:
\n\nFor queries[0]
:
nums = [1, 2]
.nums[0]
and nums[1]
. The array becomes [0, 0]
.For queries[1]
:
nums = [2, 3, 4]
.nums[0]
and nums[2]
. The array becomes [0, 3, 1]
.nums[1]
and nums[2]
. The array becomes [0, 0, 0]
.The output is 1 + 2 = 3
.
Example 2:
\n\nInput: queries = [[2,6]]
\n\nOutput: 4
\n\nExplanation:
\n\nFor queries[0]
:
nums = [2, 3, 4, 5, 6]
.nums[0]
and nums[3]
. The array becomes [0, 3, 4, 1, 6]
.nums[2]
and nums[4]
. The array becomes [0, 3, 1, 1, 1]
.nums[1]
and nums[2]
. The array becomes [0, 0, 0, 1, 1]
.nums[3]
and nums[4]
. The array becomes [0, 0, 0, 0, 0]
.The output is 4.
\n\n
Constraints:
\n\n1 <= queries.length <= 105
queries[i].length == 2
queries[i] == [l, r]
1 <= l < r <= 109
x
, the number of \"/4\"
operations to change it to 0 is floor(log4(x)) + 1
.",
+ "Always pair the 2 numbers with the maximum \"/4\"
operations needed."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Bit Manipulation"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-operations-to-make-array-elements-zero/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3839",
+ "questionFrontendId": "3496",
+ "title": "Maximize Score After Pair Deletions",
+ "content": null,
+ "likes": 9,
+ "dislikes": 2,
+ "stats": "{\"totalAccepted\": \"457\", \"totalSubmission\": \"757\", \"totalAcceptedRaw\": 457, \"totalSubmissionRaw\": 757, \"acRate\": \"60.4%\"}",
+ "similarQuestions": "[]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "The number of operations is floor((n - 1) / 2)
, so the number of remaining elements is n - 2 * floor((n - 1) / 2)
.",
+ "There will be either 1 or 2 elements remaining.",
+ "If there is 1 element remaining, let it be the minimum element.",
+ "If there are 2 elements remaining, let them be the adjacent elements with the minimum sum."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Greedy"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-score-after-pair-deletions/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3848",
+ "questionFrontendId": "3497",
+ "title": "Analyze Subscription Conversion ",
+ "content": "Table: UserActivity
\n+------------------+---------+\n| Column Name | Type | \n+------------------+---------+\n| user_id | int |\n| activity_date | date |\n| activity_type | varchar |\n| activity_duration| int |\n+------------------+---------+\n(user_id, activity_date, activity_type) is the unique key for this table.\nactivity_type is one of ('free_trial', 'paid', 'cancelled').\nactivity_duration is the number of minutes the user spent on the platform that day.\nEach row represents a user's activity on a specific date.\n\n\n
A subscription service wants to analyze user behavior patterns. The company offers a 7
-day free trial, after which users can subscribe to a paid plan or cancel. Write a solution to:
2
decimal places)2
decimal places)Return the result table ordered by user_id
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nUserActivity table:
\n\n\n+---------+---------------+---------------+-------------------+\n| user_id | activity_date | activity_type | activity_duration |\n+---------+---------------+---------------+-------------------+\n| 1 | 2023-01-01 | free_trial | 45 |\n| 1 | 2023-01-02 | free_trial | 30 |\n| 1 | 2023-01-05 | free_trial | 60 |\n| 1 | 2023-01-10 | paid | 75 |\n| 1 | 2023-01-12 | paid | 90 |\n| 1 | 2023-01-15 | paid | 65 |\n| 2 | 2023-02-01 | free_trial | 55 |\n| 2 | 2023-02-03 | free_trial | 25 |\n| 2 | 2023-02-07 | free_trial | 50 |\n| 2 | 2023-02-10 | cancelled | 0 |\n| 3 | 2023-03-05 | free_trial | 70 |\n| 3 | 2023-03-06 | free_trial | 60 |\n| 3 | 2023-03-08 | free_trial | 80 |\n| 3 | 2023-03-12 | paid | 50 |\n| 3 | 2023-03-15 | paid | 55 |\n| 3 | 2023-03-20 | paid | 85 |\n| 4 | 2023-04-01 | free_trial | 40 |\n| 4 | 2023-04-03 | free_trial | 35 |\n| 4 | 2023-04-05 | paid | 45 |\n| 4 | 2023-04-07 | cancelled | 0 |\n+---------+---------------+---------------+-------------------+\n\n\n
Output:
\n\n\n+---------+--------------------+-------------------+\n| user_id | trial_avg_duration | paid_avg_duration |\n+---------+--------------------+-------------------+\n| 1 | 45.00 | 76.67 |\n| 3 | 70.00 | 63.33 |\n| 4 | 37.50 | 45.00 |\n+---------+--------------------+-------------------+\n\n\n
Explanation:
\n\nThe result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.
\nGiven a string s
, calculate its reverse degree.
The reverse degree is calculated as follows:
\n\n'a'
= 26, 'b'
= 25, ..., 'z'
= 1) with its position in the string (1-indexed).Return the reverse degree of s
.
\n
Example 1:
\n\nInput: s = "abc"
\n\nOutput: 148
\n\nExplanation:
\n\nLetter | \n\t\t\tIndex in Reversed Alphabet | \n\t\t\tIndex in String | \n\t\t\tProduct | \n\t\t
---|---|---|---|
'a' | \n\t\t\t26 | \n\t\t\t1 | \n\t\t\t26 | \n\t\t
'b' | \n\t\t\t25 | \n\t\t\t2 | \n\t\t\t50 | \n\t\t
'c' | \n\t\t\t24 | \n\t\t\t3 | \n\t\t\t72 | \n\t\t
The reversed degree is 26 + 50 + 72 = 148
.
Example 2:
\n\nInput: s = "zaza"
\n\nOutput: 160
\n\nExplanation:
\n\nLetter | \n\t\t\tIndex in Reversed Alphabet | \n\t\t\tIndex in String | \n\t\t\tProduct | \n\t\t
---|---|---|---|
'z' | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t1 | \n\t\t
'a' | \n\t\t\t26 | \n\t\t\t2 | \n\t\t\t52 | \n\t\t
'z' | \n\t\t\t1 | \n\t\t\t3 | \n\t\t\t3 | \n\t\t
'a' | \n\t\t\t26 | \n\t\t\t4 | \n\t\t\t104 | \n\t\t
The reverse degree is 1 + 52 + 3 + 104 = 160
.
\n
Constraints:
\n\n1 <= s.length <= 1000
s
contains only lowercase English letters.You are given a binary string s
of length n
, where:
'1'
represents an active section.'0'
represents an inactive section.You can perform at most one trade to maximize the number of active sections in s
. In a trade, you:
'1'
s that is surrounded by '0'
s to all '0'
s.'0'
s that is surrounded by '1'
s to all '1'
s.Return the maximum number of active sections in s
after making the optimal trade.
Note: Treat s
as if it is augmented with a '1'
at both ends, forming t = '1' + s + '1'
. The augmented '1'
s do not contribute to the final count.
\n
Example 1:
\n\nInput: s = "01"
\n\nOutput: 1
\n\nExplanation:
\n\nBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 1.
Example 2:
\n\nInput: s = "0100"
\n\nOutput: 4
\n\nExplanation:
\n\n"0100"
→ Augmented to "101001"
."0100"
, convert "101001"
→ "100001"
→ "111111"
."1111"
. The maximum number of active sections is 4.Example 3:
\n\nInput: s = "1000100"
\n\nOutput: 7
\n\nExplanation:
\n\n"1000100"
→ Augmented to "110001001"
."000100"
, convert "110001001"
→ "110000001"
→ "111111111"
."1111111"
. The maximum number of active sections is 7.Example 4:
\n\nInput: s = "01010"
\n\nOutput: 4
\n\nExplanation:
\n\n"01010"
→ Augmented to "1010101"
."010"
, convert "1010101"
→ "1000101"
→ "1111101"
."11110"
. The maximum number of active sections is 4.\n
Constraints:
\n\n1 <= n == s.length <= 105
s[i]
is either '0'
or '1'
delta
.",
+ "Find the maximum delta
and add it to the total number of ones in the string."
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Enumeration"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-active-section-with-trade-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3765",
+ "questionFrontendId": "3500",
+ "title": "Minimum Cost to Divide Array Into Subarrays",
+ "content": "You are given two integer arrays, nums
and cost
, of the same size, and an integer k
.
You can divide nums
into subarrays. The cost of the ith
subarray consisting of elements nums[l..r]
is:
(nums[0] + nums[1] + ... + nums[r] + k * i) * (cost[l] + cost[l + 1] + ... + cost[r])
.Note that i
represents the order of the subarray: 1 for the first subarray, 2 for the second, and so on.
Return the minimum total cost possible from any valid division.
\n\n\n
Example 1:
\n\nInput: nums = [3,1,4], cost = [4,6,6], k = 1
\n\nOutput: 110
\n\nExplanation:
\nThe minimum total cost possible can be achieved by dividingnums
into subarrays [3, 1]
and [4]
.\n\n[3,1]
is (3 + 1 + 1 * 1) * (4 + 6) = 50
.[4]
is (3 + 1 + 4 + 1 * 2) * 6 = 60
.Example 2:
\n\nInput: nums = [4,8,5,1,14,2,2,12,1], cost = [7,2,8,4,2,2,1,1,2], k = 7
\n\nOutput: 985
\n\nExplanation:
\nThe minimum total cost possible can be achieved by dividingnums
into subarrays [4, 8, 5, 1]
, [14, 2, 2]
, and [12, 1]
.\n\n[4, 8, 5, 1]
is (4 + 8 + 5 + 1 + 7 * 1) * (7 + 2 + 8 + 4) = 525
.[14, 2, 2]
is (4 + 8 + 5 + 1 + 14 + 2 + 2 + 7 * 2) * (2 + 2 + 1) = 250
.[12, 1]
is (4 + 8 + 5 + 1 + 14 + 2 + 2 + 12 + 1 + 7 * 3) * (1 + 2) = 210
.\n
Constraints:
\n\n1 <= nums.length <= 1000
cost.length == nums.length
1 <= nums[i], cost[i] <= 1000
1 <= k <= 1000
dp[i]
is the minimum cost to split the array suffix starting at i
.",
+ "Observe that no matter how many subarrays we have, if we have the first subarray on the left, the total cost of the previous subarrays increases by k * total_cost_of_the_subarray
. This is because when we increase i
to (i + 1)
, the cost increase is just the suffix sum of the cost array."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-cost-to-divide-array-into-subarrays/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3804",
+ "questionFrontendId": "3501",
+ "title": "Maximize Active Section with Trade II",
+ "content": "You are given a binary string s
of length n
, where:
'1'
represents an active section.'0'
represents an inactive section.You can perform at most one trade to maximize the number of active sections in s
. In a trade, you:
'1'
s that is surrounded by '0'
s to all '0'
s.'0'
s that is surrounded by '1'
s to all '1'
s.Additionally, you are given a 2D array queries
, where queries[i] = [li, ri]
represents a substring s[li...ri]
.
For each query, determine the maximum possible number of active sections in s
after making the optimal trade on the substring s[li...ri]
.
Return an array answer
, where answer[i]
is the result for queries[i]
.
Note
\n\ns[li...ri]
as if it is augmented with a '1'
at both ends, forming t = '1' + s[li...ri] + '1'
. The augmented '1'
s do not contribute to the final count.\n
Example 1:
\n\nInput: s = "01", queries = [[0,1]]
\n\nOutput: [1]
\n\nExplanation:
\n\nBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 1.
Example 2:
\n\nInput: s = "0100", queries = [[0,3],[0,2],[1,3],[2,3]]
\n\nOutput: [4,3,1,1]
\n\nExplanation:
\n\nQuery [0, 3]
→ Substring "0100"
→ Augmented to "101001"
\n\tChoose "0100"
, convert "0100"
→ "0000"
→ "1111"
.
\n\tThe final string without augmentation is "1111"
. The maximum number of active sections is 4.
Query [0, 2]
→ Substring "010"
→ Augmented to "10101"
\n\tChoose "010"
, convert "010"
→ "000"
→ "111"
.
\n\tThe final string without augmentation is "1110"
. The maximum number of active sections is 3.
Query [1, 3]
→ Substring "100"
→ Augmented to "11001"
\n\tBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 1.
Query [2, 3]
→ Substring "00"
→ Augmented to "1001"
\n\tBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 1.
Example 3:
\n\nInput: s = "1000100", queries = [[1,5],[0,6],[0,4]]
\n\nOutput: [6,7,2]
\n\nExplanation:
\n\nQuery [1, 5]
→ Substring "00010"
→ Augmented to "1000101"
\n\tChoose "00010"
, convert "00010"
→ "00000"
→ "11111"
.
\n\tThe final string without augmentation is "1111110"
. The maximum number of active sections is 6.
Query [0, 6]
→ Substring "1000100"
→ Augmented to "110001001"
\n\tChoose "000100"
, convert "000100"
→ "000000"
→ "111111"
.
\n\tThe final string without augmentation is "1111111"
. The maximum number of active sections is 7.
Query [0, 4]
→ Substring "10001"
→ Augmented to "1100011"
\n\tBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 2.
Example 4:
\n\nInput: s = "01010", queries = [[0,3],[1,4],[1,3]]
\n\nOutput: [4,4,2]
\n\nExplanation:
\n\nQuery [0, 3]
→ Substring "0101"
→ Augmented to "101011"
\n\tChoose "010"
, convert "010"
→ "000"
→ "111"
.
\n\tThe final string without augmentation is "11110"
. The maximum number of active sections is 4.
Query [1, 4]
→ Substring "1010"
→ Augmented to "110101"
\n\tChoose "010"
, convert "010"
→ "000"
→ "111"
.
\n\tThe final string without augmentation is "01111"
. The maximum number of active sections is 4.
Query [1, 3]
→ Substring "101"
→ Augmented to "11011"
\n\tBecause there is no block of '1'
s surrounded by '0'
s, no valid trade is possible. The maximum number of active sections is 2.
\n
Constraints:
\n\n1 <= n == s.length <= 105
1 <= queries.length <= 105
s[i]
is either '0'
or '1'
.queries[i] = [li, ri]
0 <= li <= ri < n
ans[i] = len[i - 1] + len[i + 1]
, where i
is a one-segment.",
+ "For a zero-segment, define ans[i] = 0
.",
+ "Note that all three segments (i - 1
, i
, and i + 1
) should be fully covered by the substring.",
+ "Use a segment tree to perform range maximum queries on the answer. The query to the segment tree is not straightforward since we need to ensure the zero-segments are fully covered. Handle the first and last segments separately."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Binary Search"
+ },
+ {
+ "name": "Segment Tree"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-active-section-with-trade-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3832",
+ "questionFrontendId": "3502",
+ "title": "Minimum Cost to Reach Every Position",
+ "content": "You are given an integer array cost
of size n
. You are currently at position n
(at the end of the line) in a line of n + 1
people (numbered from 0 to n
).
You wish to move forward in the line, but each person in front of you charges a specific amount to swap places. The cost to swap with person i
is given by cost[i]
.
You are allowed to swap places with people as follows:
\n\ncost[i]
to swap with them.Return an array answer
of size n
, where answer[i]
is the minimum total cost to reach each position i
in the line.
\n
Example 1:
\n\nInput: cost = [5,3,4,1,3,2]
\n\nOutput: [5,3,3,1,1,1]
\n\nExplanation:
\n\nWe can get to each position in the following way:
\n\ni = 0
. We can swap with person 0 for a cost of 5.i = 1
. We can swap with person 1 for a cost of 3.i = 2
. We can swap with person 1 for a cost of 3, then swap with person 2 for free.i = 3
. We can swap with person 3 for a cost of 1.i = 4
. We can swap with person 3 for a cost of 1, then swap with person 4 for free.i = 5
. We can swap with person 3 for a cost of 1, then swap with person 5 for free.Example 2:
\n\nInput: cost = [1,2,4,6,7]
\n\nOutput: [1,1,1,1,1]
\n\nExplanation:
\n\nWe can swap with person 0 for a cost of 1, then we will be able to reach any position i
for free.
\n
Constraints:
\n\n1 <= n == cost.length <= 100
1 <= cost[i] <= 100
You are given two strings, s
and t
.
You can create a new string by selecting a substring from s
(possibly empty) and a substring from t
(possibly empty), then concatenating them in order.
Return the length of the longest palindrome that can be formed this way.
\n\n\n
Example 1:
\n\nInput: s = "a", t = "a"
\n\nOutput: 2
\n\nExplanation:
\n\nConcatenating "a"
from s
and "a"
from t
results in "aa"
, which is a palindrome of length 2.
Example 2:
\n\nInput: s = "abc", t = "def"
\n\nOutput: 1
\n\nExplanation:
\n\nSince all characters are different, the longest palindrome is any single character, so the answer is 1.
\nExample 3:
\n\nInput: s = "b", t = "aaaa"
\n\nOutput: 4
\n\nExplanation:
\n\nSelecting "aaaa
" from t
is the longest palindrome, so the answer is 4.
Example 4:
\n\nInput: s = "abcde", t = "ecdba"
\n\nOutput: 5
\n\nExplanation:
\n\nConcatenating "abc"
from s
and "ba"
from t
results in "abcba"
, which is a palindrome of length 5.
\n
Constraints:
\n\n1 <= s.length, t.length <= 30
s
and t
consist of lowercase English letters.You are given two strings, s
and t
.
You can create a new string by selecting a substring from s
(possibly empty) and a substring from t
(possibly empty), then concatenating them in order.
Return the length of the longest palindrome that can be formed this way.
\n\n\n
Example 1:
\n\nInput: s = "a", t = "a"
\n\nOutput: 2
\n\nExplanation:
\n\nConcatenating "a"
from s
and "a"
from t
results in "aa"
, which is a palindrome of length 2.
Example 2:
\n\nInput: s = "abc", t = "def"
\n\nOutput: 1
\n\nExplanation:
\n\nSince all characters are different, the longest palindrome is any single character, so the answer is 1.
\nExample 3:
\n\nInput: s = "b", t = "aaaa"
\n\nOutput: 4
\n\nExplanation:
\n\nSelecting "aaaa
" from t
is the longest palindrome, so the answer is 4.
Example 4:
\n\nInput: s = "abcde", t = "ecdba"
\n\nOutput: 5
\n\nExplanation:
\n\nConcatenating "abc"
from s
and "ba"
from t
results in "abcba"
, which is a palindrome of length 5.
\n
Constraints:
\n\n1 <= s.length, t.length <= 1000
s
and t
consist of lowercase English letters.dp[i][j]
be the length of the longest answer if we try starting it with s[i]
and ending it with t[j]
.",
+ "For s
, preprocess the length of the longest palindrome starting at index i
as p[i]
.",
+ "For t
, preprocess the length of the longest palindrome ending at index j
as q[j]
.",
+ "If s[i] != t[j]
, then dp[i][j] = max(p[i], q[j])
.",
+ "Otherwise, dp[i][j] = max(p[i], q[j], 2 + dp[i + 1][j - 1])
."
+ ],
+ "topicTags": [
+ {
+ "name": "Two Pointers"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/longest-palindrome-after-substring-concatenation-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3717",
+ "questionFrontendId": "3505",
+ "title": "Minimum Operations to Make Elements Within K Subarrays Equal",
+ "content": "You are given an integer array nums
and two integers, x
and k
. You can perform the following operation any number of times (including zero):
nums
by 1.Return the minimum number of operations needed to have at least k
non-overlapping subarrays of size exactly x
in nums
, where all elements within each subarray are equal.
\n
Example 1:
\n\nInput: nums = [5,-2,1,3,7,3,6,4,-1], x = 3, k = 2
\n\nOutput: 8
\n\nExplanation:
\n\nnums[1]
and use 2 operations to subtract 2 from nums[3]
. The resulting array is [5, 1, 1, 1, 7, 3, 6, 4, -1]
.nums[5]
and use 2 operations to subtract 2 from nums[6]
. The resulting array is [5, 1, 1, 1, 7, 4, 4, 4, -1]
.[1, 1, 1]
(from indices 1 to 3) and [4, 4, 4]
(from indices 5 to 7) are equal. Since 8 total operations were used, 8 is the output.Example 2:
\n\nInput: nums = [9,-2,-2,-2,1,5], x = 2, k = 2
\n\nOutput: 3
\n\nExplanation:
\n\nnums[4]
. The resulting array is [9, -2, -2, -2, -2, 5]
.[-2, -2]
(from indices 1 to 2) and [-2, -2]
(from indices 3 to 4) are equal. Since 3 operations were used, 3 is the output.\n
Constraints:
\n\n2 <= nums.length <= 105
-106 <= nums[i] <= 106
2 <= x <= nums.length
1 <= k <= 15
2 <= k * x <= nums.length
Given an array nums
, you can perform the following operation any number of times:
nums
. If multiple such pairs exist, choose the leftmost one.Return the minimum number of operations needed to make the array non-decreasing.
\n\nAn array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists).
\n\n\n
Example 1:
\n\nInput: nums = [5,2,3,1]
\n\nOutput: 2
\n\nExplanation:
\n\n(3,1)
has the minimum sum of 4. After replacement, nums = [5,2,4]
.(2,4)
has the minimum sum of 6. After replacement, nums = [5,6]
.The array nums
became non-decreasing in two operations.
Example 2:
\n\nInput: nums = [1,2,2]
\n\nOutput: 0
\n\nExplanation:
\n\nThe array nums
is already sorted.
\n
Constraints:
\n\n1 <= nums.length <= 50
-1000 <= nums[i] <= 1000
Design a data structure that can efficiently manage data packets in a network router. Each data packet consists of the following attributes:
\n\nsource
: A unique identifier for the machine that generated the packet.destination
: A unique identifier for the target machine.timestamp
: The time at which the packet arrived at the router.Implement the Router
class:
Router(int memoryLimit)
: Initializes the Router object with a fixed memory limit.
memoryLimit
is the maximum number of packets the router can store at any given time.bool addPacket(int source, int destination, int timestamp)
: Adds a packet with the given attributes to the router.
source
, destination
, and timestamp
already exists in the router.true
if the packet is successfully added (i.e., it is not a duplicate); otherwise return false
.int[] forwardPacket()
: Forwards the next packet in FIFO (First In First Out) order.
[source, destination, timestamp]
.int getCount(int destination, int startTime, int endTime)
:
[startTime, endTime]
.Note that queries for addPacket
will be made in increasing order of timestamp
.
\n
Example 1:
\n\nInput:
\n["Router", "addPacket", "addPacket", "addPacket", "addPacket", "addPacket", "forwardPacket", "addPacket", "getCount"]
\n[[3], [1, 4, 90], [2, 5, 90], [1, 4, 90], [3, 5, 95], [4, 5, 105], [], [5, 2, 110], [5, 100, 110]]
Output:
\n[null, true, true, false, true, true, [2, 5, 90], true, 1]
Explanation
\nRouter router = new Router(3); // Initialize Router with memoryLimit of 3.[1, 4, 90]
is removed as number of packets exceeds memoryLimit. Return True.[2, 5, 90]
and remove it from router.[100, 110]
is [4, 5, 105]
. Return 1.Example 2:
\n\nInput:
\n["Router", "addPacket", "forwardPacket", "forwardPacket"]
\n[[2], [7, 4, 90], [], []]
Output:
\n[null, true, [7, 4, 90], []]
Explanation
\nRouter router = new Router(2); // InitializeRouter
with memoryLimit
of 2.[7, 4, 90]
.[]
.\n
Constraints:
\n\n2 <= memoryLimit <= 105
1 <= source, destination <= 2 * 105
1 <= timestamp <= 109
1 <= startTime <= endTime <= 109
105
calls will be made to addPacket
, forwardPacket
, and getCount
methods altogether.addPacket
will be made in increasing order of timestamp
.You are given an integer array nums
and two integers, k
and limit
. Your task is to find a non-empty subsequence of nums
that:
k
.limit
.Return the product of the numbers in such a subsequence. If no subsequence satisfies the requirements, return -1.
\n\nThe alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3], k = 2, limit = 10
\n\nOutput: 6
\n\nExplanation:
\n\nThe subsequences with an alternating sum of 2 are:
\n\n[1, 2, 3]
\n\n\t1 - 2 + 3 = 2
1 * 2 * 3 = 6
[2]
\n\tThe maximum product within the limit is 6.
\nExample 2:
\n\nInput: nums = [0,2,3], k = -5, limit = 12
\n\nOutput: -1
\n\nExplanation:
\n\nA subsequence with an alternating sum of exactly -5 does not exist.
\nExample 3:
\n\nInput: nums = [2,2,3,3], k = 0, limit = 9
\n\nOutput: 9
\n\nExplanation:
\n\nThe subsequences with an alternating sum of 0 are:
\n\n[2, 2]
\n\n\t2 - 2 = 0
2 * 2 = 4
[3, 3]
\n\t3 - 3 = 0
3 * 3 = 9
[2, 2, 3, 3]
\n\t2 - 2 + 3 - 3 = 0
2 * 2 * 3 * 3 = 36
The subsequence [2, 2, 3, 3]
has the greatest product with an alternating sum equal to k
, but 36 > 9
. The next greatest product is 9, which is within the limit.
\n
Constraints:
\n\n1 <= nums.length <= 150
0 <= nums[i] <= 12
-105 <= k <= 105
1 <= limit <= 5000
0
and an alternating sum of k
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-product-of-subsequences-with-an-alternating-sum-equal-to-k/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3772",
+ "questionFrontendId": "3510",
+ "title": "Minimum Pair Removal to Sort Array II",
+ "content": "Given an array nums
, you can perform the following operation any number of times:
nums
. If multiple such pairs exist, choose the leftmost one.Return the minimum number of operations needed to make the array non-decreasing.
\n\nAn array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists).
\n\n\n
Example 1:
\n\nInput: nums = [5,2,3,1]
\n\nOutput: 2
\n\nExplanation:
\n\n(3,1)
has the minimum sum of 4. After replacement, nums = [5,2,4]
.(2,4)
has the minimum sum of 6. After replacement, nums = [5,6]
.The array nums
became non-decreasing in two operations.
Example 2:
\n\nInput: nums = [1,2,2]
\n\nOutput: 0
\n\nExplanation:
\n\nThe array nums
is already sorted.
\n
Constraints:
\n\n1 <= nums.length <= 105
-109 <= nums[i] <= 109
i
. Replace the element at index i
with the maximum value. Find the selected subarray with the next smallest last index j
that does not contain index i
. Replace the element at index j
with the maximum value, and repeat this process until all non-positive subarrays are fixed."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/make-a-positive-array/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3846",
+ "questionFrontendId": "3512",
+ "title": "Minimum Operations to Make Array Sum Divisible by K",
+ "content": "You are given an integer array nums
and an integer k
. You can perform the following operation any number of times:
i
and replace nums[i]
with nums[i] - 1
.Return the minimum number of operations required to make the sum of the array divisible by k
.
\n
Example 1:
\n\nInput: nums = [3,9,7], k = 5
\n\nOutput: 4
\n\nExplanation:
\n\nnums[1] = 9
. Now, nums = [3, 5, 7]
.Example 2:
\n\nInput: nums = [4,1,3], k = 4
\n\nOutput: 0
\n\nExplanation:
\n\nExample 3:
\n\nInput: nums = [3,2], k = 6
\n\nOutput: 5
\n\nExplanation:
\n\nnums[0] = 3
and 2 operations on nums[1] = 2
. Now, nums = [0, 0]
.\n
Constraints:
\n\n1 <= nums.length <= 1000
1 <= nums[i] <= 1000
1 <= k <= 100
sum(nums) % k
"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-operations-to-make-array-sum-divisible-by-k/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3824",
+ "questionFrontendId": "3513",
+ "title": "Number of Unique XOR Triplets I",
+ "content": "You are given an integer array nums
of length n
, where nums
is a permutation of the numbers in the range [1, n]
.
A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k]
where i <= j <= k
.
Return the number of unique XOR triplet values from all possible triplets (i, j, k)
.
\n
Example 1:
\n\nInput: nums = [1,2]
\n\nOutput: 2
\n\nExplanation:
\n\nThe possible XOR triplet values are:
\n\n(0, 0, 0) → 1 XOR 1 XOR 1 = 1
(0, 0, 1) → 1 XOR 1 XOR 2 = 2
(0, 1, 1) → 1 XOR 2 XOR 2 = 1
(1, 1, 1) → 2 XOR 2 XOR 2 = 2
The unique XOR values are {1, 2}
, so the output is 2.
Example 2:
\n\nInput: nums = [3,1,2]
\n\nOutput: 4
\n\nExplanation:
\n\nThe possible XOR triplet values include:
\n\n(0, 0, 0) → 3 XOR 3 XOR 3 = 3
(0, 0, 1) → 3 XOR 3 XOR 1 = 1
(0, 0, 2) → 3 XOR 3 XOR 2 = 2
(0, 1, 2) → 3 XOR 1 XOR 2 = 0
The unique XOR values are {0, 1, 2, 3}
, so the output is 4.
\n
Constraints:
\n\n1 <= n == nums.length <= 105
1 <= nums[i] <= n
nums
is a permutation of integers from 1
to n
.n >= 3
we can obtain all numbers in [0, 2^(msb(n) + 1) - 1]
, where msb(n)
is the index of the most significant bit in n
\u2019s binary representation (i.e., the highest power of 2 less than or equal to n
). Handle the case when n <= 2
separately."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Bit Manipulation"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/number-of-unique-xor-triplets-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3820",
+ "questionFrontendId": "3514",
+ "title": "Number of Unique XOR Triplets II",
+ "content": "You are given an integer array nums
.
A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k]
where i <= j <= k
.
Return the number of unique XOR triplet values from all possible triplets (i, j, k)
.
\n
Example 1:
\n\nInput: nums = [1,3]
\n\nOutput: 2
\n\nExplanation:
\n\nThe possible XOR triplet values are:
\n\n(0, 0, 0) → 1 XOR 1 XOR 1 = 1
(0, 0, 1) → 1 XOR 1 XOR 3 = 3
(0, 1, 1) → 1 XOR 3 XOR 3 = 1
(1, 1, 1) → 3 XOR 3 XOR 3 = 3
The unique XOR values are {1, 3}
. Thus, the output is 2.
Example 2:
\n\nInput: nums = [6,7,8,9]
\n\nOutput: 4
\n\nExplanation:
\n\nThe possible XOR triplet values are {6, 7, 8, 9}
. Thus, the output is 4.
\n
Constraints:
\n\n1 <= nums.length <= 1500
1 <= nums[i] <= 1500
max_xor
.",
+ "For each index i
, consider all pairs of indices (j, k)
such that i <= j <= k
. For each such pair, compute the triplet XOR as nums[i] XOR nums[j] XOR nums[k]
.",
+ "You can optimize the calculation by precomputing or reusing intermediate XOR results. For example, after fixing an index i
, compute XORs of pairs (j, k)
in O(n2)
time instead of checking all three indices independently.",
+ "Finally, count the number of unique XOR values obtained from all triplets."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Bit Manipulation"
+ },
+ {
+ "name": "Enumeration"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/number-of-unique-xor-triplets-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3829",
+ "questionFrontendId": "3515",
+ "title": "Shortest Path in a Weighted Tree",
+ "content": "You are given an integer n
and an undirected, weighted tree rooted at node 1 with n
nodes numbered from 1 to n
. This is represented by a 2D array edges
of length n - 1
, where edges[i] = [ui, vi, wi]
indicates an undirected edge from node ui
to vi
with weight wi
.
You are also given a 2D integer array queries
of length q
, where each queries[i]
is either:
[1, u, v, w']
– Update the weight of the edge between nodes u
and v
to w'
, where (u, v)
is guaranteed to be an edge present in edges
.[2, x]
– Compute the shortest path distance from the root node 1 to node x
.Return an integer array answer
, where answer[i]
is the shortest path distance from node 1 to x
for the ith
query of [2, x]
.
\n
Example 1:
\n\nInput: n = 2, edges = [[1,2,7]], queries = [[2,2],[1,1,2,4],[2,2]]
\n\nOutput: [7,4]
\n\nExplanation:
\n\n[2,2]
: The shortest path from root node 1 to node 2 is 7.[1,1,2,4]
: The weight of edge (1,2)
changes from 7 to 4.[2,2]
: The shortest path from root node 1 to node 2 is 4.Example 2:
\n\nInput: n = 3, edges = [[1,2,2],[1,3,4]], queries = [[2,1],[2,3],[1,1,3,7],[2,2],[2,3]]
\n\nOutput: [0,4,2,7]
\n\nExplanation:
\n\n[2,1]
: The shortest path from root node 1 to node 1 is 0.[2,3]
: The shortest path from root node 1 to node 3 is 4.[1,1,3,7]
: The weight of edge (1,3)
changes from 4 to 7.[2,2]
: The shortest path from root node 1 to node 2 is 2.[2,3]
: The shortest path from root node 1 to node 3 is 7.Example 3:
\n\nInput: n = 4, edges = [[1,2,2],[2,3,1],[3,4,5]], queries = [[2,4],[2,3],[1,2,3,3],[2,2],[2,3]]
\n\nOutput: [8,3,2,5]
\n\nExplanation:
\n\n[2,4]
: The shortest path from root node 1 to node 4 consists of edges (1,2)
, (2,3)
, and (3,4)
with weights 2 + 1 + 5 = 8
.[2,3]
: The shortest path from root node 1 to node 3 consists of edges (1,2)
and (2,3)
with weights 2 + 1 = 3
.[1,2,3,3]
: The weight of edge (2,3)
changes from 1 to 3.[2,2]
: The shortest path from root node 1 to node 2 is 2.[2,3]
: The shortest path from root node 1 to node 3 consists of edges (1,2)
and (2,3)
with updated weights 2 + 3 = 5
.\n
Constraints:
\n\n1 <= n <= 105
edges.length == n - 1
edges[i] == [ui, vi, wi]
1 <= ui, vi <= n
1 <= wi <= 104
edges
represents a valid tree.1 <= queries.length == q <= 105
queries[i].length == 2
or 4
\n\tqueries[i] == [1, u, v, w']
or,queries[i] == [2, x]
1 <= u, v, x <= n
(u, v)
is always an edge from edges
.1 <= w' <= 104
u
, v
, w'
], adjust the distance for all descendants by applying a delta update to the corresponding range in the flattened array."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ },
+ {
+ "name": "Binary Indexed Tree"
+ },
+ {
+ "name": "Segment Tree"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/shortest-path-in-a-weighted-tree/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3830",
+ "questionFrontendId": "3516",
+ "title": "Find Closest Person",
+ "content": "You are given three integers x
, y
, and z
, representing the positions of three people on a number line:
x
is the position of Person 1.y
is the position of Person 2.z
is the position of Person 3, who does not move.Both Person 1 and Person 2 move toward Person 3 at the same speed.
\n\nDetermine which person reaches Person 3 first:
\n\nReturn the result accordingly.
\n\n\n
Example 1:
\n\nInput: x = 2, y = 7, z = 4
\n\nOutput: 1
\n\nExplanation:
\n\nSince Person 1 reaches Person 3 first, the output is 1.
\nExample 2:
\n\nInput: x = 2, y = 5, z = 6
\n\nOutput: 2
\n\nExplanation:
\n\nSince Person 2 reaches Person 3 first, the output is 2.
\nExample 3:
\n\nInput: x = 1, y = 5, z = 3
\n\nOutput: 0
\n\nExplanation:
\n\nSince both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.
\n\n
Constraints:
\n\n1 <= x, y, z <= 100
You are given a palindromic string s
.
Return the lexicographically smallest palindromic permutation of s
.
\n
Example 1:
\n\nInput: s = "z"
\n\nOutput: "z"
\n\nExplanation:
\n\nA string of only one character is already the lexicographically smallest palindrome.
\nExample 2:
\n\nInput: s = "babab"
\n\nOutput: "abbba"
\n\nExplanation:
\n\nRearranging "babab"
→ "abbba"
gives the smallest lexicographic palindrome.
Example 3:
\n\nInput: s = "daccad"
\n\nOutput: "acddca"
\n\nExplanation:
\n\nRearranging "daccad"
→ "acddca"
gives the smallest lexicographic palindrome.
\n
Constraints:
\n\n1 <= s.length <= 105
s
consists of lowercase English letters.s
is guaranteed to be palindromic.s
), and then the other half is its reverse to obtain the lexicographically smallest permutation."
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Counting Sort"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/smallest-palindromic-rearrangement-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3813",
+ "questionFrontendId": "3518",
+ "title": "Smallest Palindromic Rearrangement II",
+ "content": "You are given a palindromic string s
and an integer k
.
Return the k-th lexicographically smallest palindromic permutation of s
. If there are fewer than k
distinct palindromic permutations, return an empty string.
Note: Different rearrangements that yield the same palindromic string are considered identical and are counted once.
\n\n\n
Example 1:
\n\nInput: s = "abba", k = 2
\n\nOutput: "baab"
\n\nExplanation:
\n\n"abba"
are "abba"
and "baab"
."abba"
comes before "baab"
. Since k = 2
, the output is "baab"
.Example 2:
\n\nInput: s = "aa", k = 2
\n\nOutput: ""
\n\nExplanation:
\n\n"aa"
.k = 2
exceeds the number of possible rearrangements.Example 3:
\n\nInput: s = "bacab", k = 1
\n\nOutput: "abcba"
\n\nExplanation:
\n\n"bacab"
are "abcba"
and "bacab"
."abcba"
comes before "bacab"
. Since k = 1
, the output is "abcba"
.\n
Constraints:
\n\n1 <= s.length <= 104
s
consists of lowercase English letters.s
is guaranteed to be palindromic.1 <= k <= 106
floor(n / 2)
characters (the rest are determined by symmetry).",
+ "Count character frequencies and use half the counts for construction.",
+ "Incrementally choose each character (from smallest to largest) and calculate how many valid arrangements result if that character is chosen at the current index.",
+ "If the count is at least k
, fix that character; otherwise, subtract the count from k
and try the next candidate.",
+ "Use combinatorics to compute the number of permutations at each step."
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Combinatorics"
+ },
+ {
+ "name": "Counting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/smallest-palindromic-rearrangement-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3810",
+ "questionFrontendId": "3519",
+ "title": "Count Numbers with Non-Decreasing Digits ",
+ "content": "You are given two integers, l
and r
, represented as strings, and an integer b
. Return the count of integers in the inclusive range [l, r]
whose digits are in non-decreasing order when represented in base b
.
An integer is considered to have non-decreasing digits if, when read from left to right (from the most significant digit to the least significant digit), each digit is greater than or equal to the previous one.
\n\nSince the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: l = "23", r = "28", b = 8
\n\nOutput: 3
\n\nExplanation:
\n\nExample 2:
\n\nInput: l = "2", r = "7", b = 2
\n\nOutput: 2
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= l.length <= r.length <= 100
2 <= b <= 10
l
and r
consist only of digits.l
is less than or equal to the value represented by r
.l
and r
do not contain leading zeros.Table: ProductPurchases
\n+-------------+------+\n| Column Name | Type | \n+-------------+------+\n| user_id | int |\n| product_id | int |\n| quantity | int |\n+-------------+------+\n(user_id, product_id) is the unique key for this table.\nEach row represents a purchase of a product by a user in a specific quantity.\n\n\n
Table: ProductInfo
\n+-------------+---------+\n| Column Name | Type | \n+-------------+---------+\n| product_id | int |\n| category | varchar |\n| price | decimal |\n+-------------+---------+\nproduct_id is the primary key for this table.\nEach row assigns a category and price to a product.\n\n\n
Amazon wants to implement the Customers who bought this also bought... feature based on co-purchase patterns. Write a solution to :
\n\nproduct1_id
< product2_id
)A product pair is considered for recommendation if at least 3
different customers have purchased both products.
Return the result table ordered by customer_count in descending order, and in case of a tie, by product1_id
in ascending order, and then by product2_id
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nProductPurchases table:
\n\n\n+---------+------------+----------+\n| user_id | product_id | quantity |\n+---------+------------+----------+\n| 1 | 101 | 2 |\n| 1 | 102 | 1 |\n| 1 | 103 | 3 |\n| 2 | 101 | 1 |\n| 2 | 102 | 5 |\n| 2 | 104 | 1 |\n| 3 | 101 | 2 |\n| 3 | 103 | 1 |\n| 3 | 105 | 4 |\n| 4 | 101 | 1 |\n| 4 | 102 | 1 |\n| 4 | 103 | 2 |\n| 4 | 104 | 3 |\n| 5 | 102 | 2 |\n| 5 | 104 | 1 |\n+---------+------------+----------+\n\n\n
ProductInfo table:
\n\n\n+------------+-------------+-------+\n| product_id | category | price |\n+------------+-------------+-------+\n| 101 | Electronics | 100 |\n| 102 | Books | 20 |\n| 103 | Clothing | 35 |\n| 104 | Kitchen | 50 |\n| 105 | Sports | 75 |\n+------------+-------------+-------+\n\n\n
Output:
\n\n\n+-------------+-------------+-------------------+-------------------+----------------+\n| product1_id | product2_id | product1_category | product2_category | customer_count |\n+-------------+-------------+-------------------+-------------------+----------------+\n| 101 | 102 | Electronics | Books | 3 |\n| 101 | 103 | Electronics | Clothing | 3 |\n| 102 | 104 | Books | Kitchen | 3 |\n+-------------+-------------+-------------------+-------------------+----------------+\n\n\n
Explanation:
\n\nThe result is ordered by customer_count in descending order. For pairs with the same customer_count, they are ordered by product1_id and then product2_id in ascending order.
\nYou are given two arrays, instructions
and values
, both of size n
.
You need to simulate a process based on the following rules:
\n\ni = 0
with an initial score of 0.instructions[i]
is "add"
:\n\tvalues[i]
to your score.(i + 1)
.instructions[i]
is "jump"
:\n\t(i + values[i])
without modifying your score.The process ends when you either:
\n\ni < 0 or i >= n
), orReturn your score at the end of the process.
\n\n\n
Example 1:
\n\nInput: instructions = ["jump","add","add","jump","add","jump"], values = [2,1,3,1,-2,-3]
\n\nOutput: 1
\n\nExplanation:
\n\nSimulate the process starting at instruction 0:
\n\n"jump"
, move to index 0 + 2 = 2
."add"
, add values[2] = 3
to your score and move to index 3. Your score becomes 3."jump"
, move to index 3 + 1 = 4
."add"
, add values[4] = -2
to your score and move to index 5. Your score becomes 1."jump"
, move to index 5 + (-3) = 2
.Example 2:
\n\nInput: instructions = ["jump","add","add"], values = [3,1,1]
\n\nOutput: 0
\n\nExplanation:
\n\nSimulate the process starting at instruction 0:
\n\n"jump"
, move to index 0 + 3 = 3
.Example 3:
\n\nInput: instructions = ["jump"], values = [0]
\n\nOutput: 0
\n\nExplanation:
\n\nSimulate the process starting at instruction 0:
\n\n"jump"
, move to index 0 + 0 = 0
.\n
Constraints:
\n\nn == instructions.length == values.length
1 <= n <= 105
instructions[i]
is either "add"
or "jump"
.-105 <= values[i] <= 105
You are given an integer array nums
. In one operation, you can select a subarray and replace it with a single element equal to its maximum value.
Return the maximum possible size of the array after performing zero or more operations such that the resulting array is non-decreasing.
\n\n\n
Example 1:
\n\nInput: nums = [4,2,5,3,5]
\n\nOutput: 3
\n\nExplanation:
\n\nOne way to achieve the maximum size is:
\n\nnums[1..2] = [2, 5]
with 5
→ [4, 5, 3, 5]
.nums[2..3] = [3, 5]
with 5
→ [4, 5, 5]
.The final array [4, 5, 5]
is non-decreasing with size 3.
Example 2:
\n\nInput: nums = [1,2,3]
\n\nOutput: 3
\n\nExplanation:
\n\nNo operation is needed as the array [1,2,3]
is already non-decreasing.
\n
Constraints:
\n\n1 <= nums.length <= 2 * 105
1 <= nums[i] <= 2 * 105
You are given an array of positive integers nums
, and a positive integer k
.
You are allowed to perform an operation once on nums
, where in each operation you can remove any non-overlapping prefix and suffix from nums
such that nums
remains non-empty.
You need to find the x-value of nums
, which is the number of ways to perform this operation so that the product of the remaining elements leaves a remainder of x
when divided by k
.
Return an array result
of size k
where result[x]
is the x-value of nums
for 0 <= x <= k - 1
.
A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it.
\n\nA suffix of an array is a subarray that starts at any point within the array and extends to the end of the array.
\n\nNote that the prefix and suffix to be chosen for the operation can be empty.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,4,5], k = 3
\n\nOutput: [9,2,4]
\n\nExplanation:
\n\nx = 0
, the possible operations include all possible ways to remove non-overlapping prefix/suffix that do not remove nums[2] == 3
.x = 1
, the possible operations are:\n\t[2, 3, 4, 5]
. nums
becomes [1]
.[1, 2, 3]
and the suffix [5]
. nums
becomes [4]
.x = 2
, the possible operations are:\n\t[3, 4, 5]
. nums
becomes [1, 2]
.[1]
and the suffix [3, 4, 5]
. nums
becomes [2]
.[1, 2, 3]
and the empty suffix. nums
becomes [4, 5]
.[1, 2, 3, 4]
and the empty suffix. nums
becomes [5]
.Example 2:
\n\nInput: nums = [1,2,4,8,16,32], k = 4
\n\nOutput: [18,1,2,0]
\n\nExplanation:
\n\nx = 0
, the only operations that do not result in x = 0
are:\n\n\t[4, 8, 16, 32]
. nums
becomes [1, 2]
.[2, 4, 8, 16, 32]
. nums
becomes [1]
.[1]
and the suffix [4, 8, 16, 32]
. nums
becomes [2]
.x = 1
, the only possible operation is:\n\t[2, 4, 8, 16, 32]
. nums
becomes [1]
.x = 2
, the possible operations are:\n\t[4, 8, 16, 32]
. nums
becomes [1, 2]
.[1]
and the suffix [4, 8, 16, 32]
. nums
becomes [2]
.x = 3
, there is no possible way to perform the operation.Example 3:
\n\nInput: nums = [1,1,2,1,1], k = 2
\n\nOutput: [9,6]
\n\n
Constraints:
\n\n1 <= nums[i] <= 109
1 <= nums.length <= 105
1 <= k <= 5
dp[i][r]
as the count of subarrays ending at index i
whose product modulo k
equals r
.",
+ "Compute dp[i][r]
for each index i
in nums
and sum over all indices to get the final counts for each remainder."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-x-value-of-array-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3840",
+ "questionFrontendId": "3525",
+ "title": "Find X Value of Array II",
+ "content": "You are given an array of positive integers nums
and a positive integer k
. You are also given a 2D array queries
, where queries[i] = [indexi, valuei, starti, xi]
.
You are allowed to perform an operation once on nums
, where you can remove any suffix from nums
such that nums
remains non-empty.
The x-value of nums
for a given x
is defined as the number of ways to perform this operation so that the product of the remaining elements leaves a remainder of x
modulo k
.
For each query in queries
you need to determine the x-value of nums
for xi
after performing the following actions:
nums[indexi]
to valuei
. Only this step persists for the rest of the queries.nums[0..(starti - 1)]
(where nums[0..(-1)]
will be used to represent the empty prefix).Return an array result
of size queries.length
where result[i]
is the answer for the ith
query.
A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it.
\n\nA suffix of an array is a subarray that starts at any point within the array and extends to the end of the array.
\n\nNote that the prefix and suffix to be chosen for the operation can be empty.
\n\nNote that x-value has a different definition in this version.
\n\n\n
Example 1:
\n\nInput: nums = [1,2,3,4,5], k = 3, queries = [[2,2,0,2],[3,3,3,0],[0,1,0,1]]
\n\nOutput: [2,2,2]
\n\nExplanation:
\n\nnums
becomes [1, 2, 2, 4, 5]
, and the empty prefix must be removed. The possible operations are:\n\n\t[2, 4, 5]
. nums
becomes [1, 2]
.nums
becomes [1, 2, 2, 4, 5]
with a product 80, which gives remainder 2 when divided by 3.nums
becomes [1, 2, 2, 3, 5]
, and the prefix [1, 2, 2]
must be removed. The possible operations are:\n\tnums
becomes [3, 5]
.[5]
. nums
becomes [3]
.nums
becomes [1, 2, 2, 3, 5]
, and the empty prefix must be removed. The possible operations are:\n\t[2, 2, 3, 5]
. nums
becomes [1]
.[3, 5]
. nums
becomes [1, 2, 2]
.Example 2:
\n\nInput: nums = [1,2,4,8,16,32], k = 4, queries = [[0,2,0,2],[0,2,0,1]]
\n\nOutput: [1,0]
\n\nExplanation:
\n\nnums
becomes [2, 2, 4, 8, 16, 32]
. The only possible operation is:\n\n\t[2, 4, 8, 16, 32]
.nums
becomes [2, 2, 4, 8, 16, 32]
. There is no possible way to perform the operation.Example 3:
\n\nInput: nums = [1,1,2,1,1], k = 2, queries = [[2,1,0,1]]
\n\nOutput: [5]
\n\n
Constraints:
\n\n1 <= nums[i] <= 109
1 <= nums.length <= 105
1 <= k <= 5
1 <= queries.length <= 2 * 104
queries[i] == [indexi, valuei, starti, xi]
0 <= indexi <= nums.length - 1
1 <= valuei <= 109
0 <= starti <= nums.length - 1
0 <= xi <= k - 1
nums
.",
+ "In each segment tree node, store a frequency count of prefix product remainders for every x
in the range [0, k - 1].",
+ "For each query, update nums[index]
to value
, then merge the segments corresponding to nums[start..n - 1]
to compute the x-value
for xi
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Segment Tree"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-x-value-of-array-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3862",
+ "questionFrontendId": "3526",
+ "title": "Range XOR Queries with Subarray Reversals",
+ "content": null,
+ "likes": 3,
+ "dislikes": 2,
+ "stats": "{\"totalAccepted\": \"286\", \"totalSubmission\": \"444\", \"totalAcceptedRaw\": 286, \"totalSubmissionRaw\": 444, \"acRate\": \"64.4%\"}",
+ "similarQuestions": "[]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "Augment each AVL tree node with fields for subtree XOR, size, and a lazy reversal flag to efficiently update and query segments.",
+ "Use split and merge operations on the AVL tree to isolate subarrays for point updates, range XOR queries, and reversals in O(log n)
time."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Binary Tree"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/range-xor-queries-with-subarray-reversals/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3707",
+ "questionFrontendId": "3527",
+ "title": "Find the Most Common Response",
+ "content": "You are given a 2D string array responses
where each responses[i]
is an array of strings representing survey responses from the ith
day.
Return the most common response across all days after removing duplicate responses within each responses[i]
. If there is a tie, return the lexicographically smallest response.
\n
Example 1:
\n\nInput: responses = [["good","ok","good","ok"],["ok","bad","good","ok","ok"],["good"],["bad"]]
\n\nOutput: "good"
\n\nExplanation:
\n\nresponses = [["good", "ok"], ["ok", "bad", "good"], ["good"], ["bad"]]
."good"
appears 3 times, "ok"
appears 2 times, and "bad"
appears 2 times."good"
because it has the highest frequency.Example 2:
\n\nInput: responses = [["good","ok","good"],["ok","bad"],["bad","notsure"],["great","good"]]
\n\nOutput: "bad"
\n\nExplanation:
\n\nresponses = [["good", "ok"], ["ok", "bad"], ["bad", "notsure"], ["great", "good"]]
."bad"
, "good"
, and "ok"
each occur 2 times."bad"
because it is the lexicographically smallest amongst the words with the highest frequency.\n
Constraints:
\n\n1 <= responses.length <= 1000
1 <= responses[i].length <= 1000
1 <= responses[i][j].length <= 10
responses[i][j]
consists of only lowercase English lettersThere are n
types of units indexed from 0
to n - 1
. You are given a 2D integer array conversions
of length n - 1
, where conversions[i] = [sourceUniti, targetUniti, conversionFactori]
. This indicates that a single unit of type sourceUniti
is equivalent to conversionFactori
units of type targetUniti
.
Return an array baseUnitConversion
of length n
, where baseUnitConversion[i]
is the number of units of type i
equivalent to a single unit of type 0. Since the answer may be large, return each baseUnitConversion[i]
modulo 109 + 7
.
\n
Example 1:
\n\nInput: conversions = [[0,1,2],[1,2,3]]
\n\nOutput: [1,2,6]
\n\nExplanation:
\n\nconversions[0]
.conversions[0]
, then conversions[1]
.Example 2:
\n\nInput: conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]
\n\nOutput: [1,2,3,8,10,6,30,24]
\n\nExplanation:
\n\nconversions[0]
.conversions[1]
.conversions[0]
, then conversions[2]
.conversions[0]
, then conversions[3]
.conversions[1]
, then conversions[4]
.conversions[0]
, conversions[3]
, then conversions[5]
.conversions[1]
, conversions[4]
, then conversions[6]
.\n
Constraints:
\n\n2 <= n <= 105
conversions.length == n - 1
0 <= sourceUniti, targetUniti < n
1 <= conversionFactori <= 109
You are given an m x n
matrix grid
consisting of characters and a string pattern
.
A horizontal substring is a contiguous sequence of characters read from left to right. If the end of a row is reached before the substring is complete, it wraps to the first column of the next row and continues as needed. You do not wrap from the bottom row back to the top.
\n\nA vertical substring is a contiguous sequence of characters read from top to bottom. If the bottom of a column is reached before the substring is complete, it wraps to the first row of the next column and continues as needed. You do not wrap from the last column back to the first.
\n\nCount the number of cells in the matrix that satisfy the following condition:
\n\npattern
.Return the count of these cells.
\n\n\n
Example 1:
\nInput: grid = [["a","a","c","c"],["b","b","b","c"],["a","a","b","a"],["c","a","a","c"],["a","a","b","a"]], pattern = "abaca"
\n\nOutput: 1
\n\nExplanation:
\n\nThe pattern "abaca"
appears once as a horizontal substring (colored blue) and once as a vertical substring (colored red), intersecting at one cell (colored purple).
Example 2:
\nInput: grid = [["c","a","a","a"],["a","a","b","a"],["b","b","a","a"],["a","a","b","a"]], pattern = "aba"
\n\nOutput: 4
\n\nExplanation:
\n\nThe cells colored above are all part of at least one horizontal and one vertical substring matching the pattern "aba"
.
Example 3:
\n\nInput: grid = [["a"]], pattern = "a"
\n\nOutput: 1
\n\n
Constraints:
\n\nm == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
1 <= pattern.length <= m * n
grid
and pattern
consist of only lowercase English letters.You are given a Directed Acyclic Graph (DAG) with n
nodes labeled from 0
to n - 1
, represented by a 2D array edges
, where edges[i] = [ui, vi]
indicates a directed edge from node ui
to vi
. Each node has an associated score given in an array score
, where score[i]
represents the score of node i
.
You must process the nodes in a valid topological order. Each node is assigned a 1-based position in the processing order.
\n\nThe profit is calculated by summing up the product of each node's score and its position in the ordering.
\n\nReturn the maximum possible profit achievable with an optimal topological order.
\n\nA topological order of a DAG is a linear ordering of its nodes such that for every directed edge u → v
, node u
comes before v
in the ordering.
\n
Example 1:
\n\nInput: n = 2, edges = [[0,1]], score = [2,3]
\n\nOutput: 8
\n\nExplanation:
\n\nNode 1 depends on node 0, so a valid order is [0, 1]
.
Node | \n\t\t\tProcessing Order | \n\t\t\tScore | \n\t\t\tMultiplier | \n\t\t\tProfit Calculation | \n\t\t
---|---|---|---|---|
0 | \n\t\t\t1st | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\t2 × 1 = 2 | \n\t\t
1 | \n\t\t\t2nd | \n\t\t\t3 | \n\t\t\t2 | \n\t\t\t3 × 2 = 6 | \n\t\t
The maximum total profit achievable over all valid topological orders is 2 + 6 = 8
.
Example 2:
\n\nInput: n = 3, edges = [[0,1],[0,2]], score = [1,6,3]
\n\nOutput: 25
\n\nExplanation:
\n\nNodes 1 and 2 depend on node 0, so the most optimal valid order is [0, 2, 1]
.
Node | \n\t\t\tProcessing Order | \n\t\t\tScore | \n\t\t\tMultiplier | \n\t\t\tProfit Calculation | \n\t\t
---|---|---|---|---|
0 | \n\t\t\t1st | \n\t\t\t1 | \n\t\t\t1 | \n\t\t\t1 × 1 = 1 | \n\t\t
2 | \n\t\t\t2nd | \n\t\t\t3 | \n\t\t\t2 | \n\t\t\t3 × 2 = 6 | \n\t\t
1 | \n\t\t\t3rd | \n\t\t\t6 | \n\t\t\t3 | \n\t\t\t6 × 3 = 18 | \n\t\t
The maximum total profit achievable over all valid topological orders is 1 + 6 + 18 = 25
.
\n
Constraints:
\n\n1 <= n == score.length <= 22
1 <= score[i] <= 105
0 <= edges.length <= n * (n - 1) / 2
edges[i] == [ui, vi]
denotes a directed edge from ui
to vi
.0 <= ui, vi < n
ui != vi
mask
= (bits such that if a bit is set, it means the corresponding node is removed).",
+ "Try maintaining the degrees
across function calls."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Bit Manipulation"
+ },
+ {
+ "name": "Graph"
+ },
+ {
+ "name": "Topological Sort"
+ },
+ {
+ "name": "Bitmask"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-profit-from-valid-topological-order-in-dag/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3819",
+ "questionFrontendId": "3531",
+ "title": "Count Covered Buildings",
+ "content": "You are given a positive integer n
, representing an n x n
city. You are also given a 2D grid buildings
, where buildings[i] = [x, y]
denotes a unique building located at coordinates [x, y]
.
A building is covered if there is at least one building in all four directions: left, right, above, and below.
\n\nReturn the number of covered buildings.
\n\n\n
Example 1:
\n\nInput: n = 3, buildings = [[1,2],[2,2],[3,2],[2,1],[2,3]]
\n\nOutput: 1
\n\nExplanation:
\n\n[2,2]
is covered as it has at least one building:\n\n\t[1,2]
)[3,2]
)[2,1]
)[2,3]
)Example 2:
\n\nInput: n = 3, buildings = [[1,1],[1,2],[2,1],[2,2]]
\n\nOutput: 0
\n\nExplanation:
\n\nExample 3:
\n\nInput: n = 5, buildings = [[1,3],[3,2],[3,3],[3,5],[5,3]]
\n\nOutput: 1
\n\nExplanation:
\n\n[3,3]
is covered as it has at least one building:\n\n\t[1,3]
)[5,3]
)[3,2]
)[3,5]
)\n
Constraints:
\n\n2 <= n <= 105
1 <= buildings.length <= 105
buildings[i] = [x, y]
1 <= x, y <= n
buildings
are unique.You are given an integer n
representing the number of nodes in a graph, labeled from 0 to n - 1
.
You are also given an integer array nums
of length n
sorted in non-decreasing order, and an integer maxDiff
.
An undirected edge exists between nodes i
and j
if the absolute difference between nums[i]
and nums[j]
is at most maxDiff
(i.e., |nums[i] - nums[j]| <= maxDiff
).
You are also given a 2D integer array queries
. For each queries[i] = [ui, vi]
, determine whether there exists a path between nodes ui
and vi
.
Return a boolean array answer
, where answer[i]
is true
if there exists a path between ui
and vi
in the ith
query and false
otherwise.
\n
Example 1:
\n\nInput: n = 2, nums = [1,3], maxDiff = 1, queries = [[0,0],[0,1]]
\n\nOutput: [true,false]
\n\nExplanation:
\n\n[0,0]
: Node 0 has a trivial path to itself.[0,1]
: There is no edge between Node 0 and Node 1 because |nums[0] - nums[1]| = |1 - 3| = 2
, which is greater than maxDiff
.[true, false]
.Example 2:
\n\nInput: n = 4, nums = [2,5,6,8], maxDiff = 2, queries = [[0,1],[0,2],[1,3],[2,3]]
\n\nOutput: [false,false,true,true]
\n\nExplanation:
\n\nThe resulting graph is:
\n\n[0,1]
: There is no edge between Node 0 and Node 1 because |nums[0] - nums[1]| = |2 - 5| = 3
, which is greater than maxDiff
.[0,2]
: There is no edge between Node 0 and Node 2 because |nums[0] - nums[2]| = |2 - 6| = 4
, which is greater than maxDiff
.[1,3]
: There is a path between Node 1 and Node 3 through Node 2 since |nums[1] - nums[2]| = |5 - 6| = 1
and |nums[2] - nums[3]| = |6 - 8| = 2
, both of which are within maxDiff
.[2,3]
: There is an edge between Node 2 and Node 3 because |nums[2] - nums[3]| = |6 - 8| = 2
, which is equal to maxDiff
.[false, false, true, true]
.\n
Constraints:
\n\n1 <= n == nums.length <= 105
0 <= nums[i] <= 105
nums
is sorted in non-decreasing order.0 <= maxDiff <= 105
1 <= queries.length <= 105
queries[i] == [ui, vi]
0 <= ui, vi < n
You are given an array of positive integers nums
and a positive integer k
.
A permutation of nums
is said to form a divisible concatenation if, when you concatenate the decimal representations of the numbers in the order specified by the permutation, the resulting number is divisible by k
.
Return the lexicographically smallest permutation (when considered as a list of integers) that forms a divisible concatenation. If no such permutation exists, return an empty list.
\n\n\n
Example 1:
\n\nInput: nums = [3,12,45], k = 5
\n\nOutput: [3,12,45]
\n\nExplanation:
\n\nPermutation | \n\t\t\tConcatenated Value | \n\t\t\tDivisible by 5 | \n\t\t
---|---|---|
[3, 12, 45] | \n\t\t\t31245 | \n\t\t\tYes | \n\t\t
[3, 45, 12] | \n\t\t\t34512 | \n\t\t\tNo | \n\t\t
[12, 3, 45] | \n\t\t\t12345 | \n\t\t\tYes | \n\t\t
[12, 45, 3] | \n\t\t\t12453 | \n\t\t\tNo | \n\t\t
[45, 3, 12] | \n\t\t\t45312 | \n\t\t\tNo | \n\t\t
[45, 12, 3] | \n\t\t\t45123 | \n\t\t\tNo | \n\t\t
The lexicographically smallest permutation that forms a divisible concatenation is [3,12,45]
.
Example 2:
\n\nInput: nums = [10,5], k = 10
\n\nOutput: [5,10]
\n\nExplanation:
\n\nPermutation | \n\t\t\tConcatenated Value | \n\t\t\tDivisible by 10 | \n\t\t
---|---|---|
[5, 10] | \n\t\t\t510 | \n\t\t\tYes | \n\t\t
[10, 5] | \n\t\t\t105 | \n\t\t\tNo | \n\t\t
The lexicographically smallest permutation that forms a divisible concatenation is [5,10]
.
Example 3:
\n\nInput: nums = [1,2,3], k = 5
\n\nOutput: []
\n\nExplanation:
\n\nSince no permutation of nums
forms a valid divisible concatenation, return an empty list.
\n
Constraints:
\n\n1 <= nums.length <= 13
1 <= nums[i] <= 105
1 <= k <= 100
mask
and remainder
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Bit Manipulation"
+ },
+ {
+ "name": "Bitmask"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/concatenated-divisibility/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3852",
+ "questionFrontendId": "3534",
+ "title": "Path Existence Queries in a Graph II",
+ "content": "You are given an integer n
representing the number of nodes in a graph, labeled from 0 to n - 1
.
You are also given an integer array nums
of length n
and an integer maxDiff
.
An undirected edge exists between nodes i
and j
if the absolute difference between nums[i]
and nums[j]
is at most maxDiff
(i.e., |nums[i] - nums[j]| <= maxDiff
).
You are also given a 2D integer array queries
. For each queries[i] = [ui, vi]
, find the minimum distance between nodes ui
and vi
. If no path exists between the two nodes, return -1 for that query.
Return an array answer
, where answer[i]
is the result of the ith
query.
Note: The edges between the nodes are unweighted.
\n\n\n
Example 1:
\n\nInput: n = 5, nums = [1,8,3,4,2], maxDiff = 3, queries = [[0,3],[2,4]]
\n\nOutput: [1,1]
\n\nExplanation:
\n\nThe resulting graph is:
\n\nQuery | \n\t\t\tShortest Path | \n\t\t\tMinimum Distance | \n\t\t
---|---|---|
[0, 3] | \n\t\t\t0 → 3 | \n\t\t\t1 | \n\t\t
[2, 4] | \n\t\t\t2 → 4 | \n\t\t\t1 | \n\t\t
Thus, the output is [1, 1]
.
Example 2:
\n\nInput: n = 5, nums = [5,3,1,9,10], maxDiff = 2, queries = [[0,1],[0,2],[2,3],[4,3]]
\n\nOutput: [1,2,-1,1]
\n\nExplanation:
\n\nThe resulting graph is:
\n\nQuery | \n\t\t\tShortest Path | \n\t\t\tMinimum Distance | \n\t\t
---|---|---|
[0, 1] | \n\t\t\t0 → 1 | \n\t\t\t1 | \n\t\t
[0, 2] | \n\t\t\t0 → 1 → 2 | \n\t\t\t2 | \n\t\t
[2, 3] | \n\t\t\tNone | \n\t\t\t-1 | \n\t\t
[4, 3] | \n\t\t\t3 → 4 | \n\t\t\t1 | \n\t\t
Thus, the output is [1, 2, -1, 1]
.
Example 3:
\n\nInput: n = 3, nums = [3,6,1], maxDiff = 1, queries = [[0,0],[0,1],[1,2]]
\n\nOutput: [0,-1,-1]
\n\nExplanation:
\n\nThere are no edges between any two nodes because:
\n\n|nums[0] - nums[1]| = |3 - 6| = 3 > 1
|nums[0] - nums[2]| = |3 - 1| = 2 > 1
|nums[1] - nums[2]| = |6 - 1| = 5 > 1
Thus, no node can reach any other node, and the output is [0, -1, -1]
.
\n
Constraints:
\n\n1 <= n == nums.length <= 105
0 <= nums[i] <= 105
0 <= maxDiff <= 105
1 <= queries.length <= 105
queries[i] == [ui, vi]
0 <= ui, vi < n
nums[i]
.",
+ "Can we use binary jumping?",
+ "Use binary jumping with a sparse table data structure."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Binary Search"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Graph"
+ },
+ {
+ "name": "Sorting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/path-existence-queries-in-a-graph-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3752",
+ "questionFrontendId": "3535",
+ "title": "Unit Conversion II",
+ "content": null,
+ "likes": 2,
+ "dislikes": 4,
+ "stats": "{\"totalAccepted\": \"233\", \"totalSubmission\": \"332\", \"totalAcceptedRaw\": 233, \"totalSubmissionRaw\": 332, \"acRate\": \"70.2%\"}",
+ "similarQuestions": "[]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "Using a dfs, compute an array fromRoot
such that fromRoot[a]
is the number of units of type a
equivalent to a single unit of type 0.",
+ "answer[i] = fromRoot[unitAi]-1 * fromRoot[unitBi]
"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Depth-First Search"
+ },
+ {
+ "name": "Breadth-First Search"
+ },
+ {
+ "name": "Graph"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/unit-conversion-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3859",
+ "questionFrontendId": "3536",
+ "title": "Maximum Product of Two Digits",
+ "content": "You are given a positive integer n
.
Return the maximum product of any two digits in n
.
Note: You may use the same digit twice if it appears more than once in n
.
\n
Example 1:
\n\nInput: n = 31
\n\nOutput: 3
\n\nExplanation:
\n\nn
are [3, 1]
.3 * 1 = 3
.Example 2:
\n\nInput: n = 22
\n\nOutput: 4
\n\nExplanation:
\n\nn
are [2, 2]
.2 * 2 = 4
.Example 3:
\n\nInput: n = 124
\n\nOutput: 8
\n\nExplanation:
\n\nn
are [1, 2, 4]
.1 * 2 = 2
, 1 * 4 = 4
, 2 * 4 = 8
.\n
Constraints:
\n\n10 <= n <= 109
You are given a non-negative integer n
representing a 2n x 2n
grid. You must fill the grid with integers from 0 to 22n - 1
to make it special. A grid is special if it satisfies all the following conditions:
Return the special 2n x 2n
grid.
Note: Any 1x1 grid is special.
\n\n\n
Example 1:
\n\nInput: n = 0
\n\nOutput: [[0]]
\n\nExplanation:
\n\nThe only number that can be placed is 0, and there is only one possible position in the grid.
\nExample 2:
\n\nInput: n = 1
\n\nOutput: [[3,0],[2,1]]
\n\nExplanation:
\n\nThe numbers in each quadrant are:
\n\nSince 0 < 1 < 2 < 3
, this satisfies the given constraints.
Example 3:
\n\nInput: n = 2
\n\nOutput: [[15,12,3,0],[14,13,2,1],[11,8,7,4],[10,9,6,5]]
\n\nExplanation:
\n\nThe numbers in each quadrant are:
\n\nmax(3, 0, 2, 1) < min(7, 4, 6, 5)
max(7, 4, 6, 5) < min(11, 8, 10, 9)
max(11, 8, 10, 9) < min(15, 12, 14, 13)
This satisfies the first three requirements. Additionally, each quadrant is also a special grid. Thus, this is a special grid.
\n\n
Constraints:
\n\n0 <= n <= 10
You are given a straight road of length l
km, an integer n
, an integer k
, and two integer arrays, position
and time
, each of length n
.
The array position
lists the positions (in km) of signs in strictly increasing order (with position[0] = 0
and position[n - 1] = l
).
Each time[i]
represents the time (in minutes) required to travel 1 km between position[i]
and position[i + 1]
.
You must perform exactly k
merge operations. In one merge, you can choose any two adjacent signs at indices i
and i + 1
(with i > 0
and i + 1 < n
) and:
i + 1
so that its time becomes time[i] + time[i + 1]
.i
.Return the minimum total travel time (in minutes) to travel from 0 to l
after exactly k
merges.
\n
Example 1:
\n\nInput: l = 10, n = 4, k = 1, position = [0,3,8,10], time = [5,8,3,6]
\n\nOutput: 62
\n\nExplanation:
\n\nMerge the signs at indices 1 and 2. Remove the sign at index 1, and change the time at index 2 to 8 + 3 = 11
.
position
array: [0, 8, 10]
time
array: [5, 11, 6]
Segment | \n\t\t\t\tDistance (km) | \n\t\t\t\tTime per km (min) | \n\t\t\t\tSegment Travel Time (min) | \n\t\t\t
---|---|---|---|
0 → 8 | \n\t\t\t\t8 | \n\t\t\t\t5 | \n\t\t\t\t8 × 5 = 40 | \n\t\t\t
8 → 10 | \n\t\t\t\t2 | \n\t\t\t\t11 | \n\t\t\t\t2 × 11 = 22 | \n\t\t\t
40 + 22 = 62
, which is the minimum possible time after exactly 1 merge.Example 2:
\n\nInput: l = 5, n = 5, k = 1, position = [0,1,2,3,5], time = [8,3,9,3,3]
\n\nOutput: 34
\n\nExplanation:
\n\n3 + 9 = 12
.position
array: [0, 2, 3, 5]
time
array: [8, 12, 3, 3]
Segment | \n\t\t\t\tDistance (km) | \n\t\t\t\tTime per km (min) | \n\t\t\t\tSegment Travel Time (min) | \n\t\t\t
---|---|---|---|
0 → 2 | \n\t\t\t\t2 | \n\t\t\t\t8 | \n\t\t\t\t2 × 8 = 16 | \n\t\t\t
2 → 3 | \n\t\t\t\t1 | \n\t\t\t\t12 | \n\t\t\t\t1 × 12 = 12 | \n\t\t\t
3 → 5 | \n\t\t\t\t2 | \n\t\t\t\t3 | \n\t\t\t\t2 × 3 = 6 | \n\t\t\t
16 + 12 + 6 = 34
, which is the minimum possible time after exactly 1 merge.\n
Constraints:
\n\n1 <= l <= 105
2 <= n <= min(l + 1, 50)
0 <= k <= min(n - 2, 10)
position.length == n
position[0] = 0
and position[n - 1] = l
position
is sorted in strictly increasing order.time.length == n
1 <= time[i] <= 100\u200b
1 <= sum(time) <= 100
\u200b\u200b\u200b\u200b\u200b\u200bk
merges, you\u2019ll have n-k
signs left.",
+ "Define DP[i][j][s]
as the minimum travel time for positions 0..i
when i
is kept, j
deletions are done overall, and s
consecutive deletions occurred immediately before i
.",
+ "Update the DP by either merging (increment s
and j
) or not merging (reset s
) and adding the appropriate travel time."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/merge-operations-for-minimum-travel-time/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3851",
+ "questionFrontendId": "3539",
+ "title": "Find Sum of Array Product of Magical Sequences",
+ "content": "You are given two integers, m
and k
, and an integer array nums
.
seq
is called magical if:\n\nseq
has a size of m
.0 <= seq[i] < nums.length
2seq[0] + 2seq[1] + ... + 2seq[m - 1]
has k
set bits.The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m - 1]])
.
Return the sum of the array products for all valid magical sequences.
\n\nSince the answer may be large, return it modulo 109 + 7
.
A set bit refers to a bit in the binary representation of a number that has a value of 1.
\n\n\n
Example 1:
\n\nInput: m = 5, k = 5, nums = [1,10,100,10000,1000000]
\n\nOutput: 991600007
\n\nExplanation:
\n\nAll permutations of [0, 1, 2, 3, 4]
are magical sequences, each with an array product of 1013.
Example 2:
\n\nInput: m = 2, k = 2, nums = [5,4,3,2,1]
\n\nOutput: 170
\n\nExplanation:
\n\nThe magical sequences are [0, 1]
, [0, 2]
, [0, 3]
, [0, 4]
, [1, 0]
, [1, 2]
, [1, 3]
, [1, 4]
, [2, 0]
, [2, 1]
, [2, 3]
, [2, 4]
, [3, 0]
, [3, 1]
, [3, 2]
, [3, 4]
, [4, 0]
, [4, 1]
, [4, 2]
, and [4, 3]
.
Example 3:
\n\nInput: m = 1, k = 1, nums = [28]
\n\nOutput: 28
\n\nExplanation:
\n\nThe only magical sequence is [0]
.
\n
Constraints:
\n\n1 <= k <= m <= 30
1 <= nums.length <= 50
1 <= nums[i] <= 108
dp[i][j][mask]
be the state after choosing i
numbers (indices)",
+ "The partial sum S = 2^(seq[0]) + 2^(seq[1]) + ... + 2^(seq[i - 1])
has produced exactly j
set bits once you\u2019ve fully propagated any carries",
+ "The mask
represents the \"window\" of lower-order bits from S
that have not yet been fully processed (i.e. bits that might later create new set bits when additional terms are added)",
+ "Use combinatorics",
+ "How many ways are there to permute a sequence of entities where some are repetitive?"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Bit Manipulation"
+ },
+ {
+ "name": "Combinatorics"
+ },
+ {
+ "name": "Bitmask"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-sum-of-array-product-of-magical-sequences/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3880",
+ "questionFrontendId": "3540",
+ "title": "Minimum Time to Visit All Houses",
+ "content": null,
+ "likes": 5,
+ "dislikes": 2,
+ "stats": "{\"totalAccepted\": \"576\", \"totalSubmission\": \"818\", \"totalAcceptedRaw\": 576, \"totalSubmissionRaw\": 818, \"acRate\": \"70.4%\"}",
+ "similarQuestions": "[]",
+ "categoryTitle": "Algorithms",
+ "hints": [
+ "Use prefix sums to compute distances for both forward and backward movements.",
+ "For each move between adjacent houses, take the minimum distance from the two prefix-sum arrays."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": true,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-time-to-visit-all-houses/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3872",
+ "questionFrontendId": "3541",
+ "title": "Find Most Frequent Vowel and Consonant",
+ "content": "You are given a string s
consisting of lowercase English letters ('a'
to 'z'
).
Your task is to:
\n\n'a'
, 'e'
, 'i'
, 'o'
, or 'u'
) with the maximum frequency.Return the sum of the two frequencies.
\n\nNote: If multiple vowels or consonants have the same maximum frequency, you may choose any one of them. If there are no vowels or no consonants in the string, consider their frequency as 0.
\nThe frequency of a letterx
is the number of times it occurs in the string.\n\n
Example 1:
\n\nInput: s = "successes"
\n\nOutput: 6
\n\nExplanation:
\n\n'u'
(frequency 1), 'e'
(frequency 2). The maximum frequency is 2.'s'
(frequency 4), 'c'
(frequency 2). The maximum frequency is 4.2 + 4 = 6
.Example 2:
\n\nInput: s = "aeiaeia"
\n\nOutput: 3
\n\nExplanation:
\n\n'a'
(frequency 3), 'e'
( frequency 2), 'i'
(frequency 2). The maximum frequency is 3.s
. Hence, maximum consonant frequency = 0.3 + 0 = 3
.\n
Constraints:
\n\n1 <= s.length <= 100
s
consists of lowercase English letters only.You are given an array nums
of size n
, consisting of non-negative integers. Your task is to apply some (possibly zero) operations on the array so that all elements become 0.
In one operation, you can select a subarray [i, j]
(where 0 <= i <= j < n
) and set all occurrences of the minimum non-negative integer in that subarray to 0.
Return the minimum number of operations required to make all elements in the array 0.
\n\n\n
Example 1:
\n\nInput: nums = [0,2]
\n\nOutput: 1
\n\nExplanation:
\n\n[1,1]
(which is [2]
), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [0,0]
.Example 2:
\n\nInput: nums = [3,1,2,1]
\n\nOutput: 3
\n\nExplanation:
\n\n[1,3]
(which is [1,2,1]
), where the minimum non-negative integer is 1. Setting all occurrences of 1 to 0 results in [3,0,2,0]
.[2,2]
(which is [2]
), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [3,0,0,0]
.[0,0]
(which is [3]
), where the minimum non-negative integer is 3. Setting all occurrences of 3 to 0 results in [0,0,0,0]
.Example 3:
\n\nInput: nums = [1,2,1,2,1,2]
\n\nOutput: 4
\n\nExplanation:
\n\n[0,5]
(which is [1,2,1,2,1,2]
), where the minimum non-negative integer is 1. Setting all occurrences of 1 to 0 results in [0,2,0,2,0,2]
.[1,1]
(which is [2]
), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [0,0,0,2,0,2]
.[3,3]
(which is [2]
), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [0,0,0,0,0,2]
.[5,5]
(which is [2]
), where the minimum non-negative integer is 2. Setting all occurrences of 2 to 0 results in [0,0,0,0,0,0]
.\n
Constraints:
\n\n1 <= n == nums.length <= 105
0 <= nums[i] <= 105
You are given an integer n
and a Directed Acyclic Graph (DAG) with n
nodes labeled from 0 to n - 1
. This is represented by a 2D array edges
, where edges[i] = [ui, vi, wi]
indicates a directed edge from node ui
to vi
with weight wi
.
You are also given two integers, k
and t
.
Your task is to determine the maximum possible sum of edge weights for any path in the graph such that:
\n\nk
edges.t
.Return the maximum possible sum of weights for such a path. If no such path exists, return -1
.
\n
Example 1:
\n\nInput: n = 3, edges = [[0,1,1],[1,2,2]], k = 2, t = 4
\n\nOutput: 3
\n\nExplanation:
\n\nk = 2
edges is 0 -> 1 -> 2
with weight 1 + 2 = 3 < t
.t
is 3.Example 2:
\n\nInput: n = 3, edges = [[0,1,2],[0,2,3]], k = 1, t = 3
\n\nOutput: 2
\n\nExplanation:
\n\nk = 1
edge:\n\n\t0 -> 1
with weight 2 < t
.0 -> 2
with weight 3 = t
, which is not strictly less than t
.t
is 2.Example 3:
\n\nInput: n = 3, edges = [[0,1,6],[1,2,8]], k = 1, t = 6
\n\nOutput: -1
\n\nExplanation:
\n\n0 -> 1
with weight 6 = t
, which is not strictly less than t
.1 -> 2
with weight 8 > t
, which is not strictly less than t
.t
, the answer is -1.\n
Constraints:
\n\n1 <= n <= 300
0 <= edges.length <= 300
edges[i] = [ui, vi, wi]
0 <= ui, vi < n
ui != vi
1 <= wi <= 10
0 <= k <= 300
1 <= t <= 600
dp[i][j]
contains all possible path weights that end at node i
, have total weight less than T
, and consist of exactly j
edges"
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Graph"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-weighted-k-edge-path/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3858",
+ "questionFrontendId": "3544",
+ "title": "Subtree Inversion Sum",
+ "content": "You are given an undirected tree rooted at node 0
, with n
nodes numbered from 0 to n - 1
. The tree is represented by a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates an edge between nodes ui
and vi
.
You are also given an integer array nums
of length n
, where nums[i]
represents the value at node i
, and an integer k
.
You may perform inversion operations on a subset of nodes subject to the following rules:
\n\nSubtree Inversion Operation:
\n\n\tWhen you invert a node, every value in the subtree rooted at that node is multiplied by -1.
\n\t\tDistance Constraint on Inversions:
\n\n\tYou may only invert a node if it is "sufficiently far" from any other inverted node.
\n\t\tSpecifically, if you invert two nodes a
and b
such that one is an ancestor of the other (i.e., if LCA(a, b) = a
or LCA(a, b) = b
), then the distance (the number of edges on the unique path between them) must be at least k
.
Return the maximum possible sum of the tree's node values after applying inversion operations.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], nums = [4,-8,-6,3,7,-2,5], k = 2
\n\nOutput: 27
\n\nExplanation:
\n\nnums
array is [-4, 8, 6, 3, 7, 2, 5]
, and the total sum is 27.Example 2:
\n\nInput: edges = [[0,1],[1,2],[2,3],[3,4]], nums = [-1,3,-2,4,-5], k = 2
\n\nOutput: 9
\n\nExplanation:
\n\nnums
array becomes [-1, 3, -2, 4, 5]
, and the total sum is 9.Example 3:
\n\nInput: edges = [[0,1],[0,2]], nums = [0,-1,-2], k = 3
\n\nOutput: 3
\n\nExplanation:
\n\nApply inversion operations at nodes 1 and 2.
\n\n
Constraints:
\n\n2 <= n <= 5 * 104
edges.length == n - 1
edges[i] = [ui, vi]
0 <= ui, vi < n
nums.length == n
-5 * 104 <= nums[i] <= 5 * 104
1 <= k <= 50
edges
represents a valid tree.node
is the current tree node",
+ "parityFromAncestorInversions
indicates whether the subtree values have been flipped an even (0) or odd (1) number of times by ancestor inversions",
+ "distSinceLastInversion
tracks the number of edges from this node up to the most recent ancestor inversion"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/subtree-inversion-sum/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3871",
+ "questionFrontendId": "3545",
+ "title": "Minimum Deletions for At Most K Distinct Characters",
+ "content": "You are given a string s
consisting of lowercase English letters, and an integer k
.
Your task is to delete some (possibly none) of the characters in the string so that the number of distinct characters in the resulting string is at most k
.
Return the minimum number of deletions required to achieve this.
\n\n\n
Example 1:
\n\nInput: s = "abc", k = 2
\n\nOutput: 1
\n\nExplanation:
\n\ns
has three distinct characters: 'a'
, 'b'
and 'c'
, each with a frequency of 1.k = 2
distinct characters, remove all occurrences of any one character from the string.'c'
results in at most k
distinct characters. Thus, the answer is 1.Example 2:
\n\nInput: s = "aabb", k = 2
\n\nOutput: 0
\n\nExplanation:
\n\ns
has two distinct characters ('a'
and 'b'
) with frequencies of 2 and 2, respectively.k = 2
distinct characters, no deletions are required. Thus, the answer is 0.Example 3:
\n\nInput: s = "yyyzz", k = 1
\n\nOutput: 2
\n\nExplanation:
\n\ns
has two distinct characters ('y'
and 'z'
) with frequencies of 3 and 2, respectively.k = 1
distinct character, remove all occurrences of any one character from the string.'z'
results in at most k
distinct characters. Thus, the answer is 2.\n
Constraints:
\n\n1 <= s.length <= 16
1 <= k <= 16
s
consists only of lowercase English letters.\n", + "likes": 57, + "dislikes": 4, + "stats": "{\"totalAccepted\": \"32.7K\", \"totalSubmission\": \"45.2K\", \"totalAcceptedRaw\": 32717, \"totalSubmissionRaw\": 45228, \"acRate\": \"72.3%\"}", + "similarQuestions": "[]", + "categoryTitle": "Algorithms", + "hints": [ + "Compute the frequency of each character in
s
and collect these into a list counts
.",
+ "Sort counts
in ascending order.",
+ "Let d
= (number of distinct characters) \u2013 k
. If d <= 0
, return 0.",
+ "Otherwise, the minimum deletions is the sum of the first d
entries in counts
(removing the d
least-frequent characters)."
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Counting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-deletions-for-at-most-k-distinct-characters/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3849",
+ "questionFrontendId": "3546",
+ "title": "Equal Sum Grid Partition I",
+ "content": "You are given an m x n
matrix grid
of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:
Return true
if such a partition exists; otherwise return false
.
\n
Example 1:
\n\nInput: grid = [[1,4],[2,3]]
\n\nOutput: true
\n\nExplanation:
\n\nA horizontal cut between row 0 and row 1 results in two non-empty sections, each with a sum of 5. Thus, the answer is true
.
Example 2:
\n\nInput: grid = [[1,3],[2,4]]
\n\nOutput: false
\n\nExplanation:
\n\nNo horizontal or vertical cut results in two non-empty sections with equal sums. Thus, the answer is false
.
\n
Constraints:
\n\n1 <= m == grid.length <= 105
1 <= n == grid[i].length <= 105
2 <= m * n <= 105
1 <= grid[i][j] <= 105
horizontal
cut or a vertical
cut.",
+ "For a horizontal
cut at row r
(0 <= r vertical
cut at column c
(0 <= c < n - 1), split grid
into columns 0...c vs. c+1...n-1 and compare their sums.",
+ "Brute\u2011force all possible r
and c
cuts; if any yields equal section sums, return true
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Matrix"
+ },
+ {
+ "name": "Enumeration"
+ },
+ {
+ "name": "Prefix Sum"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/equal-sum-grid-partition-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3845",
+ "questionFrontendId": "3547",
+ "title": "Maximum Sum of Edge Values in a Graph",
+ "content": "You are given an undirected connected graph of n
nodes, numbered from 0
to n - 1
. Each node is connected to at most 2 other nodes.
The graph consists of m
edges, represented by a 2D array edges
, where edges[i] = [ai, bi]
indicates that there is an edge between nodes ai
and bi
.
You have to assign a unique value from 1
to n
to each node. The value of an edge will be the product of the values assigned to the two nodes it connects.
Your score is the sum of the values of all edges in the graph.
\n\nReturn the maximum score you can achieve.
\n\n\n
Example 1:
\nInput: n = 4, edges = [[0,1],[1,2],[2,3]]
\n\nOutput: 23
\n\nExplanation:
\n\nThe diagram above illustrates an optimal assignment of values to nodes. The sum of the values of the edges is: (1 * 3) + (3 * 4) + (4 * 2) = 23
.
Example 2:
\nInput: n = 6, edges = [[0,3],[4,5],[2,0],[1,3],[2,4],[1,5]]
\n\nOutput: 82
\n\nExplanation:
\n\nThe diagram above illustrates an optimal assignment of values to nodes. The sum of the values of the edges is: (1 * 2) + (2 * 4) + (4 * 6) + (6 * 5) + (5 * 3) + (3 * 1) = 82
.
\n
Constraints:
\n\n1 <= n <= 5 * 104
m == edges.length
1 <= m <= n
edges[i].length == 2
0 <= ai, bi < n
ai != bi
You are given an m x n
matrix grid
of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:
Return true
if such a partition exists; otherwise, return false
.
Note: A section is connected if every cell in it can be reached from any other cell by moving up, down, left, or right through other cells in the section.
\n\n\n
Example 1:
\n\nInput: grid = [[1,4],[2,3]]
\n\nOutput: true
\n\nExplanation:
\n\n1 + 4 = 5
and 2 + 3 = 5
, which are equal. Thus, the answer is true
.Example 2:
\n\nInput: grid = [[1,2],[3,4]]
\n\nOutput: true
\n\nExplanation:
\n\n1 + 3 = 4
and 2 + 4 = 6
.6 - 2 = 4
), both sections have equal sums and remain connected. Thus, the answer is true
.Example 3:
\n\nInput: grid = [[1,2,4],[2,3,5]]
\n\nOutput: false
\n\nExplanation:
\n\n1 + 2 + 4 = 7
and 2 + 3 + 5 = 10
.10 - 3 = 7
), both sections have equal sums, but they do not remain connected as it splits the bottom section into two parts ([2]
and [5]
). Thus, the answer is false
.Example 4:
\n\nInput: grid = [[4,1,8],[3,2,6]]
\n\nOutput: false
\n\nExplanation:
\n\nNo valid cut exists, so the answer is false
.
\n
Constraints:
\n\n1 <= m == grid.length <= 105
1 <= n == grid[i].length <= 105
2 <= m * n <= 105
1 <= grid[i][j] <= 105
You are given an integer array nums
.
Return the smallest index i
such that the sum of the digits of nums[i]
is equal to i
.
If no such index exists, return -1
.
\n
Example 1:
\n\nInput: nums = [1,3,2]
\n\nOutput: 2
\n\nExplanation:
\n\nnums[2] = 2
, the sum of digits is 2, which is equal to index i = 2
. Thus, the output is 2.Example 2:
\n\nInput: nums = [1,10,11]
\n\nOutput: 1
\n\nExplanation:
\n\nnums[1] = 10
, the sum of digits is 1 + 0 = 1
, which is equal to index i = 1
.nums[2] = 11
, the sum of digits is 1 + 1 = 2
, which is equal to index i = 2
.Example 3:
\n\nInput: nums = [1,2,3]
\n\nOutput: -1
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= nums.length <= 100
0 <= nums[i] <= 1000
You are given an array nums
of distinct positive integers. You need to sort the array in increasing order based on the sum of the digits of each number. If two numbers have the same digit sum, the smaller number appears first in the sorted order.
Return the minimum number of swaps required to rearrange nums
into this sorted order.
A swap is defined as exchanging the values at two distinct positions in the array.
\n\n\n
Example 1:
\n\nInput: nums = [37,100]
\n\nOutput: 1
\n\nExplanation:
\n\n[3 + 7 = 10, 1 + 0 + 0 = 1] → [10, 1]
[100, 37]
. Swap 37
with 100
to obtain the sorted order.nums
is 1.Example 2:
\n\nInput: nums = [22,14,33,7]
\n\nOutput: 0
\n\nExplanation:
\n\n[2 + 2 = 4, 1 + 4 = 5, 3 + 3 = 6, 7 = 7] → [4, 5, 6, 7]
[22, 14, 33, 7]
. The array is already sorted.nums
is 0.Example 3:
\n\nInput: nums = [18,43,34,16]
\n\nOutput: 2
\n\nExplanation:
\n\n[1 + 8 = 9, 4 + 3 = 7, 3 + 4 = 7, 1 + 6 = 7] → [9, 7, 7, 7]
[16, 34, 43, 18]
. Swap 18
with 16
, and swap 43
with 34
to obtain the sorted order.nums
is 2.\n
Constraints:
\n\n1 <= nums.length <= 105
1 <= nums[i] <= 109
nums
consists of distinct positive integers.n - number_of_cycles
in the permutation."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Sorting"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-swaps-to-sort-by-digit-sum/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3837",
+ "questionFrontendId": "3552",
+ "title": "Grid Teleportation Traversal",
+ "content": "You are given a 2D character grid matrix
of size m x n
, represented as an array of strings, where matrix[i][j]
represents the cell at the intersection of the ith
row and jth
column. Each cell is one of the following:
'.'
representing an empty cell.'#'
representing an obstacle.'A'
-'Z'
) representing a teleportation portal.You start at the top-left cell (0, 0)
, and your goal is to reach the bottom-right cell (m - 1, n - 1)
. You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle.
If you step on a cell containing a portal letter and you haven't used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used at most once during your journey.
\n\nReturn the minimum number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, return -1
.
\n
Example 1:
\n\nInput: matrix = ["A..",".A.","..."]
\n\nOutput: 2
\n\nExplanation:
\n\n(0, 0)
to (1, 1)
.(1, 1)
to (1, 2)
.(1, 2)
to (2, 2)
.Example 2:
\n\nInput: matrix = [".#...",".#.#.",".#.#.","...#."]
\n\nOutput: 13
\n\nExplanation:
\n\n\n
Constraints:
\n\n1 <= m == matrix.length <= 103
1 <= n == matrix[i].length <= 103
matrix[i][j]
is either '#'
, '.'
, or an uppercase English letter.matrix[0][0]
is not an obstacle.You are given an undirected weighted tree with n
nodes, numbered from 0
to n - 1
. It is represented by a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi, wi]
indicates that there is an edge between nodes ui
and vi
with weight wi
.\u200b
Additionally, you are given a 2D integer array queries
, where queries[j] = [src1j, src2j, destj]
.
Return an array answer
of length equal to queries.length
, where answer[j]
is the minimum total weight of a subtree such that it is possible to reach destj
from both src1j
and src2j
using edges in this subtree.
A subtree here is any connected subset of nodes and edges of the original tree forming a valid tree.
\n\n\n
Example 1:
\n\nInput: edges = [[0,1,2],[1,2,3],[1,3,5],[1,4,4],[2,5,6]], queries = [[2,3,4],[0,2,5]]
\n\nOutput: [12,11]
\n\nExplanation:
\n\nThe blue edges represent one of the subtrees that yield the optimal answer.
\n\nanswer[0]
: The total weight of the selected subtree that ensures a path from src1 = 2
and src2 = 3
to dest = 4
is 3 + 5 + 4 = 12
.
answer[1]
: The total weight of the selected subtree that ensures a path from src1 = 0
and src2 = 2
to dest = 5
is 2 + 3 + 6 = 11
.
Example 2:
\n\nInput: edges = [[1,0,8],[0,2,7]], queries = [[0,1,2]]
\n\nOutput: [15]
\n\nExplanation:
\n\nanswer[0]
: The total weight of the selected subtree that ensures a path from src1 = 0
and src2 = 1
to dest = 2
is 8 + 7 = 15
.\n
Constraints:
\n\n3 <= n <= 105
edges.length == n - 1
edges[i].length == 3
0 <= ui, vi < n
1 <= wi <= 104
1 <= queries.length <= 105
queries[j].length == 3
0 <= src1j, src2j, destj < n
src1j
, src2j
, and destj
are pairwise distinct.edges
represents a valid tree.x
, let f(x)
be the distance from the root to x
. Then for two nodes x
and y
:d(x, y) = f(x) + f(y) - 2 * f(LCA(x, y))
",
+ "For three nodes a
, b
and c
, the minimum total weight of the subtree connecting all three is:(d(a, b) + d(b, c) + d(c, a)) / 2
, where d(x, y)
is the distance between nodes x
and y
"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3891",
+ "questionFrontendId": "3554",
+ "title": "Find Category Recommendation Pairs",
+ "content": "Table: ProductPurchases
\n+-------------+------+\n| Column Name | Type | \n+-------------+------+\n| user_id | int |\n| product_id | int |\n| quantity | int |\n+-------------+------+\n(user_id, product_id) is the unique identifier for this table. \nEach row represents a purchase of a product by a user in a specific quantity.\n\n\n
Table: ProductInfo
\n+-------------+---------+\n| Column Name | Type | \n+-------------+---------+\n| product_id | int |\n| category | varchar |\n| price | decimal |\n+-------------+---------+\nproduct_id is the unique identifier for this table.\nEach row assigns a category and price to a product.\n\n\n
Amazon wants to understand shopping patterns across product categories. Write a solution to:
\n\ncategory1
< category2
)A category pair is considered reportable if at least 3
different customers have purchased products from both categories.
Return the result table of reportable category pairs ordered by customer_count in descending order, and in case of a tie, by category1 in ascending order lexicographically, and then by category2 in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nProductPurchases table:
\n\n\n+---------+------------+----------+\n| user_id | product_id | quantity |\n+---------+------------+----------+\n| 1 | 101 | 2 |\n| 1 | 102 | 1 |\n| 1 | 201 | 3 |\n| 1 | 301 | 1 |\n| 2 | 101 | 1 |\n| 2 | 102 | 2 |\n| 2 | 103 | 1 |\n| 2 | 201 | 5 |\n| 3 | 101 | 2 |\n| 3 | 103 | 1 |\n| 3 | 301 | 4 |\n| 3 | 401 | 2 |\n| 4 | 101 | 1 |\n| 4 | 201 | 3 |\n| 4 | 301 | 1 |\n| 4 | 401 | 2 |\n| 5 | 102 | 2 |\n| 5 | 103 | 1 |\n| 5 | 201 | 2 |\n| 5 | 202 | 3 |\n+---------+------------+----------+\n\n\n
ProductInfo table:
\n\n\n+------------+-------------+-------+\n| product_id | category | price |\n+------------+-------------+-------+\n| 101 | Electronics | 100 |\n| 102 | Books | 20 |\n| 103 | Books | 35 |\n| 201 | Clothing | 45 |\n| 202 | Clothing | 60 |\n| 301 | Sports | 75 |\n| 401 | Kitchen | 50 |\n+------------+-------------+-------+\n\n\n
Output:
\n\n\n+-------------+-------------+----------------+\n| category1 | category2 | customer_count |\n+-------------+-------------+----------------+\n| Books | Clothing | 3 |\n| Books | Electronics | 3 |\n| Clothing | Electronics | 3 |\n| Electronics | Sports | 3 |\n+-------------+-------------+----------------+\n\n\n
Explanation:
\n\nThe result is ordered by customer_count in descending order. Since all pairs have the same customer_count of 3, they are ordered by category1 (then category2) in ascending order.
\nGiven a string s
, find the sum of the 3 largest unique prime numbers that can be formed using any of its substrings.
Return the sum of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of all available primes. If no prime numbers can be formed, return 0.
\n\nNote: Each prime number should be counted only once, even if it appears in multiple substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.
\n\n\n
Example 1:
\n\nInput: s = "12234"
\n\nOutput: 1469
\n\nExplanation:
\n\n"12234"
are 2, 3, 23, 223, and 1223.Example 2:
\n\nInput: s = "111"
\n\nOutput: 11
\n\nExplanation:
\n\n"111"
is 11.\n
Constraints:
\n\n1 <= s.length <= 10
s
consists of only digits.s
to generate candidate numbers.",
+ "Check each candidate for primality in O(sqrt(n))
time.",
+ "Store unique primes, then sum the three largest (or all if fewer than three)."
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Number Theory"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/sum-of-largest-prime-substrings/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3857",
+ "questionFrontendId": "3557",
+ "title": "Find Maximum Number of Non Intersecting Substrings",
+ "content": "You are given a string word
.
Return the maximum number of non-intersecting substrings of word that are at least four characters long and start and end with the same letter.
\n\n\n
Example 1:
\n\nInput: word = "abcdeafdef"
\n\nOutput: 2
\n\nExplanation:
\n\nThe two substrings are "abcdea"
and "fdef"
.
Example 2:
\n\nInput: word = "bcdaaaab"
\n\nOutput: 1
\n\nExplanation:
\n\nThe only substring is "aaaa"
. Note that we cannot also choose "bcdaaaab"
since it intersects with the other substring.
\n
Constraints:
\n\n1 <= word.length <= 2 * 105
word
consists only of lowercase English letters.c
, store all occurrence indices in order",
+ "At each position i
, let j
be the first index of word[i]
; if i - j >= 3
, we can form substring [j, i]
",
+ "For each index, also store the maximum for any substring ending before that index in the dp."
+ ],
+ "topicTags": [
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Greedy"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-maximum-number-of-non-intersecting-substrings/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3844",
+ "questionFrontendId": "3558",
+ "title": "Number of Ways to Assign Edge Weights I",
+ "content": "There is an undirected tree with n
nodes labeled from 1 to n
, rooted at node 1. The tree is represented by a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
.
Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.
\n\nThe cost of a path between any two nodes u
and v
is the total weight of all edges in the path connecting them.
Select any one node x
at the maximum depth. Return the number of ways to assign edge weights in the path from node 1 to x
such that its total cost is odd.
Since the answer may be large, return it modulo 109 + 7
.
Note: Ignore all edges not in the path from node 1 to x
.
\n
Example 1:
\n\nInput: edges = [[1,2]]
\n\nOutput: 1
\n\nExplanation:
\n\n1 → 2
).Example 2:
\n\nInput: edges = [[1,2],[1,3],[3,4],[3,5]]
\n\nOutput: 2
\n\nExplanation:
\n\n1 → 3
and 3 → 4
).\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i] == [ui, vi]
1 <= ui, vi <= n
edges
represents a valid tree.max_depth
.",
+ "The number of 2
s doesn\u2019t affect parity; we only need an odd number of 1
s along the path.",
+ "The number of ways to choose an odd count of 1s among max_depth
edges is 2^(max_depth-1)
."
+ ],
+ "topicTags": [
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/number-of-ways-to-assign-edge-weights-i/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3842",
+ "questionFrontendId": "3559",
+ "title": "Number of Ways to Assign Edge Weights II",
+ "content": "There is an undirected tree with n
nodes labeled from 1 to n
, rooted at node 1. The tree is represented by a 2D integer array edges
of length n - 1
, where edges[i] = [ui, vi]
indicates that there is an edge between nodes ui
and vi
.
Initially, all edges have a weight of 0. You must assign each edge a weight of either 1 or 2.
\n\nThe cost of a path between any two nodes u
and v
is the total weight of all edges in the path connecting them.
You are given a 2D integer array queries
. For each queries[i] = [ui, vi]
, determine the number of ways to assign weights to edges in the path such that the cost of the path between ui
and vi
is odd.
Return an array answer
, where answer[i]
is the number of valid assignments for queries[i]
.
Since the answer may be large, apply modulo 109 + 7
to each answer[i]
.
Note: For each query, disregard all edges not in the path between node ui
and vi
.
\n
Example 1:
\n\nInput: edges = [[1,2]], queries = [[1,1],[1,2]]
\n\nOutput: [0,1]
\n\nExplanation:
\n\n[1,1]
: The path from Node 1 to itself consists of no edges, so the cost is 0. Thus, the number of valid assignments is 0.[1,2]
: The path from Node 1 to Node 2 consists of one edge (1 → 2
). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.Example 2:
\n\nInput: edges = [[1,2],[1,3],[3,4],[3,5]], queries = [[1,4],[3,4],[2,5]]
\n\nOutput: [2,1,4]
\n\nExplanation:
\n\n[1,4]
: The path from Node 1 to Node 4 consists of two edges (1 → 3
and 3 → 4
). Assigning weights (1,2) or (2,1) results in an odd cost. Thus, the number of valid assignments is 2.[3,4]
: The path from Node 3 to Node 4 consists of one edge (3 → 4
). Assigning weight 1 makes the cost odd, while 2 makes it even. Thus, the number of valid assignments is 1.[2,5]
: The path from Node 2 to Node 5 consists of three edges (2 → 1, 1 → 3
, and 3 → 5
). Assigning (1,2,2), (2,1,2), (2,2,1), or (1,1,1) makes the cost odd. Thus, the number of valid assignments is 4.\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i] == [ui, vi]
1 <= queries.length <= 105
queries[i] == [ui, vi]
1 <= ui, vi <= n
edges
represents a valid tree.chainLength
and sumParity
.",
+ "Use Lowest Common Ancestor to find the distance between any two nodes quickly in O(logn)
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/number-of-ways-to-assign-edge-weights-ii/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3879",
+ "questionFrontendId": "3560",
+ "title": "Find Minimum Log Transportation Cost",
+ "content": "You are given integers n
, m
, and k
.
There are two logs of lengths n
and m
units, which need to be transported in three trucks where each truck can carry one log with length at most k
units.
You may cut the logs into smaller pieces, where the cost of cutting a log of length x
into logs of length len1
and len2
is cost = len1 * len2
such that len1 + len2 = x
.
Return the minimum total cost to distribute the logs onto the trucks. If the logs don't need to be cut, the total cost is 0.
\n\n\n
Example 1:
\n\nInput: n = 6, m = 5, k = 5
\n\nOutput: 5
\n\nExplanation:
\n\nCut the log with length 6 into logs with length 1 and 5, at a cost equal to 1 * 5 == 5
. Now the three logs of length 1, 5, and 5 can fit in one truck each.
Example 2:
\n\nInput: n = 4, m = 4, k = 6
\n\nOutput: 0
\n\nExplanation:
\n\nThe two logs can fit in the trucks already, hence we don't need to cut the logs.
\n\n
Constraints:
\n\n2 <= k <= 105
1 <= n, m <= 2 * k
k
, cost is zero.",
+ "Can we transport the logs if both logs have length greater than k
.",
+ "Otherwise, pick the log with greater length and cut it into logs with lengths len1
and len2
such that len1 + len2
equals the original length.",
+ "To minimize the cost len1 * len2
, choose len1
and len2
as far apart as possible (e.g. 1
and length\u22121
)."
+ ],
+ "topicTags": [
+ {
+ "name": "Math"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Easy",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-minimum-log-transportation-cost/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3860",
+ "questionFrontendId": "3561",
+ "title": "Resulting String After Adjacent Removals",
+ "content": "You are given a string s
consisting of lowercase English letters.
You must repeatedly perform the following operation while the string s
has at least two consecutive characters:
'a'
and 'b'
, or 'b'
and 'a'
).Return the resulting string after no more operations can be performed.
\n\nNote: Consider the alphabet as circular, thus 'a'
and 'z'
are consecutive.
\n
Example 1:
\n\nInput: s = "abc"
\n\nOutput: "c"
\n\nExplanation:
\n\n"ab"
from the string, leaving "c"
as the remaining string."c"
.Example 2:
\n\nInput: s = "adcb"
\n\nOutput: ""
\n\nExplanation:
\n\n"dc"
from the string, leaving "ab"
as the remaining string."ab"
from the string, leaving ""
as the remaining string.""
.Example 3:
\n\nInput: s = "zadb"
\n\nOutput: "db"
\n\nExplanation:
\n\n"za"
from the string, leaving "db"
as the remaining string."db"
.\n
Constraints:
\n\n1 <= s.length <= 105
s
consists only of lowercase English letters.You are given an integer n
, representing the number of employees in a company. Each employee is assigned a unique ID from 1 to n
, and employee 1 is the CEO. You are given two 1-based integer arrays, present
and future
, each of length n
, where:
present[i]
represents the current price at which the ith
employee can buy a stock today.future[i]
represents the expected price at which the ith
employee can sell the stock tomorrow.The company's hierarchy is represented by a 2D integer array hierarchy
, where hierarchy[i] = [ui, vi]
means that employee ui
is the direct boss of employee vi
.
Additionally, you have an integer budget
representing the total funds available for investment.
However, the company has a discount policy: if an employee's direct boss purchases their own stock, then the employee can buy their stock at half the original price (floor(present[v] / 2)
).
Return the maximum profit that can be achieved without exceeding the given budget.
\n\nNote:
\n\nbudget
.\n
Example 1:
\n\nInput: n = 2, present = [1,2], future = [4,3], hierarchy = [[1,2]], budget = 3
\n\nOutput: 5
\n\nExplanation:
\n\n4 - 1 = 3
.floor(2 / 2) = 1
.3 - 1 = 2
.1 + 1 = 2 <= budget
. Thus, the maximum total profit achieved is 3 + 2 = 5
.Example 2:
\n\nInput: n = 2, present = [3,4], future = [5,8], hierarchy = [[1,2]], budget = 4
\n\nOutput: 4
\n\nExplanation:
\n\n8 - 4 = 4
.Example 3:
\n\nInput: n = 3, present = [4,6,8], future = [7,9,11], hierarchy = [[1,2],[1,3]], budget = 10
\n\nOutput: 10
\n\nExplanation:
\n\n7 - 4 = 3
.floor(8 / 2) = 4
and earns a profit of 11 - 4 = 7
.4 + 4 = 8 <= budget
. Thus, the maximum total profit achieved is 3 + 7 = 10
.Example 4:
\n\nInput: n = 3, present = [5,2,3], future = [8,5,6], hierarchy = [[1,2],[2,3]], budget = 7
\n\nOutput: 12
\n\nExplanation:
\n\n8 - 5 = 3
.floor(2 / 2) = 1
and earns a profit of 5 - 1 = 4
.floor(3 / 2) = 1
and earns a profit of 6 - 1 = 5
.5 + 1 + 1 = 7 <= budget
. Thus, the maximum total profit achieved is 3 + 4 + 5 = 12
.\n
Constraints:
\n\n1 <= n <= 160
present.length, future.length == n
1 <= present[i], future[i] <= 50
hierarchy.length == n - 1
hierarchy[i] == [ui, vi]
1 <= ui, vi <= n
ui != vi
1 <= budget <= 160
hierarchy
is guaranteed to have no cycles.max_profit[u]
and max_profit1[u]
for each node u
",
+ "- max_profit[u]
= maximum profit in the subtree of u
assuming the parent of u
has not bought the stock",
+ "- max_profit1[u]
= maximum profit in the subtree of u
assuming the parent of u
has bought the stock",
+ "For each node u
, consider two cases:",
+ "Buy the stock for u
(at present[u]
price if parent did not buy, or at floor(present[u]/2)
if parent bought), then add the best max_profit1
values of its children",
+ "Skip buying for u
, then add the best max_profit
values of its children"
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Tree"
+ },
+ {
+ "name": "Depth-First Search"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximum-profit-from-trading-stocks-with-discounts/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3867",
+ "questionFrontendId": "3563",
+ "title": "Lexicographically Smallest String After Adjacent Removals",
+ "content": "You are given a string s
consisting of lowercase English letters.
You can perform the following operation any number of times (including zero):
\n\n'a'
and 'b'
, or 'b'
and 'a'
).Return the lexicographically smallest string that can be obtained after performing the operations optimally.
\n\nNote: Consider the alphabet as circular, thus 'a'
and 'z'
are consecutive.
\n
Example 1:
\n\nInput: s = "abc"
\n\nOutput: "a"
\n\nExplanation:
\n\n"bc"
from the string, leaving "a"
as the remaining string."a"
.Example 2:
\n\nInput: s = "bcda"
\n\nOutput: ""
\n\nExplanation:
\n\n"cd"
from the string, leaving "ba"
as the remaining string."ba"
from the string, leaving ""
as the remaining string.""
.Example 3:
\n\nInput: s = "zdce"
\n\nOutput: "zdce"
\n\nExplanation:
\n\n"dc"
from the string, leaving "ze"
as the remaining string."ze"
."zdce"
is lexicographically smaller than "ze"
, the smallest string after all possible removals is "zdce"
.\n
Constraints:
\n\n1 <= s.length <= 250
s
consists only of lowercase English letters.Table: sales
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| sale_id | int |\n| product_id | int |\n| sale_date | date |\n| quantity | int |\n| price | decimal |\n+---------------+---------+\nsale_id is the unique identifier for this table.\nEach row contains information about a product sale including the product_id, date of sale, quantity sold, and price per unit.\n\n\n
Table: products
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| product_id | int |\n| product_name | varchar |\n| category | varchar |\n+---------------+---------+\nproduct_id is the unique identifier for this table.\nEach row contains information about a product including its name and category.\n\n\n
Write a solution to find the most popular product category for each season. The seasons are defined as:
\n\nThe popularity of a category is determined by the total quantity sold in that season. If there is a tie, select the category with the highest total revenue (quantity × price
).
Return the result table ordered by season in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nsales table:
\n\n\n+---------+------------+------------+----------+-------+\n| sale_id | product_id | sale_date | quantity | price |\n+---------+------------+------------+----------+-------+\n| 1 | 1 | 2023-01-15 | 5 | 10.00 |\n| 2 | 2 | 2023-01-20 | 4 | 15.00 |\n| 3 | 3 | 2023-03-10 | 3 | 18.00 |\n| 4 | 4 | 2023-04-05 | 1 | 20.00 |\n| 5 | 1 | 2023-05-20 | 2 | 10.00 |\n| 6 | 2 | 2023-06-12 | 4 | 15.00 |\n| 7 | 5 | 2023-06-15 | 5 | 12.00 |\n| 8 | 3 | 2023-07-24 | 2 | 18.00 |\n| 9 | 4 | 2023-08-01 | 5 | 20.00 |\n| 10 | 5 | 2023-09-03 | 3 | 12.00 |\n| 11 | 1 | 2023-09-25 | 6 | 10.00 |\n| 12 | 2 | 2023-11-10 | 4 | 15.00 |\n| 13 | 3 | 2023-12-05 | 6 | 18.00 |\n| 14 | 4 | 2023-12-22 | 3 | 20.00 |\n| 15 | 5 | 2024-02-14 | 2 | 12.00 |\n+---------+------------+------------+----------+-------+\n\n\n
products table:
\n\n\n+------------+-----------------+----------+\n| product_id | product_name | category |\n+------------+-----------------+----------+\n| 1 | Warm Jacket | Apparel |\n| 2 | Designer Jeans | Apparel |\n| 3 | Cutting Board | Kitchen |\n| 4 | Smart Speaker | Tech |\n| 5 | Yoga Mat | Fitness |\n+------------+-----------------+----------+\n\n\n
Output:
\n\n\n+---------+----------+----------------+---------------+\n| season | category | total_quantity | total_revenue |\n+---------+----------+----------------+---------------+\n| Fall | Apparel | 10 | 120.00 |\n| Spring | Kitchen | 3 | 54.00 |\n| Summer | Tech | 5 | 100.00 |\n| Winter | Apparel | 9 | 110.00 |\n+---------+----------+----------------+---------------+\n\n\n
Explanation:
\n\nThe result table is ordered by season in ascending order.
\nYou are given an integer array nums
containing distinct positive integers and an integer target
.
Determine if you can partition nums
into two non-empty disjoint subsets, with each element belonging to exactly one subset, such that the product of the elements in each subset is equal to target
.
Return true
if such a partition exists and false
otherwise.
\n
Example 1:
\n\nInput: nums = [3,1,6,8,4], target = 24
\n\nOutput: true
\n\nExplanation: The subsets [3, 8]
and [1, 6, 4]
each have a product of 24. Hence, the output is true.
Example 2:
\n\nInput: nums = [2,5,3,7], target = 15
\n\nOutput: false
\n\nExplanation: There is no way to partition nums
into two non-empty disjoint subsets such that both subsets have a product of 15. Hence, the output is false.
\n
Constraints:
\n\n3 <= nums.length <= 12
1 <= target <= 1015
1 <= nums[i] <= 100
nums
are distinct.You are given an m x n
integer matrix grid
and an integer k
.
For every contiguous k x k
submatrix of grid
, compute the minimum absolute difference between any two distinct values within that submatrix.
Return a 2D array ans
of size (m - k + 1) x (n - k + 1)
, where ans[i][j]
is the minimum absolute difference in the submatrix whose top-left corner is (i, j)
in grid
.
Note: If all elements in the submatrix have the same value, the answer will be 0.
\nA submatrix(x1, y1, x2, y2)
is a matrix that is formed by choosing all cells matrix[x][y]
where x1 <= x <= x2
and y1 <= y <= y2
.\n\n
Example 1:
\n\nInput: grid = [[1,8],[3,-2]], k = 2
\n\nOutput: [[2]]
\n\nExplanation:
\n\nk x k
submatrix: [[1, 8], [3, -2]]
.[1, 8, 3, -2]
.|1 - 3| = 2
. Thus, the answer is [[2]]
.Example 2:
\n\nInput: grid = [[3,-1]], k = 1
\n\nOutput: [[0,0]]
\n\nExplanation:
\n\nk x k
submatrix has only one distinct element.[[0, 0]]
.Example 3:
\n\nInput: grid = [[1,-2,3],[2,3,5]], k = 2
\n\nOutput: [[1,2]]
\n\nExplanation:
\n\nk × k
submatrix:\n\n\t(0, 0)
: [[1, -2], [2, 3]]
.\n\n\t\t[1, -2, 2, 3]
.|1 - 2| = 1
.(0, 1)
: [[-2, 3], [3, 5]]
.\n\t\t[-2, 3, 5]
.|3 - 5| = 2
.[[1, 2]]
.\n
Constraints:
\n\n1 <= m == grid.length <= 30
1 <= n == grid[i].length <= 30
-105 <= grid[i][j] <= 105
1 <= k <= min(m, n)
You are given an m x n
grid classroom
where a student volunteer is tasked with cleaning up litter scattered around the room. Each cell in the grid is one of the following:
'S'
: Starting position of the student'L'
: Litter that must be collected (once collected, the cell becomes empty)'R'
: Reset area that restores the student's energy to full capacity, regardless of their current energy level (can be used multiple times)'X'
: Obstacle the student cannot pass through'.'
: Empty spaceYou are also given an integer energy
, representing the student's maximum energy capacity. The student starts with this energy from the starting position 'S'
.
Each move to an adjacent cell (up, down, left, or right) costs 1 unit of energy. If the energy reaches 0, the student can only continue if they are on a reset area 'R'
, which resets the energy to its maximum capacity energy
.
Return the minimum number of moves required to collect all litter items, or -1
if it's impossible.
\n
Example 1:
\n\nInput: classroom = ["S.", "XL"], energy = 2
\n\nOutput: 2
\n\nExplanation:
\n\n(0, 0)
with 2 units of energy.(1, 0)
contains an obstacle 'X', the student cannot move directly downward.(0, 0)
→ (0, 1)
with 1 unit of energy and 1 unit remaining.(0, 1)
→ (1, 1)
to collect the litter 'L'
.Example 2:
\n\nInput: classroom = ["LS", "RL"], energy = 4
\n\nOutput: 3
\n\nExplanation:
\n\n(0, 1)
with 4 units of energy.(0, 1)
→ (0, 0)
to collect the first litter 'L'
with 1 unit of energy used and 3 units remaining.(0, 0)
→ (1, 0)
to 'R'
to reset and restore energy back to 4.(1, 0)
→ (1, 1)
to collect the second litter 'L'
.Example 3:
\n\nInput: classroom = ["L.S", "RXL"], energy = 3
\n\nOutput: -1
\n\nExplanation:
\n\nNo valid path collects all 'L'
.
\n
Constraints:
\n\n1 <= m == classroom.length <= 20
1 <= n == classroom[i].length <= 20
classroom[i][j]
is one of 'S'
, 'L'
, 'R'
, 'X'
, or '.'
1 <= energy <= 50
'S'
in the grid.'L'
cells in the grid.(x, y, mask, e, steps)
, initializing with (sx, sy, 0, energy, 0)
, and for each move update e
(\u20131 per step), update mask
on 'L', reset e=energy
on 'R', and return steps
when mask == fullMask
.",
+ "Maintain a 3D array bestEnergy[x][y][mask]
storing the maximum e
seen for each (x,y,mask)
and skip any new state with e <= bestEnergy[x][y][mask]
to prune."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Bit Manipulation"
+ },
+ {
+ "name": "Breadth-First Search"
+ },
+ {
+ "name": "Matrix"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-moves-to-clean-the-classroom/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3878",
+ "questionFrontendId": "3569",
+ "title": "Maximize Count of Distinct Primes After Split",
+ "content": "You are given an integer array nums
having length n
and a 2D integer array queries
where queries[i] = [idx, val]
.
For each query:
\n\nnums[idx] = val
.k
with 1 <= k < n
to split the array into the non-empty prefix nums[0..k-1]
and suffix nums[k..n-1]
such that the sum of the counts of distinct prime values in each part is maximum.Note: The changes made to the array in one query persist into the next query.
\n\nReturn an array containing the result for each query, in the order they are given.
\n\n\n
Example 1:
\n\nInput: nums = [2,1,3,1,2], queries = [[1,2],[3,3]]
\n\nOutput: [3,4]
\n\nExplanation:
\n\nnums = [2, 1, 3, 1, 2]
.nums = [2, 2, 3, 1, 2]
. Split nums
into [2]
and [2, 3, 1, 2]
. [2]
consists of 1 distinct prime and [2, 3, 1, 2]
consists of 2 distinct primes. Hence, the answer for this query is 1 + 2 = 3
.nums = [2, 2, 3, 3, 2]
. Split nums
into [2, 2, 3]
and [3, 2]
with an answer of 2 + 2 = 4
.[3, 4]
.Example 2:
\n\nInput: nums = [2,1,4], queries = [[0,1]]
\n\nOutput: [0]
\n\nExplanation:
\n\nnums = [2, 1, 4]
.nums = [1, 1, 4]
. There are no prime numbers in nums
, hence the answer for this query is 0.[0]
.\n
Constraints:
\n\n2 <= n == nums.length <= 5 * 104
1 <= queries.length <= 5 * 104
1 <= nums[i] <= 105
0 <= queries[i][0] < nums.length
1 <= queries[i][1] <= 105
max(nums)
with a sieve to enable O(1) primality checks.",
+ "For each prime p
, record its occurrence indices
; if it appears at least twice, treat [first, last]
as a segment, and note that the split position k
with the most overlapping segments equals the number of primes counted on both sides.",
+ "Use a segment tree with lazy propagation over all possible k
to maintain, update, and query the sum of distinct-prime counts in the prefix and suffix, adjusting for overlaps."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Segment Tree"
+ },
+ {
+ "name": "Number Theory"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-count-of-distinct-primes-after-split/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3910",
+ "questionFrontendId": "3570",
+ "title": "Find Books with No Available Copies",
+ "content": "Table: library_books
\n+------------------+---------+\n| Column Name | Type |\n+------------------+---------+\n| book_id | int |\n| title | varchar |\n| author | varchar |\n| genre | varchar |\n| publication_year | int |\n| total_copies | int |\n+------------------+---------+\nbook_id is the unique identifier for this table.\nEach row contains information about a book in the library, including the total number of copies owned by the library.\n\n\n
Table: borrowing_records
\n+---------------+---------+\n| Column Name | Type |\n+---------------+---------+\n| record_id | int |\n| book_id | int |\n| borrower_name | varchar |\n| borrow_date | date |\n| return_date | date |\n+---------------+---------+\nrecord_id is the unique identifier for this table.\nEach row represents a borrowing transaction and return_date is NULL if the book is currently borrowed and hasn't been returned yet.\n\n\n
Write a solution to find all books that are currently borrowed (not returned) and have zero copies available in the library.
\n\nreturn_date
Return the result table ordered by current borrowers in descending order, then by book title in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nlibrary_books table:
\n\n\n+---------+------------------------+------------------+----------+------------------+--------------+\n| book_id | title | author | genre | publication_year | total_copies |\n+---------+------------------------+------------------+----------+------------------+--------------+\n| 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 |\n| 2 | To Kill a Mockingbird | Harper Lee | Fiction | 1960 | 3 |\n| 3 | 1984 | George Orwell | Dystopian| 1949 | 1 |\n| 4 | Pride and Prejudice | Jane Austen | Romance | 1813 | 2 |\n| 5 | The Catcher in the Rye | J.D. Salinger | Fiction | 1951 | 1 |\n| 6 | Brave New World | Aldous Huxley | Dystopian| 1932 | 4 |\n+---------+------------------------+------------------+----------+------------------+--------------+\n\n\n
borrowing_records table:
\n\n\n+-----------+---------+---------------+-------------+-------------+\n| record_id | book_id | borrower_name | borrow_date | return_date |\n+-----------+---------+---------------+-------------+-------------+\n| 1 | 1 | Alice Smith | 2024-01-15 | NULL |\n| 2 | 1 | Bob Johnson | 2024-01-20 | NULL |\n| 3 | 2 | Carol White | 2024-01-10 | 2024-01-25 |\n| 4 | 3 | David Brown | 2024-02-01 | NULL |\n| 5 | 4 | Emma Wilson | 2024-01-05 | NULL |\n| 6 | 5 | Frank Davis | 2024-01-18 | 2024-02-10 |\n| 7 | 1 | Grace Miller | 2024-02-05 | NULL |\n| 8 | 6 | Henry Taylor | 2024-01-12 | NULL |\n| 9 | 2 | Ivan Clark | 2024-02-12 | NULL |\n| 10 | 2 | Jane Adams | 2024-02-15 | NULL |\n+-----------+---------+---------------+-------------+-------------+\n\n\n
Output:
\n\n\n+---------+------------------+---------------+-----------+------------------+-------------------+\n| book_id | title | author | genre | publication_year | current_borrowers |\n+---------+------------------+---------------+-----------+------------------+-------------------+\n| 1 | The Great Gatsby | F. Scott | Fiction | 1925 | 3 | \n| 3 | 1984 | George Orwell | Dystopian | 1949 | 1 |\n+---------+------------------+---------------+-----------+------------------+-------------------+\n\n\n
Explanation:
\n\nOutput table is ordered by current_borrowers in descending order, then by book_title in ascending order.
\nYou are given two integer arrays x
and y
, each of length n
. You must choose three distinct indices i
, j
, and k
such that:
x[i] != x[j]
x[j] != x[k]
x[k] != x[i]
Your goal is to maximize the value of y[i] + y[j] + y[k]
under these conditions. Return the maximum possible sum that can be obtained by choosing such a triplet of indices.
If no such triplet exists, return -1.
\n\n\n
Example 1:
\n\nInput: x = [1,2,1,3,2], y = [5,3,4,6,2]
\n\nOutput: 14
\n\nExplanation:
\n\ni = 0
(x[i] = 1
, y[i] = 5
), j = 1
(x[j] = 2
, y[j] = 3
), k = 3
(x[k] = 3
, y[k] = 6
).x
are distinct. 5 + 3 + 6 = 14
is the maximum we can obtain. Hence, the output is 14.Example 2:
\n\nInput: x = [1,2,1,2], y = [4,5,6,7]
\n\nOutput: -1
\n\nExplanation:
\n\nx
. Hence, the output is -1.\n
Constraints:
\n\nn == x.length == y.length
3 <= n <= 105
1 <= x[i], y[i] <= 106
x
, keep only the maximum y
; all other pairs with the same x
are redundant.",
+ "Sort the pairs by x
so that identical x
values form contiguous blocks, then take the maximum y
from each block.",
+ "Alternatively, use a map (or dictionary) from x
to its largest y
."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Hash Table"
+ },
+ {
+ "name": "Greedy"
+ },
+ {
+ "name": "Sorting"
+ },
+ {
+ "name": "Heap (Priority Queue)"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/maximize-ysum-by-picking-a-triplet-of-distinct-xvalues/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3892",
+ "questionFrontendId": "3573",
+ "title": "Best Time to Buy and Sell Stock V",
+ "content": "You are given an integer array prices
where prices[i]
is the price of a stock in dollars on the ith
day, and an integer k
.
You are allowed to make at most k
transactions, where each transaction can be either of the following:
Normal transaction: Buy on day i
, then sell on a later day j
where i < j
. You profit prices[j] - prices[i]
.
Short selling transaction: Sell on day i
, then buy back on a later day j
where i < j
. You profit prices[i] - prices[j]
.
Note that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.
\n\nReturn the maximum total profit you can earn by making at most k
transactions.
\n
Example 1:
\n\nInput: prices = [1,7,9,8,2], k = 2
\n\nOutput: 14
\n\nExplanation:
\nWe can make $14 of profit through 2 transactions:\n\nExample 2:
\n\nInput: prices = [12,16,19,19,8,1,19,13,9], k = 3
\n\nOutput: 36
\n\nExplanation:
\nWe can make $36 of profit through 3 transactions:\n\n\n
Constraints:
\n\n2 <= prices.length <= 103
1 <= prices[i] <= 109
1 <= k <= prices.length / 2
idx
, transactionsDone
, transactionType
, isTransactionRunning
.",
+ "Transactions transition from completed -> running and from running -> completed."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-v/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3888",
+ "questionFrontendId": "3574",
+ "title": "Maximize Subarray GCD Score",
+ "content": "You are given an array of positive integers nums
and an integer k
.
You may perform at most k
operations. In each operation, you can choose one element in the array and double its value. Each element can be doubled at most once.
The score of a contiguous subarray is defined as the product of its length and the greatest common divisor (GCD) of all its elements.
\n\nYour task is to return the maximum score that can be achieved by selecting a contiguous subarray from the modified array.
\n\nNote:
\n\n\n
Example 1:
\n\nInput: nums = [2,4], k = 1
\n\nOutput: 8
\n\nExplanation:
\n\nnums[0]
to 4 using one operation. The modified array becomes [4, 4]
.[4, 4]
is 4, and the length is 2.2 × 4 = 8
.Example 2:
\n\nInput: nums = [3,5,7], k = 2
\n\nOutput: 14
\n\nExplanation:
\n\nnums[2]
to 14 using one operation. The modified array becomes [3, 5, 14]
.[14]
is 14, and the length is 1.1 × 14 = 14
.Example 3:
\n\nInput: nums = [5,5,5], k = 1
\n\nOutput: 15
\n\nExplanation:
\n\n[5, 5, 5]
has a GCD of 5, and its length is 3.3 × 5 = 15
.\n
Constraints:
\n\n1 <= n == nums.length <= 1500
1 <= nums[i] <= 109
1 <= k <= n
You are given an undirected tree rooted at node 0 with n
nodes numbered from 0 to n - 1
. Each node i
has an integer value vals[i]
, and its parent is given by par[i]
.
A subset of nodes within the subtree of a node is called good if every digit from 0 to 9 appears at most once in the decimal representation of the values of the selected nodes.
\n\nThe score of a good subset is the sum of the values of its nodes.
\n\nDefine an array maxScore
of length n
, where maxScore[u]
represents the maximum possible sum of values of a good subset of nodes that belong to the subtree rooted at node u
, including u
itself and all its descendants.
Return the sum of all values in maxScore
.
Since the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: vals = [2,3], par = [-1,0]
\n\nOutput: 8
\n\nExplanation:
\n\n{0, 1}
. The subset {2, 3}
is good as the digits 2 and 3 appear only once. The score of this subset is 2 + 3 = 5
.{1}
. The subset {3}
is good. The score of this subset is 3.maxScore
array is [5, 3]
, and the sum of all values in maxScore
is 5 + 3 = 8
. Thus, the answer is 8.Example 2:
\n\nInput: vals = [1,5,2], par = [-1,0,0]
\n\nOutput: 15
\n\nExplanation:
\n\n{0, 1, 2}
. The subset {1, 5, 2}
is good as the digits 1, 5 and 2 appear only once. The score of this subset is 1 + 5 + 2 = 8
.{1}
. The subset {5}
is good. The score of this subset is 5.{2}
. The subset {2}
is good. The score of this subset is 2.maxScore
array is [8, 5, 2]
, and the sum of all values in maxScore
is 8 + 5 + 2 = 15
. Thus, the answer is 15.Example 3:
\n\nInput: vals = [34,1,2], par = [-1,0,1]
\n\nOutput: 42
\n\nExplanation:
\n\n{0, 1, 2}
. The subset {34, 1, 2}
is good as the digits 3, 4, 1 and 2 appear only once. The score of this subset is 34 + 1 + 2 = 37
.{1, 2}
. The subset {1, 2}
is good as the digits 1 and 2 appear only once. The score of this subset is 1 + 2 = 3
.{2}
. The subset {2}
is good. The score of this subset is 2.maxScore
array is [37, 3, 2]
, and the sum of all values in maxScore
is 37 + 3 + 2 = 42
. Thus, the answer is 42.Example 4:
\n\nInput: vals = [3,22,5], par = [-1,0,1]
\n\nOutput: 18
\n\nExplanation:
\n\n{0, 1, 2}
. The subset {3, 22, 5}
is not good, as digit 2 appears twice. Therefore, the subset {3, 5}
is valid. The score of this subset is 3 + 5 = 8
.{1, 2}
. The subset {22, 5}
is not good, as digit 2 appears twice. Therefore, the subset {5}
is valid. The score of this subset is 5.{2}
. The subset {5}
is good. The score of this subset is 5.maxScore
array is [8, 5, 5]
, and the sum of all values in maxScore
is 8 + 5 + 5 = 18
. Thus, the answer is 18.\n
Constraints:
\n\n1 <= n == vals.length <= 500
1 <= vals[i] <= 109
par.length == n
par[0] == -1
0 <= par[i] < n
for i
in [1, n - 1]
par
represents a valid tree.You are given an integer array nums
of size n
containing only 1
and -1
, and an integer k
.
You can perform the following operation at most k
times:
Choose an index i
(0 <= i < n - 1
), and multiply both nums[i]
and nums[i + 1]
by -1
.
Note that you can choose the same index i
more than once in different operations.
Return true
if it is possible to make all elements of the array equal after at most k
operations, and false
otherwise.
\n
Example 1:
\n\nInput: nums = [1,-1,1,-1,1], k = 3
\n\nOutput: true
\n\nExplanation:
\n\nWe can make all elements in the array equal in 2 operations as follows:
\n\ni = 1
, and multiply both nums[1]
and nums[2]
by -1. Now nums = [1,1,-1,-1,1]
.i = 2
, and multiply both nums[2]
and nums[3]
by -1. Now nums = [1,1,1,1,1]
.Example 2:
\n\nInput: nums = [-1,-1,-1,1,1,1], k = 5
\n\nOutput: false
\n\nExplanation:
\n\nIt is not possible to make all array elements equal in at most 5 operations.
\n\n
Constraints:
\n\n1 <= n == nums.length <= 105
nums[i]
is either -1 or 1.1 <= k <= n
You are given an array complexity
of length n
.
There are n
locked computers in a room with labels from 0 to n - 1
, each with its own unique password. The password of the computer i
has a complexity complexity[i]
.
The password for the computer labeled 0 is already decrypted and serves as the root. All other computers must be unlocked using it or another previously unlocked computer, following this information:
\n\ni
using the password for computer j
, where j
is any integer less than i
with a lower complexity. (i.e. j < i
and complexity[j] < complexity[i]
)i
, you must have already unlocked a computer j
such that j < i
and complexity[j] < complexity[i]
.Find the number of permutations of [0, 1, 2, ..., (n - 1)]
that represent a valid order in which the computers can be unlocked, starting from computer 0 as the only initially unlocked one.
Since the answer may be large, return it modulo 109 + 7.
\n\nNote that the password for the computer with label 0 is decrypted, and not the computer with the first position in the permutation.
\n\n\n
Example 1:
\n\nInput: complexity = [1,2,3]
\n\nOutput: 2
\n\nExplanation:
\n\nThe valid permutations are:
\n\ncomplexity[0] < complexity[1]
.complexity[1] < complexity[2]
.complexity[0] < complexity[2]
.complexity[0] < complexity[1]
.Example 2:
\n\nInput: complexity = [3,3,3,4,4,4]
\n\nOutput: 0
\n\nExplanation:
\n\nThere are no possible permutations which can unlock all computers.
\n\n
Constraints:
\n\n2 <= complexity.length <= 105
1 <= complexity[i] <= 109
1
to n - 1
can then be arranged arbitrarily, yielding factorial(n - 1)
possible orders."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Math"
+ },
+ {
+ "name": "Brainteaser"
+ },
+ {
+ "name": "Combinatorics"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/count-the-number-of-computer-unlocking-permutations/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3835",
+ "questionFrontendId": "3578",
+ "title": "Count Partitions With Max-Min Difference at Most K",
+ "content": "You are given an integer array nums
and an integer k
. Your task is to partition nums
into one or more non-empty contiguous segments such that in each segment, the difference between its maximum and minimum elements is at most k
.
Return the total number of ways to partition nums
under this condition.
Since the answer may be too large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [9,4,1,3,7], k = 4
\n\nOutput: 6
\n\nExplanation:
\n\nThere are 6 valid partitions where the difference between the maximum and minimum elements in each segment is at most k = 4
:
[[9], [4], [1], [3], [7]]
[[9], [4], [1], [3, 7]]
[[9], [4], [1, 3], [7]]
[[9], [4, 1], [3], [7]]
[[9], [4, 1], [3, 7]]
[[9], [4, 1, 3], [7]]
Example 2:
\n\nInput: nums = [3,3,4], k = 0
\n\nOutput: 2
\n\nExplanation:
\n\nThere are 2 valid partitions that satisfy the given conditions:
\n\n[[3], [3], [4]]
[[3, 3], [4]]
\n
Constraints:
\n\n2 <= nums.length <= 5 * 104
1 <= nums[i] <= 109
0 <= k <= 109
dp[idx]
be the count of ways to partition the array with the last partition ending at index idx
.",
+ "Try using a sliding window; we can track the minimum and maximum in the window using deques."
+ ],
+ "topicTags": [
+ {
+ "name": "Array"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Queue"
+ },
+ {
+ "name": "Sliding Window"
+ },
+ {
+ "name": "Prefix Sum"
+ },
+ {
+ "name": "Monotonic Queue"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/count-partitions-with-max-min-difference-at-most-k/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3866",
+ "questionFrontendId": "3579",
+ "title": "Minimum Steps to Convert String with Operations",
+ "content": "You are given two strings, word1
and word2
, of equal length. You need to transform word1
into word2
.
For this, divide word1
into one or more contiguous substrings. For each substring substr
you can perform the following operations:
Replace: Replace the character at any one index of substr
with another lowercase English letter.
Swap: Swap any two characters in substr
.
Reverse Substring: Reverse substr
.
Each of these counts as one operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).
\n\nReturn the minimum number of operations required to transform word1
into word2
.
\n
Example 1:
\n\nInput: word1 = "abcdf", word2 = "dacbe"
\n\nOutput: 4
\n\nExplanation:
\n\nDivide word1
into "ab"
, "c"
, and "df"
. The operations are:
"ab"
,\n\n\t"ab" -> "ba"
."ba" -> "da"
."c"
do no operations."df"
,\n\t"df" -> "bf"
."bf" -> "be"
.Example 2:
\n\nInput: word1 = "abceded", word2 = "baecfef"
\n\nOutput: 4
\n\nExplanation:
\n\nDivide word1
into "ab"
, "ce"
, and "ded"
. The operations are:
"ab"
,\n\n\t"ab" -> "ba"
."ce"
,\n\t"ce" -> "ec"
."ded"
,\n\t"ded" -> "fed"
."fed" -> "fef"
.Example 3:
\n\nInput: word1 = "abcdef", word2 = "fedabc"
\n\nOutput: 2
\n\nExplanation:
\n\nDivide word1
into "abcdef"
. The operations are:
"abcdef"
,\n\n\t"abcdef" -> "fedcba"
."fedcba" -> "fedabc"
.\n
Constraints:
\n\n1 <= word1.length == word2.length <= 100
word1
and word2
consist only of lowercase English letters.word1
. For the DP, we try both the substring and its reversed version (just add one extra operation)",
+ "First we swap pairs like (word1[i]
, word2[i]
) and (word1[j]
, word2[j]
) where word1[i] == word2[j]
and word2[i] == word1[j]
",
+ "For the remaining characters, we use replace operations"
+ ],
+ "topicTags": [
+ {
+ "name": "String"
+ },
+ {
+ "name": "Dynamic Programming"
+ },
+ {
+ "name": "Greedy"
+ }
+ ],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/minimum-steps-to-convert-string-with-operations/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3921",
+ "questionFrontendId": "3580",
+ "title": "Find Consistently Improving Employees",
+ "content": "Table: employees
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| employee_id | int |\n| name | varchar |\n+-------------+---------+\nemployee_id is the unique identifier for this table.\nEach row contains information about an employee.\n\n\n
Table: performance_reviews
\n+-------------+------+\n| Column Name | Type |\n+-------------+------+\n| review_id | int |\n| employee_id | int |\n| review_date | date |\n| rating | int |\n+-------------+------+\nreview_id is the unique identifier for this table.\nEach row represents a performance review for an employee. The rating is on a scale of 1-5 where 5 is excellent and 1 is poor.\n\n\n
Write a solution to find employees who have consistently improved their performance over their last three reviews.
\n\n3
review to be considered3
reviews must show strictly increasing ratings (each review better than the previous)3
reviews based on review_date
for each employee3
reviewsReturn the result table ordered by improvement score in descending order, then by name in ascending order.
\n\nThe result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\nemployees table:
\n\n\n+-------------+----------------+\n| employee_id | name |\n+-------------+----------------+\n| 1 | Alice Johnson |\n| 2 | Bob Smith |\n| 3 | Carol Davis |\n| 4 | David Wilson |\n| 5 | Emma Brown |\n+-------------+----------------+\n\n\n
performance_reviews table:
\n\n\n+-----------+-------------+-------------+--------+\n| review_id | employee_id | review_date | rating |\n+-----------+-------------+-------------+--------+\n| 1 | 1 | 2023-01-15 | 2 |\n| 2 | 1 | 2023-04-15 | 3 |\n| 3 | 1 | 2023-07-15 | 4 |\n| 4 | 1 | 2023-10-15 | 5 |\n| 5 | 2 | 2023-02-01 | 3 |\n| 6 | 2 | 2023-05-01 | 2 |\n| 7 | 2 | 2023-08-01 | 4 |\n| 8 | 2 | 2023-11-01 | 5 |\n| 9 | 3 | 2023-03-10 | 1 |\n| 10 | 3 | 2023-06-10 | 2 |\n| 11 | 3 | 2023-09-10 | 3 |\n| 12 | 3 | 2023-12-10 | 4 |\n| 13 | 4 | 2023-01-20 | 4 |\n| 14 | 4 | 2023-04-20 | 4 |\n| 15 | 4 | 2023-07-20 | 4 |\n| 16 | 5 | 2023-02-15 | 3 |\n| 17 | 5 | 2023-05-15 | 2 |\n+-----------+-------------+-------------+--------+\n\n\n
Output:
\n\n\n+-------------+----------------+-------------------+\n| employee_id | name | improvement_score |\n+-------------+----------------+-------------------+\n| 2 | Bob Smith | 3 |\n| 1 | Alice Johnson | 2 |\n| 3 | Carol Davis | 2 |\n+-------------+----------------+-------------------+\n\n\n
Explanation:
\n\nThe output table is ordered by improvement_score in descending order, then by name in ascending order.
\nYou are given a string caption
representing the caption for a video.
The following actions must be performed in order to generate a valid tag for the video:
\n\nCombine all words in the string into a single camelCase string prefixed with '#'
. A camelCase string is one where the first letter of all words except the first one is capitalized. All characters after the first character in each word must be lowercase.
Remove all characters that are not an English letter, except the first '#'
.
Truncate the result to a maximum of 100 characters.
\n\tReturn the tag after performing the actions on caption
.
\n
Example 1:
\n\nInput: caption = "Leetcode daily streak achieved"
\n\nOutput: "#leetcodeDailyStreakAchieved"
\n\nExplanation:
\n\nThe first letter for all words except "leetcode"
should be capitalized.
Example 2:
\n\nInput: caption = "can I Go There"
\n\nOutput: "#canIGoThere"
\n\nExplanation:
\n\nThe first letter for all words except "can"
should be capitalized.
Example 3:
\n\nInput: caption = "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
\n\nOutput: "#hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"
\n\nExplanation:
\n\nSince the first word has length 101, we need to truncate the last two letters from the word.
\n\n
Constraints:
\n\n1 <= caption.length <= 150
caption
consists only of English letters and ' '
.You are given an integer array nums
.
A special triplet is defined as a triplet of indices (i, j, k)
such that:
0 <= i < j < k < n
, where n = nums.length
nums[i] == nums[j] * 2
nums[k] == nums[j] * 2
Return the total number of special triplets in the array.
\n\nSince the answer may be large, return it modulo 109 + 7
.
\n
Example 1:
\n\nInput: nums = [6,3,6]
\n\nOutput: 1
\n\nExplanation:
\n\nThe only special triplet is (i, j, k) = (0, 1, 2)
, where:
nums[0] = 6
, nums[1] = 3
, nums[2] = 6
nums[0] = nums[1] * 2 = 3 * 2 = 6
nums[2] = nums[1] * 2 = 3 * 2 = 6
Example 2:
\n\nInput: nums = [0,1,0,0]
\n\nOutput: 1
\n\nExplanation:
\n\nThe only special triplet is (i, j, k) = (0, 2, 3)
, where:
nums[0] = 0
, nums[2] = 0
, nums[3] = 0
nums[0] = nums[2] * 2 = 0 * 2 = 0
nums[3] = nums[2] * 2 = 0 * 2 = 0
Example 3:
\n\nInput: nums = [8,4,2,8,4]
\n\nOutput: 2
\n\nExplanation:
\n\nThere are exactly two special triplets:
\n\n(i, j, k) = (0, 1, 3)
\n\n\tnums[0] = 8
, nums[1] = 4
, nums[3] = 8
nums[0] = nums[1] * 2 = 4 * 2 = 8
nums[3] = nums[1] * 2 = 4 * 2 = 8
(i, j, k) = (1, 2, 4)
\n\tnums[1] = 4
, nums[2] = 2
, nums[4] = 4
nums[1] = nums[2] * 2 = 2 * 2 = 4
nums[4] = nums[2] * 2 = 2 * 2 = 4
\n
Constraints:
\n\n3 <= n == nums.length <= 105
0 <= nums[i] <= 105
freqPrev
and freqNext
\u2014to track how many times each value appears before and after the current index.",
+ "For each index j
in the triplet (i
,j
,k
), compute its contribution to the answer using your freqPrev and freqNext counts."
+ ],
+ "topicTags": [],
+ "companyTags": null,
+ "difficulty": "Medium",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/count-special-triplets/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3755",
+ "questionFrontendId": "3584",
+ "title": "Maximum Product of First and Last Elements of a Subsequence",
+ "content": "You are given an integer array nums
and an integer m
.
Return the maximum product of the first and last elements of any subsequence of nums
of size m
.
\n
Example 1:
\n\nInput: nums = [-1,-9,2,3,-2,-3,1], m = 1
\n\nOutput: 81
\n\nExplanation:
\n\nThe subsequence [-9]
has the largest product of the first and last elements: -9 * -9 = 81
. Therefore, the answer is 81.
Example 2:
\n\nInput: nums = [1,3,-5,5,6,-4], m = 3
\n\nOutput: 20
\n\nExplanation:
\n\nThe subsequence [-5, 6, -4]
has the largest product of the first and last elements.
Example 3:
\n\nInput: nums = [2,-1,2,-6,5,2,-5,7], m = 2
\n\nOutput: 35
\n\nExplanation:
\n\nThe subsequence [5, 7]
has the largest product of the first and last elements.
\n
Constraints:
\n\n1 <= nums.length <= 105
-105 <= nums[i] <= 105
1 <= m <= nums.length
You are given an integer n
and an undirected, weighted tree rooted at node 0 with n
nodes numbered from 0 to n - 1
. This is represented by a 2D array edges
of length n - 1
, where edges[i] = [ui, vi, wi]
indicates an edge from node ui
to vi
with weight wi
.
The weighted median node is defined as the first node x
on the path from ui
to vi
such that the sum of edge weights from ui
to x
is greater than or equal to half of the total path weight.
You are given a 2D integer array queries
. For each queries[j] = [uj, vj]
, determine the weighted median node along the path from uj
to vj
.
Return an array ans
, where ans[j]
is the node index of the weighted median for queries[j]
.
\n
Example 1:
\n\nInput: n = 2, edges = [[0,1,7]], queries = [[1,0],[0,1]]
\n\nOutput: [0,1]
\n\nExplanation:
\n\nQuery | \n\t\t\tPath | \n\t\t\tEdge \n\t\t\tWeights | \n\t\t\tTotal \n\t\t\tPath \n\t\t\tWeight | \n\t\t\tHalf | \n\t\t\tExplanation | \n\t\t\tAnswer | \n\t\t
---|---|---|---|---|---|---|
[1, 0] | \n\t\t\t1 → 0 | \n\t\t\t[7] | \n\t\t\t7 | \n\t\t\t3.5 | \n\t\t\tSum from 1 → 0 = 7 >= 3.5 , median is node 0. | \n\t\t\t0 | \n\t\t
[0, 1] | \n\t\t\t0 → 1 | \n\t\t\t[7] | \n\t\t\t7 | \n\t\t\t3.5 | \n\t\t\tSum from 0 → 1 = 7 >= 3.5 , median is node 1. | \n\t\t\t1 | \n\t\t
Example 2:
\n\nInput: n = 3, edges = [[0,1,2],[2,0,4]], queries = [[0,1],[2,0],[1,2]]
\n\nOutput: [1,0,2]
\n\nExplanation:
\n\nQuery | \n\t\t\tPath | \n\t\t\tEdge \n\t\t\tWeights | \n\t\t\tTotal \n\t\t\tPath \n\t\t\tWeight | \n\t\t\tHalf | \n\t\t\tExplanation | \n\t\t\tAnswer | \n\t\t
---|---|---|---|---|---|---|
[0, 1] | \n\t\t\t0 → 1 | \n\t\t\t[2] | \n\t\t\t2 | \n\t\t\t1 | \n\t\t\tSum from 0 → 1 = 2 >= 1 , median is node 1. | \n\t\t\t1 | \n\t\t
[2, 0] | \n\t\t\t2 → 0 | \n\t\t\t[4] | \n\t\t\t4 | \n\t\t\t2 | \n\t\t\tSum from 2 → 0 = 4 >= 2 , median is node 0. | \n\t\t\t0 | \n\t\t
[1, 2] | \n\t\t\t1 → 0 → 2 | \n\t\t\t[2, 4] | \n\t\t\t6 | \n\t\t\t3 | \n\t\t\tSum from 1 → 0 = 2 < 3 .\n\t\t\tSum from 1 → 2 = 2 + 4 = 6 >= 3 , median is node 2. | \n\t\t\t2 | \n\t\t
Example 3:
\n\nInput: n = 5, edges = [[0,1,2],[0,2,5],[1,3,1],[2,4,3]], queries = [[3,4],[1,2]]
\n\nOutput: [2,2]
\n\nExplanation:
\n\nQuery | \n\t\t\tPath | \n\t\t\tEdge \n\t\t\tWeights | \n\t\t\tTotal \n\t\t\tPath \n\t\t\tWeight | \n\t\t\tHalf | \n\t\t\tExplanation | \n\t\t\tAnswer | \n\t\t
---|---|---|---|---|---|---|
[3, 4] | \n\t\t\t3 → 1 → 0 → 2 → 4 | \n\t\t\t[1, 2, 5, 3] | \n\t\t\t11 | \n\t\t\t5.5 | \n\t\t\tSum from 3 → 1 = 1 < 5.5 .\n\t\t\tSum from 3 → 0 = 1 + 2 = 3 < 5.5 .\n\t\t\tSum from 3 → 2 = 1 + 2 + 5 = 8 >= 5.5 , median is node 2. | \n\t\t\t2 | \n\t\t
[1, 2] | \n\t\t\t1 → 0 → 2 | \n\t\t\t[2, 5] | \n\t\t\t7 | \n\t\t\t3.5 | \n\t\t\t\n\t\t\t Sum from | \n\t\t\t2 | \n\t\t
\n
Constraints:
\n\n2 <= n <= 105
edges.length == n - 1
edges[i] == [ui, vi, wi]
0 <= ui, vi < n
1 <= wi <= 109
1 <= queries.length <= 105
queries[j] == [uj, vj]
0 <= uj, vj < n
edges
represents a valid tree.u
and v
, with lowest common ancestor l
and total path weight tot
.",
+ "If the median lies on the path from u
up to l
: find the first node where 2 * sum >= tot
(equivalently, the last where 2 * sum < tot
and move one node above).",
+ "Otherwise, it lies on the path from v
up to l
: use the same 2 * sum >= tot
criterion as you climb.",
+ "In both cases, binary lifting with sparse tables lets you jump by powers of two while tracking cumulative weights to locate the weighted median in O(log n)"
+ ],
+ "topicTags": [],
+ "companyTags": null,
+ "difficulty": "Hard",
+ "isPaidOnly": false,
+ "solution": null,
+ "hasSolution": false,
+ "hasVideoSolution": false,
+ "url": "https://leetcode.com/problems/find-weighted-median-node-in-tree/"
+ }
+ }
+ },
+ {
+ "data": {
+ "question": {
+ "questionId": "3932",
+ "questionFrontendId": "3586",
+ "title": "Find COVID Recovery Patients",
+ "content": "Table: patients
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| patient_id | int |\n| patient_name| varchar |\n| age | int |\n+-------------+---------+\npatient_id is the unique identifier for this table.\nEach row contains information about a patient.\n\n\n
Table: covid_tests
\n+-------------+---------+\n| Column Name | Type |\n+-------------+---------+\n| test_id | int |\n| patient_id | int |\n| test_date | date |\n| result | varchar |\n+-------------+---------+\ntest_id is the unique identifier for this table.\nEach row represents a COVID test result. The result can be Positive, Negative, or Inconclusive.\n\n\n
Write a solution to find patients who have recovered from COVID - patients who tested positive but later tested negative.
\n\nReturn the result table ordered by recovery_time
in ascending order, then by patient_name
in ascending order.
The result format is in the following example.
\n\n\n
Example:
\n\nInput:
\n\npatients table:
\n\n\n+------------+--------------+-----+\n| patient_id | patient_name | age |\n+------------+--------------+-----+\n| 1 | Alice Smith | 28 |\n| 2 | Bob Johnson | 35 |\n| 3 | Carol Davis | 42 |\n| 4 | David Wilson | 31 |\n| 5 | Emma Brown | 29 |\n+------------+--------------+-----+\n\n\n
covid_tests table:
\n\n\n+---------+------------+------------+--------------+\n| test_id | patient_id | test_date | result |\n+---------+------------+------------+--------------+\n| 1 | 1 | 2023-01-15 | Positive |\n| 2 | 1 | 2023-01-25 | Negative |\n| 3 | 2 | 2023-02-01 | Positive |\n| 4 | 2 | 2023-02-05 | Inconclusive |\n| 5 | 2 | 2023-02-12 | Negative |\n| 6 | 3 | 2023-01-20 | Negative |\n| 7 | 3 | 2023-02-10 | Positive |\n| 8 | 3 | 2023-02-20 | Negative |\n| 9 | 4 | 2023-01-10 | Positive |\n| 10 | 4 | 2023-01-18 | Positive |\n| 11 | 5 | 2023-02-15 | Negative |\n| 12 | 5 | 2023-02-20 | Negative |\n+---------+------------+------------+--------------+\n\n\n
Output:
\n\n\n+------------+--------------+-----+---------------+\n| patient_id | patient_name | age | recovery_time |\n+------------+--------------+-----+---------------+\n| 1 | Alice Smith | 28 | 10 |\n| 3 | Carol Davis | 42 | 10 |\n| 2 | Bob Johnson | 35 | 11 |\n+------------+--------------+-----+---------------+\n\n\n
Explanation:
\n\nOutput table is ordered by recovery_time in ascending order, and then by patient_name in ascending order.
\n+ Explore LeetCode data through our API endpoints. Get problem details, + user statistics, submissions history, and more! +
+ + + ++ Made with โค๏ธ by + + Yan-Ying Liao + +
+