Dataset Viewer
Auto-converted to Parquet
Title
stringlengths
3
81
Description
stringlengths
219
5.66k
C
stringclasses
154 values
C#
stringclasses
299 values
C++
stringlengths
88
4.55k
Cangjie
stringclasses
3 values
Dart
stringclasses
2 values
Go
stringlengths
47
3.11k
Java
stringlengths
86
5.36k
JavaScript
stringclasses
465 values
Kotlin
stringclasses
15 values
MySQL
stringclasses
282 values
Nim
stringclasses
4 values
PHP
stringclasses
111 values
Pandas
stringclasses
31 values
Python3
stringlengths
82
4.27k
Ruby
stringclasses
8 values
Rust
stringlengths
83
4.8k
Scala
stringclasses
5 values
Shell
stringclasses
4 values
Swift
stringclasses
13 values
TypeScript
stringlengths
65
20.6k
Make Sum Divisible by P
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.   Example 1: Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: 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. Example 2: Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: 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. Example 3: Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.   Constraints: 1 <= nums.length <= 10 5 1 <= nums[i] <= 10 9 1 <= p <= 10 9
null
null
class Solution { public: int minSubarray(vector<int>& nums, int p) { int k = 0; for (int& x : nums) { k = (k + x) % p; } if (k == 0) { return 0; } unordered_map<int, int> last; last[0] = -1; int n = nums.size(); int ans = n; int cur = 0; for (int i = 0; i < n; ++i) { cur = (cur + nums[i]) % p; int target = (cur - k + p) % p; if (last.count(target)) { ans = min(ans, i - last[target]); } last[cur] = i; } return ans == n ? -1 : ans; } };
null
null
func minSubarray(nums []int, p int) int { k := 0 for _, x := range nums { k = (k + x) % p } if k == 0 { return 0 } last := map[int]int{0: -1} n := len(nums) ans := n cur := 0 for i, x := range nums { cur = (cur + x) % p target := (cur - k + p) % p if j, ok := last[target]; ok { ans = min(ans, i-j) } last[cur] = i } if ans == n { return -1 } return ans }
class Solution { public int minSubarray(int[] nums, int p) { int k = 0; for (int x : nums) { k = (k + x) % p; } if (k == 0) { return 0; } Map<Integer, Integer> last = new HashMap<>(); last.put(0, -1); int n = nums.length; int ans = n; int cur = 0; for (int i = 0; i < n; ++i) { cur = (cur + nums[i]) % p; int target = (cur - k + p) % p; if (last.containsKey(target)) { ans = Math.min(ans, i - last.get(target)); } last.put(cur, i); } return ans == n ? -1 : ans; } }
/** * @param {number[]} nums * @param {number} p * @return {number} */ var minSubarray = function (nums, p) { let k = 0; for (const x of nums) { k = (k + x) % p; } if (k === 0) { return 0; } const last = new Map(); last.set(0, -1); const n = nums.length; let ans = n; let cur = 0; for (let i = 0; i < n; ++i) { cur = (cur + nums[i]) % p; const target = (cur - k + p) % p; if (last.has(target)) { const j = last.get(target); ans = Math.min(ans, i - j); } last.set(cur, i); } return ans === n ? -1 : ans; };
null
null
null
null
null
class Solution: def minSubarray(self, nums: List[int], p: int) -> int: k = sum(nums) % p if k == 0: return 0 last = {0: -1} cur = 0 ans = len(nums) for i, x in enumerate(nums): cur = (cur + x) % p target = (cur - k + p) % p if target in last: ans = min(ans, i - last[target]) last[cur] = i return -1 if ans == len(nums) else ans
null
use std::collections::HashMap; impl Solution { pub fn min_subarray(nums: Vec<i32>, p: i32) -> i32 { let mut k = 0; for &x in &nums { k = (k + x) % p; } if k == 0 { return 0; } let mut last = HashMap::new(); last.insert(0, -1); let n = nums.len(); let mut ans = n as i32; let mut cur = 0; for i in 0..n { cur = (cur + nums[i]) % p; let target = (cur - k + p) % p; if let Some(&prev_idx) = last.get(&target) { ans = ans.min(i as i32 - prev_idx); } last.insert(cur, i as i32); } if ans == n as i32 { -1 } else { ans } } }
null
null
null
function minSubarray(nums: number[], p: number): number { let k = 0; for (const x of nums) { k = (k + x) % p; } if (k === 0) { return 0; } const last = new Map<number, number>(); last.set(0, -1); const n = nums.length; let ans = n; let cur = 0; for (let i = 0; i < n; ++i) { cur = (cur + nums[i]) % p; const target = (cur - k + p) % p; if (last.has(target)) { const j = last.get(target)!; ans = Math.min(ans, i - j); } last.set(cur, i); } return ans === n ? -1 : ans; }
Largest Subarray Length K 🔒
An array A is larger than some array B if for the first index i where A[i] != B[i] , A[i] > B[i] . For example, consider 0 -indexing: [1,3,2,4] > [1,2,2,4] , since at index 1 , 3 > 2 . [1,4,4,4] < [2,1,1,1] , since at index 0 , 1 < 2 . A subarray is a contiguous subsequence of the array. Given an integer array nums of distinct integers, return the largest subarray of nums of length k .   Example 1: Input: nums = [1,4,5,2,3], k = 3 Output: [5,2,3] Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3]. Of these, [5,2,3] is the largest. Example 2: Input: nums = [1,4,5,2,3], k = 4 Output: [4,5,2,3] Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3]. Of these, [4,5,2,3] is the largest. Example 3: Input: nums = [1,4,5,2,3], k = 1 Output: [5]   Constraints: 1 <= k <= nums.length <= 10 5 1 <= nums[i] <= 10 9 All the integers of nums are unique .   Follow up: What if the integers in nums are not distinct?
null
null
class Solution { public: vector<int> largestSubarray(vector<int>& nums, int k) { auto i = max_element(nums.begin(), nums.end() - k + 1); return {i, i + k}; } };
null
null
func largestSubarray(nums []int, k int) []int { j := 0 for i := 1; i < len(nums)-k+1; i++ { if nums[j] < nums[i] { j = i } } return nums[j : j+k] }
class Solution { public int[] largestSubarray(int[] nums, int k) { int j = 0; for (int i = 1; i < nums.length - k + 1; ++i) { if (nums[j] < nums[i]) { j = i; } } return Arrays.copyOfRange(nums, j, j + k); } }
null
null
null
null
null
null
class Solution: def largestSubarray(self, nums: List[int], k: int) -> List[int]: i = nums.index(max(nums[: len(nums) - k + 1])) return nums[i : i + k]
null
impl Solution { pub fn largest_subarray(nums: Vec<i32>, k: i32) -> Vec<i32> { let mut j = 0; for i in 1..=nums.len() - (k as usize) { if nums[i] > nums[j] { j = i; } } nums[j..j + (k as usize)].to_vec() } }
null
null
null
function largestSubarray(nums: number[], k: number): number[] { let j = 0; for (let i = 1; i < nums.length - k + 1; ++i) { if (nums[j] < nums[i]) { j = i; } } return nums.slice(j, j + k); }
Zero Array Transformation II
You are given an integer array nums of length n and a 2D array queries where queries[i] = [l i , r i , val i ] . Each queries[i] represents the following action on nums : Decrement the value at each index in the range [l i , r i ] in nums by at most val i . The amount by which each value is decremented can be chosen independently for each index. A Zero Array is an array with all its elements equal to 0. Return 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.   Example 1: Input: nums = [2,0,2], queries = [[0,2,1],[0,2,1],[1,1,3]] Output: 2 Explanation: For i = 0 (l = 0, r = 2, val = 1): Decrement values at indices [0, 1, 2] by [1, 0, 1] respectively. The array will become [1, 0, 1] . For i = 1 (l = 0, r = 2, val = 1): Decrement values at indices [0, 1, 2] by [1, 0, 1] respectively. The array will become [0, 0, 0] , which is a Zero Array. Therefore, the minimum value of k is 2. Example 2: Input: nums = [4,3,2,1], queries = [[1,3,2],[0,2,1]] Output: -1 Explanation: For i = 0 (l = 1, r = 3, val = 2): Decrement values at indices [1, 2, 3] by [2, 2, 1] respectively. The array will become [4, 1, 0, 0] . For i = 1 (l = 0, r = 2, val = 1): Decrement values at indices [0, 1, 2] by [1, 1, 0] respectively. The array will become [3, 0, 0, 0] , which is not a Zero Array.   Constraints: 1 <= nums.length <= 10 5 0 <= nums[i] <= 5 * 10 5 1 <= queries.length <= 10 5 queries[i].length == 3 0 <= l i <= r i < nums.length 1 <= val i <= 5
null
null
class Solution { public: int minZeroArray(vector<int>& nums, vector<vector<int>>& queries) { int n = nums.size(); int d[n + 1]; int m = queries.size(); int l = 0, r = m + 1; auto check = [&](int k) -> bool { memset(d, 0, sizeof(d)); for (int i = 0; i < k; ++i) { int l = queries[i][0], r = queries[i][1], val = queries[i][2]; d[l] += val; d[r + 1] -= val; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; }; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } };
null
null
func minZeroArray(nums []int, queries [][]int) int { n, m := len(nums), len(queries) l := sort.Search(m+1, func(k int) bool { d := make([]int, n+1) for _, q := range queries[:k] { l, r, val := q[0], q[1], q[2] d[l] += val d[r+1] -= val } s := 0 for i, x := range nums { s += d[i] if x > s { return false } } return true }) if l > m { return -1 } return l }
class Solution { private int n; private int[] nums; private int[][] queries; public int minZeroArray(int[] nums, int[][] queries) { this.nums = nums; this.queries = queries; n = nums.length; int m = queries.length; int l = 0, r = m + 1; while (l < r) { int mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; } private boolean check(int k) { int[] d = new int[n + 1]; for (int i = 0; i < k; ++i) { int l = queries[i][0], r = queries[i][1], val = queries[i][2]; d[l] += val; d[r + 1] -= val; } for (int i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; } }
null
null
null
null
null
null
class Solution: def minZeroArray(self, nums: List[int], queries: List[List[int]]) -> int: def check(k: int) -> bool: d = [0] * (len(nums) + 1) for l, r, val in queries[:k]: d[l] += val d[r + 1] -= val s = 0 for x, y in zip(nums, d): s += y if x > s: return False return True m = len(queries) l = bisect_left(range(m + 1), True, key=check) return -1 if l > m else l
null
impl Solution { pub fn min_zero_array(nums: Vec<i32>, queries: Vec<Vec<i32>>) -> i32 { let n = nums.len(); let m = queries.len(); let mut d: Vec<i64> = vec![0; n + 1]; let (mut l, mut r) = (0_usize, m + 1); let check = |k: usize, d: &mut Vec<i64>| -> bool { d.fill(0); for i in 0..k { let (l, r, val) = ( queries[i][0] as usize, queries[i][1] as usize, queries[i][2] as i64, ); d[l] += val; d[r + 1] -= val; } let mut s: i64 = 0; for i in 0..n { s += d[i]; if nums[i] as i64 > s { return false; } } true }; while l < r { let mid = (l + r) >> 1; if check(mid, &mut d) { r = mid; } else { l = mid + 1; } } if l > m { -1 } else { l as i32 } } }
null
null
null
function minZeroArray(nums: number[], queries: number[][]): number { const [n, m] = [nums.length, queries.length]; const d: number[] = Array(n + 1); let [l, r] = [0, m + 1]; const check = (k: number): boolean => { d.fill(0); for (let i = 0; i < k; ++i) { const [l, r, val] = queries[i]; d[l] += val; d[r + 1] -= val; } for (let i = 0, s = 0; i < n; ++i) { s += d[i]; if (nums[i] > s) { return false; } } return true; }; while (l < r) { const mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } return l > m ? -1 : l; }
Immediate Food Delivery II
Table: Delivery +-----------------------------+---------+ | Column Name | Type | +-----------------------------+---------+ | delivery_id | int | | customer_id | int | | order_date | date | | customer_pref_delivery_date | date | +-----------------------------+---------+ delivery_id is the column of unique values of this table. The 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).   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 . The 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. Write a solution to find the percentage of immediate orders in the first orders of all customers, rounded to 2 decimal places . The result format is in the following example.   Example 1: Input: Delivery table: +-------------+-------------+------------+-----------------------------+ | delivery_id | customer_id | order_date | customer_pref_delivery_date | +-------------+-------------+------------+-----------------------------+ | 1 | 1 | 2019-08-01 | 2019-08-02 | | 2 | 2 | 2019-08-02 | 2019-08-02 | | 3 | 1 | 2019-08-11 | 2019-08-12 | | 4 | 3 | 2019-08-24 | 2019-08-24 | | 5 | 3 | 2019-08-21 | 2019-08-22 | | 6 | 2 | 2019-08-11 | 2019-08-13 | | 7 | 4 | 2019-08-09 | 2019-08-09 | +-------------+-------------+------------+-----------------------------+ Output: +----------------------+ | immediate_percentage | +----------------------+ | 50.00 | +----------------------+ Explanation: The customer id 1 has a first order with delivery id 1 and it is scheduled. The customer id 2 has a first order with delivery id 2 and it is immediate. The customer id 3 has a first order with delivery id 5 and it is scheduled. The customer id 4 has a first order with delivery id 7 and it is immediate. Hence, half the customers have immediate first orders.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below WITH T AS ( SELECT *, RANK() OVER ( PARTITION BY customer_id ORDER BY order_date ) AS rk FROM Delivery ) SELECT ROUND(AVG(order_date = customer_pref_delivery_date) * 100, 2) AS immediate_percentage FROM T WHERE rk = 1;
null
null
null
null
null
null
null
null
null
null
Rearranging Fruits
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: Chose two indices i and j , and swap the i th   fruit of basket1 with the j th  fruit of basket2 . The cost of the swap is min(basket1[i],basket2[j]) . Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets. Return the minimum cost to make both the baskets equal or -1 if impossible.   Example 1: Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2] Output: 1 Explanation: 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. Example 2: Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1] Output: -1 Explanation: It can be shown that it is impossible to make both the baskets equal.   Constraints: basket1.length == basket2.length 1 <= basket1.length <= 10 5 1 <= basket1[i],basket2[i] <= 10 9
null
null
class Solution { public: long long minCost(vector<int>& basket1, vector<int>& basket2) { int n = basket1.size(); unordered_map<int, int> cnt; for (int i = 0; i < n; ++i) { cnt[basket1[i]]++; cnt[basket2[i]]--; } int mi = 1 << 30; vector<int> nums; for (auto& [x, v] : cnt) { if (v % 2) { return -1; } for (int i = abs(v) / 2; i; --i) { nums.push_back(x); } mi = min(mi, x); } ranges::sort(nums); int m = nums.size(); long long ans = 0; for (int i = 0; i < m / 2; ++i) { ans += min(nums[i], mi * 2); } return ans; } };
null
null
func minCost(basket1 []int, basket2 []int) (ans int64) { cnt := map[int]int{} for i, a := range basket1 { cnt[a]++ cnt[basket2[i]]-- } mi := 1 << 30 nums := []int{} for x, v := range cnt { if v%2 != 0 { return -1 } for i := abs(v) / 2; i > 0; i-- { nums = append(nums, x) } mi = min(mi, x) } sort.Ints(nums) m := len(nums) for i := 0; i < m/2; i++ { ans += int64(min(nums[i], mi*2)) } return } func abs(x int) int { if x < 0 { return -x } return x }
class Solution { public long minCost(int[] basket1, int[] basket2) { int n = basket1.length; Map<Integer, Integer> cnt = new HashMap<>(); for (int i = 0; i < n; ++i) { cnt.merge(basket1[i], 1, Integer::sum); cnt.merge(basket2[i], -1, Integer::sum); } int mi = 1 << 30; List<Integer> nums = new ArrayList<>(); for (var e : cnt.entrySet()) { int x = e.getKey(), v = e.getValue(); if (v % 2 != 0) { return -1; } for (int i = Math.abs(v) / 2; i > 0; --i) { nums.add(x); } mi = Math.min(mi, x); } Collections.sort(nums); int m = nums.size(); long ans = 0; for (int i = 0; i < m / 2; ++i) { ans += Math.min(nums.get(i), mi * 2); } return ans; } }
null
null
null
null
null
null
class Solution: def minCost(self, basket1: List[int], basket2: List[int]) -> int: cnt = Counter() for a, b in zip(basket1, basket2): cnt[a] += 1 cnt[b] -= 1 mi = min(cnt) nums = [] for x, v in cnt.items(): if v % 2: return -1 nums.extend([x] * (abs(v) // 2)) nums.sort() m = len(nums) // 2 return sum(min(x, mi * 2) for x in nums[:m])
null
use std::collections::HashMap; impl Solution { pub fn min_cost(basket1: Vec<i32>, basket2: Vec<i32>) -> i64 { let n = basket1.len(); let mut cnt: HashMap<i32, i32> = HashMap::new(); for i in 0..n { *cnt.entry(basket1[i]).or_insert(0) += 1; *cnt.entry(basket2[i]).or_insert(0) -= 1; } let mut mi = i32::MAX; let mut nums = Vec::new(); for (x, v) in cnt { if v % 2 != 0 { return -1; } for _ in 0..(v.abs() / 2) { nums.push(x); } mi = mi.min(x); } nums.sort(); let m = nums.len(); let mut ans = 0; for i in 0..(m / 2) { ans += nums[i].min(mi * 2) as i64; } ans } }
null
null
null
function minCost(basket1: number[], basket2: number[]): number { const n = basket1.length; const cnt: Map<number, number> = new Map(); for (let i = 0; i < n; i++) { cnt.set(basket1[i], (cnt.get(basket1[i]) || 0) + 1); cnt.set(basket2[i], (cnt.get(basket2[i]) || 0) - 1); } let mi = Number.MAX_SAFE_INTEGER; const nums: number[] = []; for (const [x, v] of cnt.entries()) { if (v % 2 !== 0) { return -1; } for (let i = 0; i < Math.abs(v) / 2; i++) { nums.push(x); } mi = Math.min(mi, x); } nums.sort((a, b) => a - b); const m = nums.length; let ans = 0; for (let i = 0; i < m / 2; i++) { ans += Math.min(nums[i], mi * 2); } return ans; }
Minimum Number of Chairs in a Waiting Room
You are given a string s . Simulate events at each second i : If s[i] == 'E' , a person enters the waiting room and takes one of the chairs in it. If 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 .   Example 1: Input: s = "EEEEEEE" Output: 7 Explanation: After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed. Example 2: Input: s = "ELELEEL" Output: 2 Explanation: Let's consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second. Second Event People in the Waiting Room Available Chairs 0 Enter 1 1 1 Leave 0 2 2 Enter 1 1 3 Leave 0 2 4 Enter 1 1 5 Enter 2 0 6 Leave 1 1 Example 3: Input: s = "ELEELEELLL" Output: 3 Explanation: Let's consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second. Second Event People in the Waiting Room Available Chairs 0 Enter 1 2 1 Leave 0 3 2 Enter 1 2 3 Enter 2 1 4 Leave 1 2 5 Enter 2 1 6 Enter 3 0 7 Leave 2 1 8 Leave 1 2 9 Leave 0 3   Constraints: 1 <= s.length <= 50 s consists only of the letters 'E' and 'L' . s represents a valid sequence of entries and exits.
null
null
class Solution { public: int minimumChairs(string s) { int cnt = 0, left = 0; for (char& c : s) { if (c == 'E') { if (left > 0) { --left; } else { ++cnt; } } else { ++left; } } return cnt; } };
null
null
func minimumChairs(s string) int { cnt, left := 0, 0 for _, c := range s { if c == 'E' { if left > 0 { left-- } else { cnt++ } } else { left++ } } return cnt }
class Solution { public int minimumChairs(String s) { int cnt = 0, left = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == 'E') { if (left > 0) { --left; } else { ++cnt; } } else { ++left; } } return cnt; } }
null
null
null
null
null
null
class Solution: def minimumChairs(self, s: str) -> int: cnt = left = 0 for c in s: if c == "E": if left: left -= 1 else: cnt += 1 else: left += 1 return cnt
null
null
null
null
null
function minimumChairs(s: string): number { let [cnt, left] = [0, 0]; for (const c of s) { if (c === 'E') { if (left > 0) { --left; } else { ++cnt; } } else { ++left; } } return cnt; }
Rotate String
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. For example, if s = "abcde" , then it will be "bcdea" after one shift.   Example 1: Input: s = "abcde", goal = "cdeab" Output: true Example 2: Input: s = "abcde", goal = "abced" Output: false   Constraints: 1 <= s.length, goal.length <= 100 s and goal consist of lowercase English letters.
null
null
class Solution { public: bool rotateString(string s, string goal) { return s.size() == goal.size() && strstr((s + s).data(), goal.data()); } };
null
null
func rotateString(s string, goal string) bool { return len(s) == len(goal) && strings.Contains(s+s, goal) }
class Solution { public boolean rotateString(String s, String goal) { return s.length() == goal.length() && (s + s).contains(goal); } }
null
null
null
null
class Solution { /** * @param String $s * @param String $goal * @return Boolean */ function rotateString($s, $goal) { return strlen($goal) === strlen($s) && strpos($s . $s, $goal) !== false; } }
null
class Solution: def rotateString(self, s: str, goal: str) -> bool: return len(s) == len(goal) and goal in s + s
null
impl Solution { pub fn rotate_string(s: String, goal: String) -> bool { s.len() == goal.len() && (s.clone() + &s).contains(&goal) } }
null
null
null
function rotateString(s: string, goal: string): boolean { return s.length === goal.length && (goal + goal).includes(s); }
Kth Smallest Product of Two Sorted Arrays
Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k , return the k th ( 1-based ) smallest product of nums1[i] \* nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length .   Example 1: Input: nums1 = [2,5], nums2 = [3,4], k = 2 Output: 8 Explanation: The 2 smallest products are: - nums1[0] * nums2[0] = 2 * 3 = 6 - nums1[0] * nums2[1] = 2 * 4 = 8 The 2 nd smallest product is 8. Example 2: Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6 Output: 0 Explanation: The 6 smallest products are: - nums1[0] * nums2[1] = (-4) * 4 = -16 - nums1[0] * nums2[0] = (-4) * 2 = -8 - nums1[1] * nums2[1] = (-2) * 4 = -8 - nums1[1] * nums2[0] = (-2) * 2 = -4 - nums1[2] * nums2[0] = 0 * 2 = 0 - nums1[2] * nums2[1] = 0 * 4 = 0 The 6 th smallest product is 0. Example 3: Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3 Output: -6 Explanation: The 3 smallest products are: - nums1[0] * nums2[4] = (-2) * 5 = -10 - nums1[0] * nums2[3] = (-2) * 4 = -8 - nums1[4] * nums2[0] = 2 * (-3) = -6 The 3 rd smallest product is -6.   Constraints: 1 <= nums1.length, nums2.length <= 5 * 10 4 -10 5 <= nums1[i], nums2[j] <= 10 5 1 <= k <= nums1.length * nums2.length nums1 and nums2 are sorted.
null
null
class Solution { public: long long kthSmallestProduct(vector<int>& nums1, vector<int>& nums2, long long k) { int m = nums1.size(), n = nums2.size(); int a = max(abs(nums1[0]), abs(nums1[m - 1])); int b = max(abs(nums2[0]), abs(nums2[n - 1])); long long r = 1LL * a * b; long long l = -r; auto count = [&](long long p) { long long cnt = 0; for (int x : nums1) { if (x > 0) { int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if (1LL * x * nums2[mid] > p) { r = mid; } else { l = mid + 1; } } cnt += l; } else if (x < 0) { int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if (1LL * x * nums2[mid] <= p) { r = mid; } else { l = mid + 1; } } cnt += n - l; } else if (p >= 0) { cnt += n; } } return cnt; }; while (l < r) { long long mid = (l + r) >> 1; if (count(mid) >= k) { r = mid; } else { l = mid + 1; } } return l; } };
null
null
func kthSmallestProduct(nums1 []int, nums2 []int, k int64) int64 { m := len(nums1) n := len(nums2) a := max(abs(nums1[0]), abs(nums1[m-1])) b := max(abs(nums2[0]), abs(nums2[n-1])) r := int64(a) * int64(b) l := -r count := func(p int64) int64 { var cnt int64 for _, x := range nums1 { if x > 0 { l, r := 0, n for l < r { mid := (l + r) >> 1 if int64(x)*int64(nums2[mid]) > p { r = mid } else { l = mid + 1 } } cnt += int64(l) } else if x < 0 { l, r := 0, n for l < r { mid := (l + r) >> 1 if int64(x)*int64(nums2[mid]) <= p { r = mid } else { l = mid + 1 } } cnt += int64(n - l) } else if p >= 0 { cnt += int64(n) } } return cnt } for l < r { mid := (l + r) >> 1 if count(mid) >= k { r = mid } else { l = mid + 1 } } return l } func abs(x int) int { if x < 0 { return -x } return x }
class Solution { private int[] nums1; private int[] nums2; public long kthSmallestProduct(int[] nums1, int[] nums2, long k) { this.nums1 = nums1; this.nums2 = nums2; int m = nums1.length; int n = nums2.length; int a = Math.max(Math.abs(nums1[0]), Math.abs(nums1[m - 1])); int b = Math.max(Math.abs(nums2[0]), Math.abs(nums2[n - 1])); long r = (long) a * b; long l = (long) -a * b; while (l < r) { long mid = (l + r) >> 1; if (count(mid) >= k) { r = mid; } else { l = mid + 1; } } return l; } private long count(long p) { long cnt = 0; int n = nums2.length; for (int x : nums1) { if (x > 0) { int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if ((long) x * nums2[mid] > p) { r = mid; } else { l = mid + 1; } } cnt += l; } else if (x < 0) { int l = 0, r = n; while (l < r) { int mid = (l + r) >> 1; if ((long) x * nums2[mid] <= p) { r = mid; } else { l = mid + 1; } } cnt += n - l; } else if (p >= 0) { cnt += n; } } return cnt; } }
null
null
null
null
null
null
class Solution: def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int: def count(p: int) -> int: cnt = 0 n = len(nums2) for x in nums1: if x > 0: cnt += bisect_right(nums2, p / x) elif x < 0: cnt += n - bisect_left(nums2, p / x) else: cnt += n * int(p >= 0) return cnt mx = max(abs(nums1[0]), abs(nums1[-1])) * max(abs(nums2[0]), abs(nums2[-1])) return bisect_left(range(-mx, mx + 1), k, key=count) - mx
null
impl Solution { pub fn kth_smallest_product(nums1: Vec<i32>, nums2: Vec<i32>, k: i64) -> i64 { let m = nums1.len(); let n = nums2.len(); let a = nums1[0].abs().max(nums1[m - 1].abs()) as i64; let b = nums2[0].abs().max(nums2[n - 1].abs()) as i64; let mut l = -a * b; let mut r = a * b; let count = |p: i64| -> i64 { let mut cnt = 0i64; for &x in &nums1 { if x > 0 { let mut left = 0; let mut right = n; while left < right { let mid = (left + right) / 2; if (x as i64) * (nums2[mid] as i64) > p { right = mid; } else { left = mid + 1; } } cnt += left as i64; } else if x < 0 { let mut left = 0; let mut right = n; while left < right { let mid = (left + right) / 2; if (x as i64) * (nums2[mid] as i64) <= p { right = mid; } else { left = mid + 1; } } cnt += (n - left) as i64; } else if p >= 0 { cnt += n as i64; } } cnt }; while l < r { let mid = l + (r - l) / 2; if count(mid) >= k { r = mid; } else { l = mid + 1; } } l } }
null
null
null
function kthSmallestProduct(nums1: number[], nums2: number[], k: number): number { const m = nums1.length; const n = nums2.length; const a = BigInt(Math.max(Math.abs(nums1[0]), Math.abs(nums1[m - 1]))); const b = BigInt(Math.max(Math.abs(nums2[0]), Math.abs(nums2[n - 1]))); let l = -a * b; let r = a * b; const count = (p: bigint): bigint => { let cnt = 0n; for (const x of nums1) { const bx = BigInt(x); if (bx > 0n) { let l = 0, r = n; while (l < r) { const mid = (l + r) >> 1; const prod = bx * BigInt(nums2[mid]); if (prod > p) { r = mid; } else { l = mid + 1; } } cnt += BigInt(l); } else if (bx < 0n) { let l = 0, r = n; while (l < r) { const mid = (l + r) >> 1; const prod = bx * BigInt(nums2[mid]); if (prod <= p) { r = mid; } else { l = mid + 1; } } cnt += BigInt(n - l); } else if (p >= 0n) { cnt += BigInt(n); } } return cnt; }; while (l < r) { const mid = (l + r) >> 1n; if (count(mid) >= BigInt(k)) { r = mid; } else { l = mid + 1n; } } return Number(l); }
Before and After Puzzle 🔒
Given a list of phrases , generate a list of Before and After puzzles. A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start or the end of a phrase. There are no consecutive spaces in a phrase. Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase is the same as the first word of the second phrase . Return the Before and After puzzles that can be formed by every two phrases  phrases[i]  and  phrases[j]  where  i != j . Note that the order of matching two phrases matters, we want to consider both orders. You should return a list of  distinct  strings sorted lexicographically .   Example 1: Input: phrases = ["writing code","code rocks"] Output: ["writing code rocks"] Example 2: Input: phrases = ["mission statement", "a quick bite to eat",   "a chip off the old block",   "chocolate bar",   "mission impossible",   "a man on a mission",   "block party",   "eat my words",   "bar of soap"] Output: ["a chip off the old block party",   "a man on a mission impossible",   "a man on a mission statement",   "a quick bite to eat my words", "chocolate bar of soap"] Example 3: Input: phrases = ["a","b","a"] Output: ["a"]   Constraints: 1 <= phrases.length <= 100 1 <= phrases[i].length <= 100
null
null
class Solution { public: vector<string> beforeAndAfterPuzzles(vector<string>& phrases) { int n = phrases.size(); pair<string, string> ps[n]; for (int i = 0; i < n; ++i) { int j = phrases[i].find(' '); if (j == string::npos) { ps[i] = {phrases[i], phrases[i]}; } else { int k = phrases[i].rfind(' '); ps[i] = {phrases[i].substr(0, j), phrases[i].substr(k + 1)}; } } unordered_set<string> s; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i != j && ps[i].second == ps[j].first) { s.insert(phrases[i] + phrases[j].substr(ps[i].second.size())); } } } vector<string> ans(s.begin(), s.end()); sort(ans.begin(), ans.end()); return ans; } };
null
null
func beforeAndAfterPuzzles(phrases []string) []string { n := len(phrases) ps := make([][2]string, n) for i, p := range phrases { ws := strings.Split(p, " ") ps[i] = [2]string{ws[0], ws[len(ws)-1]} } s := map[string]bool{} for i := 0; i < n; i++ { for j := 0; j < n; j++ { if i != j && ps[i][1] == ps[j][0] { s[phrases[i]+phrases[j][len(ps[j][0]):]] = true } } } ans := make([]string, 0, len(s)) for k := range s { ans = append(ans, k) } sort.Strings(ans) return ans }
class Solution { public List<String> beforeAndAfterPuzzles(String[] phrases) { int n = phrases.length; var ps = new String[n][]; for (int i = 0; i < n; ++i) { var ws = phrases[i].split(" "); ps[i] = new String[] {ws[0], ws[ws.length - 1]}; } Set<String> s = new HashSet<>(); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i != j && ps[i][1].equals(ps[j][0])) { s.add(phrases[i] + phrases[j].substring(ps[j][0].length())); } } } var ans = new ArrayList<>(s); Collections.sort(ans); return ans; } }
null
null
null
null
null
null
class Solution: def beforeAndAfterPuzzles(self, phrases: List[str]) -> List[str]: ps = [] for p in phrases: ws = p.split() ps.append((ws[0], ws[-1])) n = len(ps) ans = [] for i in range(n): for j in range(n): if i != j and ps[i][1] == ps[j][0]: ans.append(phrases[i] + phrases[j][len(ps[j][0]) :]) return sorted(set(ans))
null
null
null
null
null
function beforeAndAfterPuzzles(phrases: string[]): string[] { const ps: string[][] = []; for (const p of phrases) { const ws = p.split(' '); ps.push([ws[0], ws[ws.length - 1]]); } const n = ps.length; const s: Set<string> = new Set(); for (let i = 0; i < n; ++i) { for (let j = 0; j < n; ++j) { if (i !== j && ps[i][1] === ps[j][0]) { s.add(`${phrases[i]}${phrases[j].substring(ps[j][0].length)}`); } } } return [...s].sort(); }
Lowest Common Ancestor of a Binary Tree III 🔒
Given two nodes of a binary tree p and q , return their lowest common ancestor (LCA) . Each node will have a reference to its parent node. The definition for Node is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the definition of LCA on Wikipedia : "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself )."   Example 1: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The LCA of nodes 5 and 1 is 3. Example 2: Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. Example 3: Input: root = [1,2], p = 1, q = 2 Output: 1   Constraints: The number of nodes in the tree is in the range [2, 10 5 ] . -10 9 <= Node.val <= 10 9 All Node.val are unique . p != q p and q exist in the tree.
null
null
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* parent; }; */ class Solution { public: Node* lowestCommonAncestor(Node* p, Node* q) { Node* a = p; Node* b = q; while (a != b) { a = a->parent ? a->parent : q; b = b->parent ? b->parent : p; } return a; } };
null
null
/** * Definition for Node. * type Node struct { * Val int * Left *Node * Right *Node * Parent *Node * } */ func lowestCommonAncestor(p *Node, q *Node) *Node { a, b := p, q for a != b { if a.Parent != nil { a = a.Parent } else { a = q } if b.Parent != nil { b = b.Parent } else { b = p } } return a }
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node parent; }; */ class Solution { public Node lowestCommonAncestor(Node p, Node q) { Node a = p, b = q; while (a != b) { a = a.parent == null ? q : a.parent; b = b.parent == null ? p : b.parent; } return a; } }
null
null
null
null
null
null
""" # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None """ class Solution: def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node': a, b = p, q while a != b: a = a.parent if a.parent else q b = b.parent if b.parent else p return a
null
null
null
null
null
/** * Definition for a binary tree node. * class Node { * val: number * left: Node | null * right: Node | null * parent: Node | null * constructor(val?: number, left?: Node | null, right?: Node | null, parent?: Node | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * this.parent = (parent===undefined ? null : parent) * } * } */ function lowestCommonAncestor(p: Node | null, q: Node | null): Node | null { let [a, b] = [p, q]; while (a != b) { a = a.parent ?? q; b = b.parent ?? p; } return a; }
Letter Tile Possibilities
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 .   Example 1: Input: tiles = "AAB" Output: 8 Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA". Example 2: Input: tiles = "AAABBC" Output: 188 Example 3: Input: tiles = "V" Output: 1   Constraints: 1 <= tiles.length <= 7 tiles consists of uppercase English letters.
null
null
class Solution { public: int numTilePossibilities(string tiles) { int cnt[26]{}; for (char c : tiles) { ++cnt[c - 'A']; } function<int(int* cnt)> dfs = [&](int* cnt) -> int { int res = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { ++res; --cnt[i]; res += dfs(cnt); ++cnt[i]; } } return res; }; return dfs(cnt); } };
null
null
func numTilePossibilities(tiles string) int { cnt := [26]int{} for _, c := range tiles { cnt[c-'A']++ } var dfs func(cnt [26]int) int dfs = func(cnt [26]int) (res int) { for i, x := range cnt { if x > 0 { res++ cnt[i]-- res += dfs(cnt) cnt[i]++ } } return } return dfs(cnt) }
class Solution { public int numTilePossibilities(String tiles) { int[] cnt = new int[26]; for (char c : tiles.toCharArray()) { ++cnt[c - 'A']; } return dfs(cnt); } private int dfs(int[] cnt) { int res = 0; for (int i = 0; i < cnt.length; ++i) { if (cnt[i] > 0) { ++res; --cnt[i]; res += dfs(cnt); ++cnt[i]; } } return res; } }
null
null
null
null
null
null
class Solution: def numTilePossibilities(self, tiles: str) -> int: def dfs(cnt: Counter) -> int: ans = 0 for i, x in cnt.items(): if x > 0: ans += 1 cnt[i] -= 1 ans += dfs(cnt) cnt[i] += 1 return ans cnt = Counter(tiles) return dfs(cnt)
null
null
null
null
null
function numTilePossibilities(tiles: string): number { const cnt: number[] = new Array(26).fill(0); for (const c of tiles) { ++cnt[c.charCodeAt(0) - 'A'.charCodeAt(0)]; } const dfs = (cnt: number[]): number => { let res = 0; for (let i = 0; i < 26; ++i) { if (cnt[i] > 0) { ++res; --cnt[i]; res += dfs(cnt); ++cnt[i]; } } return res; }; return dfs(cnt); }
Most Popular Video Creator
You are given two string arrays creators and ids , and an integer array views , all of length n . The i th 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. If multiple creators have the highest popularity, find all of them. If multiple videos have the highest view count for a creator, find the lexicographically smallest id. Note: 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] = [creators i , id i ] means that creators i has the highest popularity and id i is the id of their most popular video. The answer can be returned in any order.   Example 1: Input: creators = ["alice","bob","alice","chris"], ids = ["one","two","three","four"], views = [5,10,5,4] Output: [["alice","one"],["bob","two"]] Explanation: The popularity of alice is 5 + 5 = 10. The popularity of bob is 10. The popularity of chris is 4. alice and bob are the most popular creators. For bob, the video with the highest view count is "two". For 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: Input: creators = ["alice","alice","alice"], ids = ["a","b","c"], views = [1,2,2] Output: [["alice","b"]] Explanation: The videos with id "b" and "c" have the highest view count. Since "b" is lexicographically smaller than "c", it is included in the answer.   Constraints: n == creators.length == ids.length == views.length 1 <= n <= 10 5 1 <= creators[i].length, ids[i].length <= 5 creators[i] and ids[i] consist only of lowercase English letters. 0 <= views[i] <= 10 5
null
null
class Solution { public: vector<vector<string>> mostPopularCreator(vector<string>& creators, vector<string>& ids, vector<int>& views) { unordered_map<string, long long> cnt; unordered_map<string, int> d; int n = ids.size(); for (int k = 0; k < n; ++k) { auto c = creators[k], id = ids[k]; int v = views[k]; cnt[c] += v; if (!d.count(c) || views[d[c]] < v || (views[d[c]] == v && ids[d[c]] > id)) { d[c] = k; } } long long mx = 0; for (auto& [_, x] : cnt) { mx = max(mx, x); } vector<vector<string>> ans; for (auto& [c, x] : cnt) { if (x == mx) { ans.push_back({c, ids[d[c]]}); } } return ans; } };
null
null
func mostPopularCreator(creators []string, ids []string, views []int) (ans [][]string) { cnt := map[string]int{} d := map[string]int{} for k, c := range creators { i, v := ids[k], views[k] cnt[c] += v if j, ok := d[c]; !ok || views[j] < v || (views[j] == v && ids[j] > i) { d[c] = k } } mx := 0 for _, x := range cnt { if mx < x { mx = x } } for c, x := range cnt { if x == mx { ans = append(ans, []string{c, ids[d[c]]}) } } return }
class Solution { public List<List<String>> mostPopularCreator(String[] creators, String[] ids, int[] views) { int n = ids.length; Map<String, Long> cnt = new HashMap<>(n); Map<String, Integer> d = new HashMap<>(n); for (int k = 0; k < n; ++k) { String c = creators[k], i = ids[k]; long v = views[k]; cnt.merge(c, v, Long::sum); if (!d.containsKey(c) || views[d.get(c)] < v || (views[d.get(c)] == v && ids[d.get(c)].compareTo(i) > 0)) { d.put(c, k); } } long mx = 0; for (long x : cnt.values()) { mx = Math.max(mx, x); } List<List<String>> ans = new ArrayList<>(); for (var e : cnt.entrySet()) { if (e.getValue() == mx) { String c = e.getKey(); ans.add(List.of(c, ids[d.get(c)])); } } return ans; } }
null
null
null
null
null
null
class Solution: def mostPopularCreator( self, creators: List[str], ids: List[str], views: List[int] ) -> List[List[str]]: cnt = defaultdict(int) d = defaultdict(int) for k, (c, i, v) in enumerate(zip(creators, ids, views)): cnt[c] += v if c not in d or views[d[c]] < v or (views[d[c]] == v and ids[d[c]] > i): d[c] = k mx = max(cnt.values()) return [[c, ids[d[c]]] for c, x in cnt.items() if x == mx]
null
null
null
null
null
function mostPopularCreator(creators: string[], ids: string[], views: number[]): string[][] { const cnt: Map<string, number> = new Map(); const d: Map<string, number> = new Map(); const n = ids.length; for (let k = 0; k < n; ++k) { const [c, i, v] = [creators[k], ids[k], views[k]]; cnt.set(c, (cnt.get(c) ?? 0) + v); if (!d.has(c) || views[d.get(c)!] < v || (views[d.get(c)!] === v && ids[d.get(c)!] > i)) { d.set(c, k); } } const mx = Math.max(...cnt.values()); const ans: string[][] = []; for (const [c, x] of cnt) { if (x === mx) { ans.push([c, ids[d.get(c)!]]); } } return ans; }
Shortest Impossible Sequence of Rolls
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 i th 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.   Example 1: Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4 Output: 3 Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls. Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls. The sequence [1, 4, 2] cannot be taken from rolls, so we return 3. Note that there are other sequences that cannot be taken from rolls. Example 2: Input: rolls = [1,1,2,2], k = 2 Output: 2 Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls. The sequence [2, 1] cannot be taken from rolls, so we return 2. Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest. Example 3: Input: rolls = [1,1,3,2,2,2,3,3], k = 4 Output: 1 Explanation: The sequence [4] cannot be taken from rolls, so we return 1. Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.   Constraints: n == rolls.length 1 <= n <= 10 5 1 <= rolls[i] <= k <= 10 5
null
null
class Solution { public: int shortestSequence(vector<int>& rolls, int k) { unordered_set<int> s; int ans = 1; for (int v : rolls) { s.insert(v); if (s.size() == k) { s.clear(); ++ans; } } return ans; } };
null
null
func shortestSequence(rolls []int, k int) int { s := map[int]bool{} ans := 1 for _, v := range rolls { s[v] = true if len(s) == k { ans++ s = map[int]bool{} } } return ans }
class Solution { public int shortestSequence(int[] rolls, int k) { Set<Integer> s = new HashSet<>(); int ans = 1; for (int v : rolls) { s.add(v); if (s.size() == k) { s.clear(); ++ans; } } return ans; } }
null
null
null
null
null
null
class Solution: def shortestSequence(self, rolls: List[int], k: int) -> int: ans = 1 s = set() for v in rolls: s.add(v) if len(s) == k: ans += 1 s.clear() return ans
null
null
null
null
null
null
Product's Worth Over Invoices 🔒
Table: Product +-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | name | varchar | +-------------+---------+ product_id is the column with unique values for this table. This table contains the ID and the name of the product. The name consists of only lowercase English letters. No two products have the same name.   Table: Invoice +-------------+------+ | Column Name | Type | +-------------+------+ | invoice_id | int | | product_id | int | | rest | int | | paid | int | | canceled | int | | refunded | int | +-------------+------+ invoice_id is the column with unique values for this table and the id of this invoice. product_id is the id of the product for this invoice. rest is the amount left to pay for this invoice. paid is the amount paid for this invoice. canceled is the amount canceled for this invoice. refunded is the amount refunded for this invoice.   Write a solution that will, for all products, return each product name with the total amount due, paid, canceled, and refunded across all invoices. Return the result table ordered by product_name . The result format is in the following example.   Example 1: Input: Product table: +------------+-------+ | product_id | name | +------------+-------+ | 0 | ham | | 1 | bacon | +------------+-------+ Invoice table: +------------+------------+------+------+----------+----------+ | invoice_id | product_id | rest | paid | canceled | refunded | +------------+------------+------+------+----------+----------+ | 23 | 0 | 2 | 0 | 5 | 0 | | 12 | 0 | 0 | 4 | 0 | 3 | | 1 | 1 | 1 | 1 | 0 | 1 | | 2 | 1 | 1 | 0 | 1 | 1 | | 3 | 1 | 0 | 1 | 1 | 1 | | 4 | 1 | 1 | 1 | 1 | 0 | +------------+------------+------+------+----------+----------+ Output: +-------+------+------+----------+----------+ | name | rest | paid | canceled | refunded | +-------+------+------+----------+----------+ | bacon | 3 | 3 | 3 | 3 | | ham | 2 | 4 | 5 | 3 | +-------+------+------+----------+----------+ Explanation: - The amount of money left to pay for bacon is 1 + 1 + 0 + 1 = 3 - The amount of money paid for bacon is 1 + 0 + 1 + 1 = 3 - The amount of money canceled for bacon is 0 + 1 + 1 + 1 = 3 - The amount of money refunded for bacon is 1 + 1 + 1 + 0 = 3 - The amount of money left to pay for ham is 2 + 0 = 2 - The amount of money paid for ham is 0 + 4 = 4 - The amount of money canceled for ham is 5 + 0 = 5 - The amount of money refunded for ham is 0 + 3 = 3
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT name, IFNULL(SUM(rest), 0) AS rest, IFNULL(SUM(paid), 0) AS paid, IFNULL(SUM(canceled), 0) AS canceled, IFNULL(SUM(refunded), 0) AS refunded FROM Product LEFT JOIN Invoice USING (product_id) GROUP BY product_id ORDER BY name;
null
null
null
null
null
null
null
null
null
null
Number of Valid Clock Times
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 .   Example 1: Input: time = "?5:00" Output: 2 Explanation: 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. Example 2: Input: time = "0?:0?" Output: 100 Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices. Example 3: Input: time = "??:??" Output: 1440 Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.   Constraints: time is a valid string of length 5 in the format "hh:mm" . "00" <= hh <= "23" "00" <= mm <= "59" Some of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9 .
null
null
class Solution { public: int countTime(string time) { auto f = [](string s, int m) { int cnt = 0; for (int i = 0; i < m; ++i) { bool a = s[0] == '?' || s[0] - '0' == i / 10; bool b = s[1] == '?' || s[1] - '0' == i % 10; cnt += a && b; } return cnt; }; return f(time.substr(0, 2), 24) * f(time.substr(3, 2), 60); } };
null
null
func countTime(time string) int { f := func(s string, m int) (cnt int) { for i := 0; i < m; i++ { a := s[0] == '?' || int(s[0]-'0') == i/10 b := s[1] == '?' || int(s[1]-'0') == i%10 if a && b { cnt++ } } return } return f(time[:2], 24) * f(time[3:], 60) }
class Solution { public int countTime(String time) { return f(time.substring(0, 2), 24) * f(time.substring(3), 60); } private int f(String s, int m) { int cnt = 0; for (int i = 0; i < m; ++i) { boolean a = s.charAt(0) == '?' || s.charAt(0) - '0' == i / 10; boolean b = s.charAt(1) == '?' || s.charAt(1) - '0' == i % 10; cnt += a && b ? 1 : 0; } return cnt; } }
null
null
null
null
null
null
class Solution: def countTime(self, time: str) -> int: def f(s: str, m: int) -> int: cnt = 0 for i in range(m): a = s[0] == '?' or (int(s[0]) == i // 10) b = s[1] == '?' or (int(s[1]) == i % 10) cnt += a and b return cnt return f(time[:2], 24) * f(time[3:], 60)
null
impl Solution { pub fn count_time(time: String) -> i32 { let f = |s: &str, m: usize| -> i32 { let mut cnt = 0; let first = s.chars().nth(0).unwrap(); let second = s.chars().nth(1).unwrap(); for i in 0..m { let a = first == '?' || (first.to_digit(10).unwrap() as usize) == i / 10; let b = second == '?' || (second.to_digit(10).unwrap() as usize) == i % 10; if a && b { cnt += 1; } } cnt }; f(&time[..2], 24) * f(&time[3..], 60) } }
null
null
null
function countTime(time: string): number { const f = (s: string, m: number): number => { let cnt = 0; for (let i = 0; i < m; ++i) { const a = s[0] === '?' || s[0] === Math.floor(i / 10).toString(); const b = s[1] === '?' || s[1] === (i % 10).toString(); if (a && b) { ++cnt; } } return cnt; }; return f(time.slice(0, 2), 24) * f(time.slice(3), 60); }
Maximum Number of Moves to Kill All Pawns
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] = [x i , y i ] 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: The player selects a pawn that still exists on the board and captures it with the knight in the fewest possible moves . Note that the player can select any pawn, it might not be one that can be captured in the least number of moves. In the process of capturing the selected pawn, the knight may pass other pawns without capturing them . Only the selected pawn can be captured in this turn. Alice 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. Return the maximum total number of moves made during the game that Alice can achieve, assuming both players play optimally . Note 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.   Example 1: Input: kx = 1, ky = 1, positions = [[0,0]] Output: 4 Explanation: The knight takes 4 moves to reach the pawn at (0, 0) . Example 2: Input: kx = 0, ky = 2, positions = [[1,1],[2,2],[3,3]] Output: 8 Explanation: Alice picks the pawn at (2, 2) and captures it in two moves: (0, 2) -> (1, 4) -> (2, 2) . Bob picks the pawn at (3, 3) and captures it in two moves: (2, 2) -> (4, 1) -> (3, 3) . Alice picks the pawn at (1, 1) and captures it in four moves: (3, 3) -> (4, 1) -> (2, 2) -> (0, 3) -> (1, 1) . Example 3: Input: kx = 0, ky = 0, positions = [[1,2],[2,4]] Output: 3 Explanation: Alice picks the pawn at (2, 4) and captures it in two moves: (0, 0) -> (1, 2) -> (2, 4) . Note that the pawn at (1, 2) is not captured. Bob picks the pawn at (1, 2) and captures it in one move: (2, 4) -> (1, 2) .   Constraints: 0 <= kx, ky <= 49 1 <= positions.length <= 15 positions[i].length == 2 0 <= positions[i][0], positions[i][1] <= 49 All positions[i] are unique. The input is generated such that positions[i] != [kx, ky] for all 0 <= i < positions.length .
null
null
class Solution { public: int maxMoves(int kx, int ky, vector<vector<int>>& positions) { int n = positions.size(); const int m = 50; const int dx[8] = {1, 1, 2, 2, -1, -1, -2, -2}; const int dy[8] = {2, -2, 1, -1, 2, -2, 1, -1}; int dist[n + 1][m][m]; memset(dist, -1, sizeof(dist)); for (int i = 0; i <= n; ++i) { int x = (i < n) ? positions[i][0] : kx; int y = (i < n) ? positions[i][1] : ky; queue<pair<int, int>> q; q.push({x, y}); dist[i][x][y] = 0; for (int step = 1; !q.empty(); ++step) { for (int k = q.size(); k > 0; --k) { auto [x1, y1] = q.front(); q.pop(); for (int j = 0; j < 8; ++j) { int x2 = x1 + dx[j], y2 = y1 + dy[j]; if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == -1) { dist[i][x2][y2] = step; q.push({x2, y2}); } } } } } int f[n + 1][1 << n][2]; memset(f, -1, sizeof(f)); auto dfs = [&](this auto&& dfs, int last, int state, int k) -> int { if (state == 0) { return 0; } if (f[last][state][k] != -1) { return f[last][state][k]; } int res = (k == 1) ? 0 : INT_MAX; for (int i = 0; i < positions.size(); ++i) { int x = positions[i][0], y = positions[i][1]; if ((state >> i) & 1) { int t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y]; if (k == 1) { res = max(res, t); } else { res = min(res, t); } } } return f[last][state][k] = res; }; return dfs(n, (1 << n) - 1, 1); } };
null
null
func maxMoves(kx int, ky int, positions [][]int) int { n := len(positions) const m = 50 dx := []int{1, 1, 2, 2, -1, -1, -2, -2} dy := []int{2, -2, 1, -1, 2, -2, 1, -1} dist := make([][][]int, n+1) for i := range dist { dist[i] = make([][]int, m) for j := range dist[i] { dist[i][j] = make([]int, m) for k := range dist[i][j] { dist[i][j][k] = -1 } } } for i := 0; i <= n; i++ { x := kx y := ky if i < n { x = positions[i][0] y = positions[i][1] } q := [][2]int{[2]int{x, y}} dist[i][x][y] = 0 for step := 1; len(q) > 0; step++ { for k := len(q); k > 0; k-- { p := q[0] q = q[1:] x1, y1 := p[0], p[1] for j := 0; j < 8; j++ { x2 := x1 + dx[j] y2 := y1 + dy[j] if x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == -1 { dist[i][x2][y2] = step q = append(q, [2]int{x2, y2}) } } } } } f := make([][][]int, n+1) for i := range f { f[i] = make([][]int, 1<<n) for j := range f[i] { f[i][j] = make([]int, 2) for k := range f[i][j] { f[i][j][k] = -1 } } } var dfs func(last, state, k int) int dfs = func(last, state, k int) int { if state == 0 { return 0 } if f[last][state][k] != -1 { return f[last][state][k] } var res int if k == 0 { res = math.MaxInt32 } for i, p := range positions { x, y := p[0], p[1] if (state>>i)&1 == 1 { t := dfs(i, state^(1<<i), k^1) + dist[last][x][y] if k == 1 { res = max(res, t) } else { res = min(res, t) } } } f[last][state][k] = res return res } return dfs(n, (1<<n)-1, 1) }
class Solution { private Integer[][][] f; private Integer[][][] dist; private int[][] positions; private final int[] dx = {1, 1, 2, 2, -1, -1, -2, -2}; private final int[] dy = {2, -2, 1, -1, 2, -2, 1, -1}; public int maxMoves(int kx, int ky, int[][] positions) { int n = positions.length; final int m = 50; dist = new Integer[n + 1][m][m]; this.positions = positions; for (int i = 0; i <= n; ++i) { int x = i < n ? positions[i][0] : kx; int y = i < n ? positions[i][1] : ky; Deque<int[]> q = new ArrayDeque<>(); q.offer(new int[] {x, y}); for (int step = 1; !q.isEmpty(); ++step) { for (int k = q.size(); k > 0; --k) { var p = q.poll(); int x1 = p[0], y1 = p[1]; for (int j = 0; j < 8; ++j) { int x2 = x1 + dx[j], y2 = y1 + dy[j]; if (x2 >= 0 && x2 < m && y2 >= 0 && y2 < m && dist[i][x2][y2] == null) { dist[i][x2][y2] = step; q.offer(new int[] {x2, y2}); } } } } } f = new Integer[n + 1][1 << n][2]; return dfs(n, (1 << n) - 1, 1); } private int dfs(int last, int state, int k) { if (state == 0) { return 0; } if (f[last][state][k] != null) { return f[last][state][k]; } int res = k == 1 ? 0 : Integer.MAX_VALUE; for (int i = 0; i < positions.length; ++i) { int x = positions[i][0], y = positions[i][1]; if ((state >> i & 1) == 1) { int t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y]; res = k == 1 ? Math.max(res, t) : Math.min(res, t); } } return f[last][state][k] = res; } }
null
null
null
null
null
null
class Solution: def maxMoves(self, kx: int, ky: int, positions: List[List[int]]) -> int: @cache def dfs(last: int, state: int, k: int) -> int: if state == 0: return 0 if k: res = 0 for i, (x, y) in enumerate(positions): if state >> i & 1: t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y] if res < t: res = t return res else: res = inf for i, (x, y) in enumerate(positions): if state >> i & 1: t = dfs(i, state ^ (1 << i), k ^ 1) + dist[last][x][y] if res > t: res = t return res n = len(positions) m = 50 dist = [[[-1] * m for _ in range(m)] for _ in range(n + 1)] dx = [1, 1, 2, 2, -1, -1, -2, -2] dy = [2, -2, 1, -1, 2, -2, 1, -1] positions.append([kx, ky]) for i, (x, y) in enumerate(positions): dist[i][x][y] = 0 q = deque([(x, y)]) step = 0 while q: step += 1 for _ in range(len(q)): x1, y1 = q.popleft() for j in range(8): x2, y2 = x1 + dx[j], y1 + dy[j] if 0 <= x2 < m and 0 <= y2 < m and dist[i][x2][y2] == -1: dist[i][x2][y2] = step q.append((x2, y2)) ans = dfs(n, (1 << n) - 1, 1) dfs.cache_clear() return ans
null
null
null
null
null
null
Number of Students Unable to Eat Lunch
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: If the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue. Otherwise, they will leave it and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i ​​​​​​th sandwich in the stack ( i = 0 is the top of the stack) and students[j] is the preference of the j ​​​​​​th student in the initial queue ( j = 0 is the front of the queue). Return the number of students that are unable to eat.   Example 1: Input: students = [1,1,0,0], sandwiches = [0,1,0,1] Output: 0 Explanation: - Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1]. - Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0]. - Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1]. - Front student leaves the top sandwich and returns to the end of the line making students = [0,1]. - Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1]. - Front student takes the top sandwich and leaves the line making students = [] and sandwiches = []. Hence all students are able to eat. Example 2: Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1] Output: 3   Constraints: 1 <= students.length, sandwiches.length <= 100 students.length == sandwiches.length sandwiches[i] is 0 or 1 . students[i] is 0 or 1 .
int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize) { int count[2] = {0}; for (int i = 0; i < studentsSize; i++) { count[students[i]]++; } for (int i = 0; i < sandwichesSize; i++) { int j = sandwiches[i]; if (count[j] == 0) { return count[j ^ 1]; } count[j]--; } return 0; }
null
class Solution { public: int countStudents(vector<int>& students, vector<int>& sandwiches) { int cnt[2] = {0}; for (int& v : students) ++cnt[v]; for (int& v : sandwiches) { if (cnt[v]-- == 0) { return cnt[v ^ 1]; } } return 0; } };
null
null
func countStudents(students []int, sandwiches []int) int { cnt := [2]int{} for _, v := range students { cnt[v]++ } for _, v := range sandwiches { if cnt[v] == 0 { return cnt[v^1] } cnt[v]-- } return 0 }
class Solution { public int countStudents(int[] students, int[] sandwiches) { int[] cnt = new int[2]; for (int v : students) { ++cnt[v]; } for (int v : sandwiches) { if (cnt[v]-- == 0) { return cnt[v ^ 1]; } } return 0; } }
null
null
null
null
null
null
class Solution: def countStudents(self, students: List[int], sandwiches: List[int]) -> int: cnt = Counter(students) for v in sandwiches: if cnt[v] == 0: return cnt[v ^ 1] cnt[v] -= 1 return 0
null
impl Solution { pub fn count_students(students: Vec<i32>, sandwiches: Vec<i32>) -> i32 { let mut count = [0, 0]; for &v in students.iter() { count[v as usize] += 1; } for &v in sandwiches.iter() { let v = v as usize; if count[v as usize] == 0 { return count[v ^ 1]; } count[v] -= 1; } 0 } }
null
null
null
function countStudents(students: number[], sandwiches: number[]): number { const count = [0, 0]; for (const v of students) { count[v]++; } for (const v of sandwiches) { if (count[v] === 0) { return count[v ^ 1]; } count[v]--; } return 0; }
Maximize Items 🔒
Table: Inventory +----------------+---------+ | Column Name | Type | +----------------+---------+ | item_id | int | | item_type | varchar | | item_category | varchar | | square_footage | decimal | +----------------+---------+ item_id is the column of unique values for this table. Each row includes item id, item type, item category and sqaure footage. Leetcode warehouse wants to maximize the number of items it can stock in a 500,000 square feet warehouse. It wants to stock as many prime items as possible, and afterwards use the remaining square footage to stock the most number of non-prime items. Write a solution to find the number of prime and non-prime items that can be stored in the 500,000 square feet warehouse. Output the item type with prime_eligible followed by not_prime and the maximum number of items that can be stocked. Note: Item count must be a whole number (integer). If the count for the not_prime category is 0 , you should output 0 for that particular category. Return the result table ordered by item count in descending order . The result format is in the following example.   Example 1: Input: Inventory table: +---------+----------------+---------------+----------------+ | item_id | item_type | item_category | square_footage | +---------+----------------+---------------+----------------+ | 1374 | prime_eligible | Watches | 68.00 | | 4245 | not_prime | Art | 26.40 | | 5743 | prime_eligible | Software | 325.00 | | 8543 | not_prime | Clothing | 64.50 | | 2556 | not_prime | Shoes | 15.00 | | 2452 | prime_eligible | Scientific | 85.00 | | 3255 | not_prime | Furniture | 22.60 | | 1672 | prime_eligible | Beauty | 8.50 | | 4256 | prime_eligible | Furniture | 55.50 | | 6325 | prime_eligible | Food | 13.20 | +---------+----------------+---------------+----------------+ Output: +----------------+-------------+ | item_type | item_count | +----------------+-------------+ | prime_eligible | 5400 | | not_prime | 8 | +----------------+-------------+ Explanation: - The prime-eligible category comprises a total of 6 items, amounting to a combined square footage of 555.20 (68 + 325 + 85 + 8.50 + 55.50 + 13.20). It is possible to store 900 combinations of these 6 items, totaling 5400 items and occupying 499,680 square footage. - In the not_prime category, there are a total of 4 items with a combined square footage of 128.50. After deducting the storage used by prime-eligible items (500,000 - 499,680 = 320), there is room for 2 combinations of non-prime items, accommodating a total of 8 non-prime items within the available 320 square footage. Output table is ordered by item count in descending order.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below WITH T AS ( SELECT SUM(square_footage) AS s FROM Inventory WHERE item_type = 'prime_eligible' ) SELECT 'prime_eligible' AS item_type, COUNT(1) * FLOOR(500000 / s) AS item_count FROM Inventory JOIN T WHERE item_type = 'prime_eligible' UNION ALL SELECT 'not_prime', IFNULL(COUNT(1) * FLOOR(IF(s = 0, 500000, 500000 % s) / SUM(square_footage)), 0) FROM Inventory JOIN T WHERE item_type = 'not_prime';
null
null
null
null
null
null
null
null
null
null
Minimum Path Cost in a Grid
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.   Example 1: Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]] Output: 17 Explanation: The path with the minimum possible cost is the path 5 -> 0 -> 1. - The sum of the values of cells visited is 5 + 0 + 1 = 6. - The cost of moving from 5 to 0 is 3. - The cost of moving from 0 to 1 is 8. So the total cost of the path is 6 + 3 + 8 = 17. Example 2: Input: 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]] Output: 6 Explanation: The path with the minimum possible cost is the path 2 -> 3. - The sum of the values of cells visited is 2 + 3 = 5. - The cost of moving from 2 to 3 is 1. So the total cost of this path is 5 + 1 = 6.   Constraints: m == 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
null
null
class Solution { public: int minPathCost(vector<vector<int>>& grid, vector<vector<int>>& moveCost) { int m = grid.size(), n = grid[0].size(); const int inf = 1 << 30; vector<int> f = grid[0]; for (int i = 1; i < m; ++i) { vector<int> g(n, inf); for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { g[j] = min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); } } f = move(g); } return *min_element(f.begin(), f.end()); } };
null
null
func minPathCost(grid [][]int, moveCost [][]int) int { m, n := len(grid), len(grid[0]) f := grid[0] for i := 1; i < m; i++ { g := make([]int, n) for j := 0; j < n; j++ { g[j] = 1 << 30 for k := 0; k < n; k++ { g[j] = min(g[j], f[k]+moveCost[grid[i-1][k]][j]+grid[i][j]) } } f = g } return slices.Min(f) }
class Solution { public int minPathCost(int[][] grid, int[][] moveCost) { int m = grid.length, n = grid[0].length; int[] f = grid[0]; final int inf = 1 << 30; for (int i = 1; i < m; ++i) { int[] g = new int[n]; Arrays.fill(g, inf); for (int j = 0; j < n; ++j) { for (int k = 0; k < n; ++k) { g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); } } f = g; } // return Arrays.stream(f).min().getAsInt(); int ans = inf; for (int v : f) { ans = Math.min(ans, v); } return ans; } }
null
null
null
null
null
null
class Solution: def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) f = grid[0] for i in range(1, m): g = [inf] * n for j in range(n): for k in range(n): g[j] = min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]) f = g return min(f)
null
impl Solution { pub fn min_path_cost(grid: Vec<Vec<i32>>, move_cost: Vec<Vec<i32>>) -> i32 { let m = grid.len(); let n = grid[0].len(); let mut f = grid[0].clone(); for i in 1..m { let mut g: Vec<i32> = vec![i32::MAX; n]; for j in 0..n { for k in 0..n { g[j] = g[j].min(f[k] + move_cost[grid[i - 1][k] as usize][j] + grid[i][j]); } } f.copy_from_slice(&g); } f.iter().cloned().min().unwrap_or(0) } }
null
null
null
function minPathCost(grid: number[][], moveCost: number[][]): number { const m = grid.length; const n = grid[0].length; const f = grid[0]; for (let i = 1; i < m; ++i) { const g: number[] = Array(n).fill(Infinity); for (let j = 0; j < n; ++j) { for (let k = 0; k < n; ++k) { g[j] = Math.min(g[j], f[k] + moveCost[grid[i - 1][k]][j] + grid[i][j]); } } f.splice(0, n, ...g); } return Math.min(...f); }
Find Closest Number to Zero
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 .   Example 1: Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1. Example 2: Input: nums = [2,-1,1] Output: 1 Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.   Constraints: 1 <= n <= 1000 -10 5 <= nums[i] <= 10 5
null
null
class Solution { public: int findClosestNumber(vector<int>& nums) { int ans = 0, d = 1 << 30; for (int x : nums) { int y = abs(x); if (y < d || (y == d && x > ans)) { ans = x; d = y; } } return ans; } };
null
null
func findClosestNumber(nums []int) int { ans, d := 0, 1<<30 for _, x := range nums { if y := abs(x); y < d || (y == d && x > ans) { ans, d = x, y } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
class Solution { public int findClosestNumber(int[] nums) { int ans = 0, d = 1 << 30; for (int x : nums) { int y = Math.abs(x); if (y < d || (y == d && x > ans)) { ans = x; d = y; } } return ans; } }
null
null
null
null
null
null
class Solution: def findClosestNumber(self, nums: List[int]) -> int: ans, d = 0, inf for x in nums: if (y := abs(x)) < d or (y == d and x > ans): ans, d = x, y return ans
null
null
null
null
null
function findClosestNumber(nums: number[]): number { let [ans, d] = [0, 1 << 30]; for (const x of nums) { const y = Math.abs(x); if (y < d || (y == d && x > ans)) { [ans, d] = [x, y]; } } return ans; }
Minimum Number of Operations to Reinitialize a Permutation
You are given an even integer n ​​​​​​. You initially have a permutation perm of size n ​​ where perm[i] == i ​ (0-indexed) ​​​​. In one operation, you will create a new array arr , and for each i : If i % 2 == 0 , then arr[i] = perm[i / 2] . If i % 2 == 1 , then arr[i] = perm[n / 2 + (i - 1) / 2] . You will then assign arr ​​​​ to perm . Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.   Example 1: Input: n = 2 Output: 1 Explanation: perm = [0,1] initially. After the 1 st operation, perm = [0,1] So it takes only 1 operation. Example 2: Input: n = 4 Output: 2 Explanation: perm = [0,1,2,3] initially. After the 1 st operation, perm = [0,2,1,3] After the 2 nd operation, perm = [0,1,2,3] So it takes only 2 operations. Example 3: Input: n = 6 Output: 4   Constraints: 2 <= n <= 1000 n ​​​​​​ is even.
null
null
class Solution { public: int reinitializePermutation(int n) { int ans = 0; for (int i = 1;;) { ++ans; if (i < (n >> 1)) { i <<= 1; } else { i = (i - (n >> 1)) << 1 | 1; } if (i == 1) { return ans; } } } };
null
null
func reinitializePermutation(n int) (ans int) { for i := 1; ; { ans++ if i < (n >> 1) { i <<= 1 } else { i = (i-(n>>1))<<1 | 1 } if i == 1 { return ans } } }
class Solution { public int reinitializePermutation(int n) { int ans = 0; for (int i = 1;;) { ++ans; if (i < (n >> 1)) { i <<= 1; } else { i = (i - (n >> 1)) << 1 | 1; } if (i == 1) { return ans; } } } }
null
null
null
null
null
null
class Solution: def reinitializePermutation(self, n: int) -> int: ans, i = 0, 1 while 1: ans += 1 if i < n >> 1: i <<= 1 else: i = (i - (n >> 1)) << 1 | 1 if i == 1: return ans
null
null
null
null
null
null
Minimum Health to Beat Game 🔒
You are playing a game that has n levels numbered from 0 to n - 1 . You are given a 0-indexed integer array damage where damage[i] is the amount of health you will lose to complete the i th level. You are also given an integer armor . You may use your armor ability at most once during the game on any level which will protect you from at most armor damage. You must complete the levels in order and your health must be greater than 0 at all times to beat the game. Return the minimum health you need to start with to beat the game.   Example 1: Input: damage = [2,7,4,3], armor = 4 Output: 13 Explanation: One optimal way to beat the game starting at 13 health is: On round 1, take 2 damage. You have 13 - 2 = 11 health. On round 2, take 7 damage. You have 11 - 7 = 4 health. On round 3, use your armor to protect you from 4 damage. You have 4 - 0 = 4 health. On round 4, take 3 damage. You have 4 - 3 = 1 health. Note that 13 is the minimum health you need to start with to beat the game. Example 2: Input: damage = [2,5,3,4], armor = 7 Output: 10 Explanation: One optimal way to beat the game starting at 10 health is: On round 1, take 2 damage. You have 10 - 2 = 8 health. On round 2, use your armor to protect you from 5 damage. You have 8 - 0 = 8 health. On round 3, take 3 damage. You have 8 - 3 = 5 health. On round 4, take 4 damage. You have 5 - 4 = 1 health. Note that 10 is the minimum health you need to start with to beat the game. Example 3: Input: damage = [3,3,3], armor = 0 Output: 10 Explanation: One optimal way to beat the game starting at 10 health is: On round 1, take 3 damage. You have 10 - 3 = 7 health. On round 2, take 3 damage. You have 7 - 3 = 4 health. On round 3, take 3 damage. You have 4 - 3 = 1 health. Note that you did not use your armor ability.   Constraints: n == damage.length 1 <= n <= 10 5 0 <= damage[i] <= 10 5 0 <= armor <= 10 5
null
null
class Solution { public: long long minimumHealth(vector<int>& damage, int armor) { long long s = 0; int mx = damage[0]; for (int& v : damage) { s += v; mx = max(mx, v); } return s - min(mx, armor) + 1; } };
null
null
func minimumHealth(damage []int, armor int) int64 { var s int64 var mx int for _, v := range damage { s += int64(v) mx = max(mx, v) } return s - int64(min(mx, armor)) + 1 }
class Solution { public long minimumHealth(int[] damage, int armor) { long s = 0; int mx = damage[0]; for (int v : damage) { s += v; mx = Math.max(mx, v); } return s - Math.min(mx, armor) + 1; } }
null
null
null
null
null
null
class Solution: def minimumHealth(self, damage: List[int], armor: int) -> int: return sum(damage) - min(max(damage), armor) + 1
null
null
null
null
null
function minimumHealth(damage: number[], armor: number): number { let s = 0; let mx = 0; for (const v of damage) { mx = Math.max(mx, v); s += v; } return s - Math.min(mx, armor) + 1; }
Partition Array into Disjoint Intervals
Given an integer array nums , partition it into two (contiguous) subarrays left and right so that: Every element in 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.   Example 1: Input: nums = [5,0,3,8,6] Output: 3 Explanation: left = [5,0,3], right = [8,6] Example 2: Input: nums = [1,1,1,0,6,12] Output: 4 Explanation: left = [1,1,1,0], right = [6,12]   Constraints: 2 <= nums.length <= 10 5 0 <= nums[i] <= 10 6 There is at least one valid answer for the given input.
null
null
class Solution { public: int partitionDisjoint(vector<int>& nums) { int n = nums.size(); vector<int> mi(n + 1, INT_MAX); for (int i = n - 1; ~i; --i) { mi[i] = min(nums[i], mi[i + 1]); } int mx = 0; for (int i = 1;; ++i) { int v = nums[i - 1]; mx = max(mx, v); if (mx <= mi[i]) { return i; } } } };
null
null
func partitionDisjoint(nums []int) int { n := len(nums) mi := make([]int, n+1) mi[n] = nums[n-1] for i := n - 1; i >= 0; i-- { mi[i] = min(nums[i], mi[i+1]) } mx := 0 for i := 1; ; i++ { v := nums[i-1] mx = max(mx, v) if mx <= mi[i] { return i } } }
class Solution { public int partitionDisjoint(int[] nums) { int n = nums.length; int[] mi = new int[n + 1]; mi[n] = nums[n - 1]; for (int i = n - 1; i >= 0; --i) { mi[i] = Math.min(nums[i], mi[i + 1]); } int mx = 0; for (int i = 1;; ++i) { int v = nums[i - 1]; mx = Math.max(mx, v); if (mx <= mi[i]) { return i; } } } }
null
null
null
null
null
null
class Solution: def partitionDisjoint(self, nums: List[int]) -> int: n = len(nums) mi = [inf] * (n + 1) for i in range(n - 1, -1, -1): mi[i] = min(nums[i], mi[i + 1]) mx = 0 for i, v in enumerate(nums, 1): mx = max(mx, v) if mx <= mi[i]: return i
null
null
null
null
null
null
Find the Lexicographically Smallest Valid Sequence
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: The indices are sorted in ascending order. Concatenating the characters at these indices in 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.   Example 1: Input: word1 = "vbcca", word2 = "abc" Output: [0,1,2] Explanation: The lexicographically smallest valid sequence of indices is [0, 1, 2] : Change word1[0] to 'a' . word1[1] is already 'b' . word1[2] is already 'c' . Example 2: Input: word1 = "bacdc", word2 = "abc" Output: [1,2,4] Explanation: The lexicographically smallest valid sequence of indices is [1, 2, 4] : word1[1] is already 'a' . Change word1[2] to 'b' . word1[4] is already 'c' . Example 3: Input: word1 = "aaaaaa", word2 = "aaabc" Output: [] Explanation: There is no valid sequence of indices. Example 4: Input: word1 = "abc", word2 = "ab" Output: [0,1]   Constraints: 1 <= word2.length < word1.length <= 3 * 10 5 word1 and word2 consist only of lowercase English letters.
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Median of Two Sorted Arrays
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)) .   Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.   Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -10 6 <= nums1[i], nums2[i] <= 10 6
int findKth(int* nums1, int m, int i, int* nums2, int n, int j, int k) { if (i >= m) return nums2[j + k - 1]; if (j >= n) return nums1[i + k - 1]; if (k == 1) return nums1[i] < nums2[j] ? nums1[i] : nums2[j]; int p = k / 2; int x = (i + p - 1 < m) ? nums1[i + p - 1] : INT_MAX; int y = (j + p - 1 < n) ? nums2[j + p - 1] : INT_MAX; if (x < y) return findKth(nums1, m, i + p, nums2, n, j, k - p); else return findKth(nums1, m, i, nums2, n, j + p, k - p); } double findMedianSortedArrays(int* nums1, int m, int* nums2, int n) { int total = m + n; int a = findKth(nums1, m, 0, nums2, n, 0, (total + 1) / 2); int b = findKth(nums1, m, 0, nums2, n, 0, (total + 2) / 2); return (a + b) / 2.0; }
public class Solution { private int m; private int n; private int[] nums1; private int[] nums2; public double FindMedianSortedArrays(int[] nums1, int[] nums2) { m = nums1.Length; n = nums2.Length; this.nums1 = nums1; this.nums2 = nums2; int a = f(0, 0, (m + n + 1) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } private int f(int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.Min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); } }
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int m = nums1.size(), n = nums2.size(); function<int(int, int, int)> f = [&](int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; int a = f(0, 0, (m + n + 1) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } };
null
null
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 { m, n := len(nums1), len(nums2) var f func(i, j, k int) int f = func(i, j, k int) int { if i >= m { return nums2[j+k-1] } if j >= n { return nums1[i+k-1] } if k == 1 { return min(nums1[i], nums2[j]) } p := k / 2 x, y := 1<<30, 1<<30 if ni := i + p - 1; ni < m { x = nums1[ni] } if nj := j + p - 1; nj < n { y = nums2[nj] } if x < y { return f(i+p, j, k-p) } return f(i, j+p, k-p) } a, b := f(0, 0, (m+n+1)/2), f(0, 0, (m+n+2)/2) return float64(a+b) / 2.0 }
class Solution { private int m; private int n; private int[] nums1; private int[] nums2; public double findMedianSortedArrays(int[] nums1, int[] nums2) { m = nums1.length; n = nums2.length; this.nums1 = nums1; this.nums2 = nums2; int a = f(0, 0, (m + n + 1) / 2); int b = f(0, 0, (m + n + 2) / 2); return (a + b) / 2.0; } private int f(int i, int j, int k) { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } int p = k / 2; int x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; int y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); } }
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function (nums1, nums2) { const m = nums1.length; const n = nums2.length; const f = (i, j, k) => { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } const p = Math.floor(k / 2); const x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; const y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; const a = f(0, 0, Math.floor((m + n + 1) / 2)); const b = f(0, 0, Math.floor((m + n + 2) / 2)); return (a + b) / 2; };
null
null
import std/[algorithm, sequtils] proc medianOfTwoSortedArrays(nums1: seq[int], nums2: seq[int]): float = var fullList: seq[int] = concat(nums1, nums2) value: int = fullList.len div 2 fullList.sort() if fullList.len mod 2 == 0: result = (fullList[value - 1] + fullList[value]) / 2 else: result = fullList[value].toFloat() # Driver Code # var # arrA: seq[int] = @[1, 2] # arrB: seq[int] = @[3, 4, 5] # echo medianOfTwoSortedArrays(arrA, arrB)
class Solution { /** * @param int[] $nums1 * @param int[] $nums2 * @return float */ function findMedianSortedArrays($nums1, $nums2) { $arr = array_merge($nums1, $nums2); sort($arr); $cnt_arr = count($arr); if ($cnt_arr % 2) { return $arr[$cnt_arr / 2]; } else { return ($arr[intdiv($cnt_arr, 2) - 1] + $arr[intdiv($cnt_arr, 2)]) / 2; } } }
null
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: def f(i: int, j: int, k: int) -> int: if i >= m: return nums2[j + k - 1] if j >= n: return nums1[i + k - 1] if k == 1: return min(nums1[i], nums2[j]) p = k // 2 x = nums1[i + p - 1] if i + p - 1 < m else inf y = nums2[j + p - 1] if j + p - 1 < n else inf return f(i + p, j, k - p) if x < y else f(i, j + p, k - p) m, n = len(nums1), len(nums2) a = f(0, 0, (m + n + 1) // 2) b = f(0, 0, (m + n + 2) // 2) return (a + b) / 2
null
null
null
null
null
function findMedianSortedArrays(nums1: number[], nums2: number[]): number { const m = nums1.length; const n = nums2.length; const f = (i: number, j: number, k: number): number => { if (i >= m) { return nums2[j + k - 1]; } if (j >= n) { return nums1[i + k - 1]; } if (k == 1) { return Math.min(nums1[i], nums2[j]); } const p = Math.floor(k / 2); const x = i + p - 1 < m ? nums1[i + p - 1] : 1 << 30; const y = j + p - 1 < n ? nums2[j + p - 1] : 1 << 30; return x < y ? f(i + p, j, k - p) : f(i, j + p, k - p); }; const a = f(0, 0, Math.floor((m + n + 1) / 2)); const b = f(0, 0, Math.floor((m + n + 2) / 2)); return (a + b) / 2; }
Largest Element in an Array after Merge Operations
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: Choose an integer i 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.   Example 1: Input: nums = [2,3,7,9,3] Output: 21 Explanation: We can apply the following operations on the array: - Choose i = 0. The resulting array will be nums = [ 5 ,7,9,3]. - Choose i = 1. The resulting array will be nums = [5, 16 ,3]. - Choose i = 0. The resulting array will be nums = [ 21 ,3]. The largest element in the final array is 21. It can be shown that we cannot obtain a larger element. Example 2: Input: nums = [5,3,3] Output: 11 Explanation: We can do the following operations on the array: - Choose i = 1. The resulting array will be nums = [5, 6 ]. - Choose i = 0. The resulting array will be nums = [ 11 ]. There is only one element in the final array, which is 11.   Constraints: 1 <= nums.length <= 10 5 1 <= nums[i] <= 10 6
null
null
class Solution { public: long long maxArrayValue(vector<int>& nums) { int n = nums.size(); long long ans = nums[n - 1], t = nums[n - 1]; for (int i = n - 2; ~i; --i) { if (nums[i] <= t) { t += nums[i]; } else { t = nums[i]; } ans = max(ans, t); } return ans; } };
null
null
func maxArrayValue(nums []int) int64 { n := len(nums) ans, t := nums[n-1], nums[n-1] for i := n - 2; i >= 0; i-- { if nums[i] <= t { t += nums[i] } else { t = nums[i] } ans = max(ans, t) } return int64(ans) }
class Solution { public long maxArrayValue(int[] nums) { int n = nums.length; long ans = nums[n - 1], t = nums[n - 1]; for (int i = n - 2; i >= 0; --i) { if (nums[i] <= t) { t += nums[i]; } else { t = nums[i]; } ans = Math.max(ans, t); } return ans; } }
null
null
null
null
null
null
class Solution: def maxArrayValue(self, nums: List[int]) -> int: for i in range(len(nums) - 2, -1, -1): if nums[i] <= nums[i + 1]: nums[i] += nums[i + 1] return max(nums)
null
null
null
null
null
function maxArrayValue(nums: number[]): number { for (let i = nums.length - 2; i >= 0; --i) { if (nums[i] <= nums[i + 1]) { nums[i] += nums[i + 1]; } } return Math.max(...nums); }
Lonely Pixel I 🔒
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels . A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.   Example 1: Input: picture = [["W","W","B"],["W","B","W"],["B","W","W"]] Output: 3 Explanation: All the three 'B's are black lonely pixels. Example 2: Input: picture = [["B","B","B"],["B","B","W"],["B","B","B"]] Output: 0   Constraints: m == picture.length n == picture[i].length 1 <= m, n <= 500 picture[i][j] is 'W' or 'B' .
null
null
class Solution { public: int findLonelyPixel(vector<vector<char>>& picture) { int m = picture.size(), n = picture[0].size(); vector<int> rows(m); vector<int> cols(n); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { ++ans; } } } return ans; } };
null
null
func findLonelyPixel(picture [][]byte) (ans int) { rows := make([]int, len(picture)) cols := make([]int, len(picture[0])) for i, row := range picture { for j, x := range row { if x == 'B' { rows[i]++ cols[j]++ } } } for i, row := range picture { for j, x := range row { if x == 'B' && rows[i] == 1 && cols[j] == 1 { ans++ } } } return }
class Solution { public int findLonelyPixel(char[][] picture) { int m = picture.length, n = picture[0].length; int[] rows = new int[m]; int[] cols = new int[n]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B') { ++rows[i]; ++cols[j]; } } } int ans = 0; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { ++ans; } } } return ans; } }
null
null
null
null
null
null
class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: rows = [0] * len(picture) cols = [0] * len(picture[0]) for i, row in enumerate(picture): for j, x in enumerate(row): if x == "B": rows[i] += 1 cols[j] += 1 ans = 0 for i, row in enumerate(picture): for j, x in enumerate(row): if x == "B" and rows[i] == 1 and cols[j] == 1: ans += 1 return ans
null
null
null
null
null
function findLonelyPixel(picture: string[][]): number { const m = picture.length; const n = picture[0].length; const rows: number[] = Array(m).fill(0); const cols: number[] = Array(n).fill(0); for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (picture[i][j] === 'B') { ++rows[i]; ++cols[j]; } } } let ans = 0; for (let i = 0; i < m; ++i) { for (let j = 0; j < n; ++j) { if (picture[i][j] === 'B' && rows[i] === 1 && cols[j] === 1) { ++ans; } } } return ans; }
Count the Number of Good Nodes
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] = [a i , b i ] indicates that there is an edge between nodes a i and b i in the tree. A node is good if all the subtrees rooted at its children have the same size. Return the number of good nodes in the given tree. A subtree of treeName is a tree consisting of a node in treeName and all of its descendants.   Example 1: Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]] Output: 7 Explanation: All of the nodes of the given tree are good. Example 2: Input: edges = [[0,1],[1,2],[2,3],[3,4],[0,5],[1,6],[2,7],[3,8]] Output: 6 Explanation: There are 6 good nodes in the given tree. They are colored in the image above. Example 3: Input: 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]] Output: 12 Explanation: All nodes except node 9 are good.   Constraints: 2 <= n <= 10 5 edges.length == n - 1 edges[i].length == 2 0 <= a i , b i < n The input is generated such that edges represents a valid tree.
null
null
class Solution { public: int countGoodNodes(vector<vector<int>>& edges) { int n = edges.size() + 1; vector<int> g[n]; for (const auto& e : edges) { int a = e[0], b = e[1]; g[a].push_back(b); g[b].push_back(a); } int ans = 0; auto dfs = [&](this auto&& dfs, int a, int fa) -> int { int pre = -1, cnt = 1, ok = 1; for (int b : g[a]) { if (b != fa) { int cur = dfs(b, a); cnt += cur; if (pre < 0) { pre = cur; } else if (pre != cur) { ok = 0; } } } ans += ok; return cnt; }; dfs(0, -1); return ans; } };
null
null
func countGoodNodes(edges [][]int) (ans int) { n := len(edges) + 1 g := make([][]int, n) for _, e := range edges { a, b := e[0], e[1] g[a] = append(g[a], b) g[b] = append(g[b], a) } var dfs func(int, int) int dfs = func(a, fa int) int { pre, cnt, ok := -1, 1, 1 for _, b := range g[a] { if b != fa { cur := dfs(b, a) cnt += cur if pre < 0 { pre = cur } else if pre != cur { ok = 0 } } } ans += ok return cnt } dfs(0, -1) return }
class Solution { private int ans; private List<Integer>[] g; public int countGoodNodes(int[][] edges) { int n = edges.length + 1; g = new List[n]; Arrays.setAll(g, k -> new ArrayList<>()); for (var e : edges) { int a = e[0], b = e[1]; g[a].add(b); g[b].add(a); } dfs(0, -1); return ans; } private int dfs(int a, int fa) { int pre = -1, cnt = 1, ok = 1; for (int b : g[a]) { if (b != fa) { int cur = dfs(b, a); cnt += cur; if (pre < 0) { pre = cur; } else if (pre != cur) { ok = 0; } } } ans += ok; return cnt; } }
null
null
null
null
null
null
class Solution: def countGoodNodes(self, edges: List[List[int]]) -> int: def dfs(a: int, fa: int) -> int: pre = -1 cnt = ok = 1 for b in g[a]: if b != fa: cur = dfs(b, a) cnt += cur if pre < 0: pre = cur elif pre != cur: ok = 0 nonlocal ans ans += ok return cnt g = defaultdict(list) for a, b in edges: g[a].append(b) g[b].append(a) ans = 0 dfs(0, -1) return ans
null
null
null
null
null
function countGoodNodes(edges: number[][]): number { const n = edges.length + 1; const g: number[][] = Array.from({ length: n }, () => []); for (const [a, b] of edges) { g[a].push(b); g[b].push(a); } let ans = 0; const dfs = (a: number, fa: number): number => { let [pre, cnt, ok] = [-1, 1, 1]; for (const b of g[a]) { if (b !== fa) { const cur = dfs(b, a); cnt += cur; if (pre < 0) { pre = cur; } else if (pre !== cur) { ok = 0; } } } ans += ok; return cnt; }; dfs(0, -1); return ans; }
Count Elements With Maximum Frequency
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.   Example 1: Input: nums = [1,2,2,3,1,4] Output: 4 Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. So the number of elements in the array with maximum frequency is 4. Example 2: Input: nums = [1,2,3,4,5] Output: 5 Explanation: All elements of the array have a frequency of 1 which is the maximum. So the number of elements in the array with maximum frequency is 5.   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100
null
null
class Solution { public: int maxFrequencyElements(vector<int>& nums) { int cnt[101]{}; for (int x : nums) { ++cnt[x]; } int ans = 0, mx = -1; for (int x : cnt) { if (mx < x) { mx = x; ans = x; } else if (mx == x) { ans += x; } } return ans; } };
null
null
func maxFrequencyElements(nums []int) (ans int) { cnt := [101]int{} for _, x := range nums { cnt[x]++ } mx := -1 for _, x := range cnt { if mx < x { mx, ans = x, x } else if mx == x { ans += x } } return }
class Solution { public int maxFrequencyElements(int[] nums) { int[] cnt = new int[101]; for (int x : nums) { ++cnt[x]; } int ans = 0, mx = -1; for (int x : cnt) { if (mx < x) { mx = x; ans = x; } else if (mx == x) { ans += x; } } return ans; } }
null
null
null
null
null
null
class Solution: def maxFrequencyElements(self, nums: List[int]) -> int: cnt = Counter(nums) mx = max(cnt.values()) return sum(x for x in cnt.values() if x == mx)
null
null
null
null
null
function maxFrequencyElements(nums: number[]): number { const cnt: number[] = Array(101).fill(0); for (const x of nums) { ++cnt[x]; } let [ans, mx] = [0, -1]; for (const x of cnt) { if (mx < x) { mx = x; ans = x; } else if (mx === x) { ans += x; } } return ans; }
Maximum Sum of an Hourglass
You are given an m x n integer matrix grid . We define an hourglass as a part of the matrix with the following form: Return the maximum sum of the elements of an hourglass . Note that an hourglass cannot be rotated and must be entirely contained within the matrix.   Example 1: Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]] Output: 30 Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30. Example 2: Input: grid = [[1,2,3],[4,5,6],[7,8,9]] Output: 35 Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.   Constraints: m == grid.length n == grid[i].length 3 <= m, n <= 150 0 <= grid[i][j] <= 10 6
null
null
class Solution { public: int maxSum(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { s += grid[x][y]; } } ans = max(ans, s); } } return ans; } };
null
null
func maxSum(grid [][]int) (ans int) { m, n := len(grid), len(grid[0]) for i := 1; i < m-1; i++ { for j := 1; j < n-1; j++ { s := -grid[i][j-1] - grid[i][j+1] for x := i - 1; x <= i+1; x++ { for y := j - 1; y <= j+1; y++ { s += grid[x][y] } } ans = max(ans, s) } } return }
class Solution { public int maxSum(int[][] grid) { int m = grid.length, n = grid[0].length; int ans = 0; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { int s = -grid[i][j - 1] - grid[i][j + 1]; for (int x = i - 1; x <= i + 1; ++x) { for (int y = j - 1; y <= j + 1; ++y) { s += grid[x][y]; } } ans = Math.max(ans, s); } } return ans; } }
null
null
null
null
null
null
class Solution: def maxSum(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) ans = 0 for i in range(1, m - 1): for j in range(1, n - 1): s = -grid[i][j - 1] - grid[i][j + 1] s += sum( grid[x][y] for x in range(i - 1, i + 2) for y in range(j - 1, j + 2) ) ans = max(ans, s) return ans
null
null
null
null
null
function maxSum(grid: number[][]): number { const m = grid.length; const n = grid[0].length; let ans = 0; for (let i = 1; i < m - 1; ++i) { for (let j = 1; j < n - 1; ++j) { let s = -grid[i][j - 1] - grid[i][j + 1]; for (let x = i - 1; x <= i + 1; ++x) { for (let y = j - 1; y <= j + 1; ++y) { s += grid[x][y]; } } ans = Math.max(ans, s); } } return ans; }
Winning Candidate 🔒
Table: Candidate +-------------+----------+ | Column Name | Type | +-------------+----------+ | id | int | | name | varchar | +-------------+----------+ id is the column with unique values for this table. Each row of this table contains information about the id and the name of a candidate.   Table: Vote +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | candidateId | int | +-------------+------+ id is an auto-increment primary key (column with unique values). candidateId is a foreign key (reference column) to id from the Candidate table. Each row of this table determines the candidate who got the i th vote in the elections.   Write a solution to report the name of the winning candidate (i.e., the candidate who got the largest number of votes). The test cases are generated so that exactly one candidate wins the elections. The result format is in the following example.   Example 1: Input: Candidate table: +----+------+ | id | name | +----+------+ | 1 | A | | 2 | B | | 3 | C | | 4 | D | | 5 | E | +----+------+ Vote table: +----+-------------+ | id | candidateId | +----+-------------+ | 1 | 2 | | 2 | 4 | | 3 | 3 | | 4 | 2 | | 5 | 5 | +----+-------------+ Output: +------+ | name | +------+ | B | +------+ Explanation: Candidate B has 2 votes. Candidates C, D, and E have 1 vote each. The winner is candidate B.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT name FROM Candidate AS c LEFT JOIN Vote AS v ON c.id = v.candidateId GROUP BY c.id ORDER BY COUNT(1) DESC LIMIT 1;
null
null
null
null
null
null
null
null
null
null
Find Consistently Improving Employees
Table: employees +-------------+---------+ | Column Name | Type | +-------------+---------+ | employee_id | int | | name | varchar | +-------------+---------+ employee_id is the unique identifier for this table. Each row contains information about an employee. Table: performance_reviews +-------------+------+ | Column Name | Type | +-------------+------+ | review_id | int | | employee_id | int | | review_date | date | | rating | int | +-------------+------+ review_id is the unique identifier for this table. Each 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. Write a solution to find employees who have consistently improved their performance over their last three reviews . An employee must have at least 3 review to be considered The employee's last 3 reviews must show strictly increasing ratings (each review better than the previous) Use the most recent 3 reviews based on review_date for each employee Calculate the improvement score as the difference between the latest rating and the earliest rating among the last 3 reviews Return the result table ordered by improvement score in descending order, then by name in ascending order . The result format is in the following example.   Example: Input: employees table: +-------------+----------------+ | employee_id | name | +-------------+----------------+ | 1 | Alice Johnson | | 2 | Bob Smith | | 3 | Carol Davis | | 4 | David Wilson | | 5 | Emma Brown | +-------------+----------------+ performance_reviews table: +-----------+-------------+-------------+--------+ | review_id | employee_id | review_date | rating | +-----------+-------------+-------------+--------+ | 1 | 1 | 2023-01-15 | 2 | | 2 | 1 | 2023-04-15 | 3 | | 3 | 1 | 2023-07-15 | 4 | | 4 | 1 | 2023-10-15 | 5 | | 5 | 2 | 2023-02-01 | 3 | | 6 | 2 | 2023-05-01 | 2 | | 7 | 2 | 2023-08-01 | 4 | | 8 | 2 | 2023-11-01 | 5 | | 9 | 3 | 2023-03-10 | 1 | | 10 | 3 | 2023-06-10 | 2 | | 11 | 3 | 2023-09-10 | 3 | | 12 | 3 | 2023-12-10 | 4 | | 13 | 4 | 2023-01-20 | 4 | | 14 | 4 | 2023-04-20 | 4 | | 15 | 4 | 2023-07-20 | 4 | | 16 | 5 | 2023-02-15 | 3 | | 17 | 5 | 2023-05-15 | 2 | +-----------+-------------+-------------+--------+ Output: +-------------+----------------+-------------------+ | employee_id | name | improvement_score | +-------------+----------------+-------------------+ | 2 | Bob Smith | 3 | | 1 | Alice Johnson | 2 | | 3 | Carol Davis | 2 | +-------------+----------------+-------------------+ Explanation: Alice Johnson (employee_id = 1): Has 4 reviews with ratings: 2, 3, 4, 5 Last 3 reviews (by date): 2023-04-15 (3), 2023-07-15 (4), 2023-10-15 (5) Ratings are strictly increasing: 3 → 4 → 5 Improvement score: 5 - 3 = 2 Carol Davis (employee_id = 3): Has 4 reviews with ratings: 1, 2, 3, 4 Last 3 reviews (by date): 2023-06-10 (2), 2023-09-10 (3), 2023-12-10 (4) Ratings are strictly increasing: 2 → 3 → 4 Improvement score: 4 - 2 = 2 Bob Smith (employee_id = 2): Has 4 reviews with ratings: 3, 2, 4, 5 Last 3 reviews (by date): 2023-05-01 (2), 2023-08-01 (4), 2023-11-01 (5) Ratings are strictly increasing: 2 → 4 → 5 Improvement score: 5 - 2 = 3 Employees not included: David Wilson (employee_id = 4): Last 3 reviews are all 4 (no improvement) Emma Brown (employee_id = 5): Only has 2 reviews (needs at least 3) The output table is ordered by improvement_score in descending order, then by name in ascending order.
null
null
null
null
null
null
null
null
null
WITH recent AS ( SELECT employee_id, review_date, ROW_NUMBER() OVER ( PARTITION BY employee_id ORDER BY review_date DESC ) AS rn, ( LAG(rating) OVER ( PARTITION BY employee_id ORDER BY review_date DESC ) - rating ) AS delta FROM performance_reviews ) SELECT employee_id, name, SUM(delta) AS improvement_score FROM recent JOIN employees USING (employee_id) WHERE rn > 1 AND rn <= 3 GROUP BY 1 HAVING COUNT(*) = 2 AND MIN(delta) > 0 ORDER BY 3 DESC, 2;
null
null
import pandas as pd def find_consistently_improving_employees( employees: pd.DataFrame, performance_reviews: pd.DataFrame ) -> pd.DataFrame: performance_reviews = performance_reviews.sort_values( ["employee_id", "review_date"], ascending=[True, False] ) performance_reviews["rn"] = ( performance_reviews.groupby("employee_id").cumcount() + 1 ) performance_reviews["lag_rating"] = performance_reviews.groupby("employee_id")[ "rating" ].shift(1) performance_reviews["delta"] = ( performance_reviews["lag_rating"] - performance_reviews["rating"] ) recent = performance_reviews[ (performance_reviews["rn"] > 1) & (performance_reviews["rn"] <= 3) ] improvement = ( recent.groupby("employee_id") .agg( improvement_score=("delta", "sum"), count=("delta", "count"), min_delta=("delta", "min"), ) .reset_index() ) improvement = improvement[ (improvement["count"] == 2) & (improvement["min_delta"] > 0) ] result = improvement.merge(employees[["employee_id", "name"]], on="employee_id") result = result.sort_values( by=["improvement_score", "name"], ascending=[False, True] ) return result[["employee_id", "name", "improvement_score"]]
null
null
null
null
null
null
null
Find Median from Data Stream
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. For example, for arr = [2,3,4] , the median is 3 . For example, for arr = [2,3] , the median is (2 + 3) / 2 = 2.5 . Implement the MedianFinder class: MedianFinder() 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.   Example 1: Input ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"] [[], [1], [2], [], [3], []] Output [null, null, null, 1.5, null, 2.0] Explanation MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = [1] medianFinder.addNum(2); // arr = [1, 2] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr[1, 2, 3] medianFinder.findMedian(); // return 2.0   Constraints: -10 5 <= num <= 10 5 There will be at least one element in the data structure before calling findMedian . At most 5 * 10 4 calls will be made to addNum and findMedian .   Follow up: If all integer numbers from the stream are in the range [0, 100] , how would you optimize your solution? If 99% of all integer numbers from the stream are in the range [0, 100] , how would you optimize your solution?
null
public class MedianFinder { private PriorityQueue<int, int> minQ = new PriorityQueue<int, int>(); private PriorityQueue<int, int> maxQ = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b.CompareTo(a))); public MedianFinder() { } public void AddNum(int num) { maxQ.Enqueue(num, num); minQ.Enqueue(maxQ.Peek(), maxQ.Dequeue()); if (minQ.Count > maxQ.Count + 1) { maxQ.Enqueue(minQ.Peek(), minQ.Dequeue()); } } public double FindMedian() { return minQ.Count == maxQ.Count ? (minQ.Peek() + maxQ.Peek()) / 2.0 : minQ.Peek(); } } /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.AddNum(num); * double param_2 = obj.FindMedian(); */
class MedianFinder { public: MedianFinder() { } void addNum(int num) { maxQ.push(num); minQ.push(maxQ.top()); maxQ.pop(); if (minQ.size() > maxQ.size() + 1) { maxQ.push(minQ.top()); minQ.pop(); } } double findMedian() { return minQ.size() == maxQ.size() ? (minQ.top() + maxQ.top()) / 2.0 : minQ.top(); } private: priority_queue<int> maxQ; priority_queue<int, vector<int>, greater<int>> minQ; }; /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder* obj = new MedianFinder(); * obj->addNum(num); * double param_2 = obj->findMedian(); */
null
null
type MedianFinder struct { minq hp maxq hp } func Constructor() MedianFinder { return MedianFinder{hp{}, hp{}} } func (this *MedianFinder) AddNum(num int) { minq, maxq := &this.minq, &this.maxq heap.Push(maxq, -num) heap.Push(minq, -heap.Pop(maxq).(int)) if minq.Len()-maxq.Len() > 1 { heap.Push(maxq, -heap.Pop(minq).(int)) } } func (this *MedianFinder) FindMedian() float64 { minq, maxq := this.minq, this.maxq if minq.Len() == maxq.Len() { return float64(minq.IntSlice[0]-maxq.IntSlice[0]) / 2 } return float64(minq.IntSlice[0]) } type hp struct{ sort.IntSlice } func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v } /** * Your MedianFinder object will be instantiated and called as such: * obj := Constructor(); * obj.AddNum(num); * param_2 := obj.FindMedian(); */
class MedianFinder { private PriorityQueue<Integer> minQ = new PriorityQueue<>(); private PriorityQueue<Integer> maxQ = new PriorityQueue<>(Collections.reverseOrder()); public MedianFinder() { } public void addNum(int num) { maxQ.offer(num); minQ.offer(maxQ.poll()); if (minQ.size() - maxQ.size() > 1) { maxQ.offer(minQ.poll()); } } public double findMedian() { return minQ.size() == maxQ.size() ? (minQ.peek() + maxQ.peek()) / 2.0 : minQ.peek(); } } /** * Your MedianFinder object will be instantiated and called as such: * MedianFinder obj = new MedianFinder(); * obj.addNum(num); * double param_2 = obj.findMedian(); */
var MedianFinder = function () { this.minQ = new MinPriorityQueue(); this.maxQ = new MaxPriorityQueue(); }; /** * @param {number} num * @return {void} */ MedianFinder.prototype.addNum = function (num) { this.maxQ.enqueue(num); this.minQ.enqueue(this.maxQ.dequeue().element); if (this.minQ.size() - this.maxQ.size() > 1) { this.maxQ.enqueue(this.minQ.dequeue().element); } }; /** * @return {number} */ MedianFinder.prototype.findMedian = function () { if (this.minQ.size() === this.maxQ.size()) { return (this.minQ.front().element + this.maxQ.front().element) / 2; } return this.minQ.front().element; }; /** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
null
null
null
null
null
class MedianFinder: def __init__(self): self.minq = [] self.maxq = [] def addNum(self, num: int) -> None: heappush(self.minq, -heappushpop(self.maxq, -num)) if len(self.minq) - len(self.maxq) > 1: heappush(self.maxq, -heappop(self.minq)) def findMedian(self) -> float: if len(self.minq) == len(self.maxq): return (self.minq[0] - self.maxq[0]) / 2 return self.minq[0] # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
null
use std::cmp::Reverse; use std::collections::BinaryHeap; struct MedianFinder { minQ: BinaryHeap<Reverse<i32>>, maxQ: BinaryHeap<i32>, } impl MedianFinder { fn new() -> Self { MedianFinder { minQ: BinaryHeap::new(), maxQ: BinaryHeap::new(), } } fn add_num(&mut self, num: i32) { self.maxQ.push(num); self.minQ.push(Reverse(self.maxQ.pop().unwrap())); if self.minQ.len() > self.maxQ.len() + 1 { self.maxQ.push(self.minQ.pop().unwrap().0); } } fn find_median(&self) -> f64 { if self.minQ.len() == self.maxQ.len() { let min_top = self.minQ.peek().unwrap().0; let max_top = *self.maxQ.peek().unwrap(); (min_top + max_top) as f64 / 2.0 } else { self.minQ.peek().unwrap().0 as f64 } } }
null
null
class MedianFinder { private var minQ = Heap<Int>(sort: <) private var maxQ = Heap<Int>(sort: >) init() { } func addNum(_ num: Int) { maxQ.insert(num) minQ.insert(maxQ.remove()!) if maxQ.count < minQ.count { maxQ.insert(minQ.remove()!) } } func findMedian() -> Double { if maxQ.count > minQ.count { return Double(maxQ.peek()!) } return (Double(maxQ.peek()!) + Double(minQ.peek()!)) / 2.0 } } struct Heap<T> { var elements: [T] let sort: (T, T) -> Bool init(sort: @escaping (T, T) -> Bool, elements: [T] = []) { self.sort = sort self.elements = elements if !elements.isEmpty { for i in stride(from: elements.count / 2 - 1, through: 0, by: -1) { siftDown(from: i) } } } var isEmpty: Bool { return elements.isEmpty } var count: Int { return elements.count } func peek() -> T? { return elements.first } mutating func insert(_ value: T) { elements.append(value) siftUp(from: elements.count - 1) } mutating func remove() -> T? { guard !elements.isEmpty else { return nil } elements.swapAt(0, elements.count - 1) let removedValue = elements.removeLast() siftDown(from: 0) return removedValue } private mutating func siftUp(from index: Int) { var child = index var parent = parentIndex(ofChildAt: child) while child > 0 && sort(elements[child], elements[parent]) { elements.swapAt(child, parent) child = parent parent = parentIndex(ofChildAt: child) } } private mutating func siftDown(from index: Int) { var parent = index while true { let left = leftChildIndex(ofParentAt: parent) let right = rightChildIndex(ofParentAt: parent) var candidate = parent if left < count && sort(elements[left], elements[candidate]) { candidate = left } if right < count && sort(elements[right], elements[candidate]) { candidate = right } if candidate == parent { return } elements.swapAt(parent, candidate) parent = candidate } } private func parentIndex(ofChildAt index: Int) -> Int { return (index - 1) / 2 } private func leftChildIndex(ofParentAt index: Int) -> Int { return 2 * index + 1 } private func rightChildIndex(ofParentAt index: Int) -> Int { return 2 * index + 2 } } /** * Your MedianFinder object will be instantiated and called as such: * let obj = MedianFinder() * obj.addNum(num) * let ret_2: Double = obj.findMedian() */
class MedianFinder { #minQ = new MinPriorityQueue(); #maxQ = new MaxPriorityQueue(); addNum(num: number): void { const [minQ, maxQ] = [this.#minQ, this.#maxQ]; maxQ.enqueue(num); minQ.enqueue(maxQ.dequeue().element); if (minQ.size() - maxQ.size() > 1) { maxQ.enqueue(minQ.dequeue().element); } } findMedian(): number { const [minQ, maxQ] = [this.#minQ, this.#maxQ]; if (minQ.size() === maxQ.size()) { return (minQ.front().element + maxQ.front().element) / 2; } return minQ.front().element; } } /** * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() * obj.addNum(num) * var param_2 = obj.findMedian() */
Array With Elements Not Equal to Average of Neighbors
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 .   Example 1: Input: nums = [1,2,3,4,5] Output: [1,2,4,5,3] Explanation: When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. Example 2: Input: nums = [6,2,0,9,7] Output: [9,7,6,2,0] Explanation: When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3. Note that the original array [6,2,0,9,7] also satisfies the conditions.   Constraints: 3 <= nums.length <= 10 5 0 <= nums[i] <= 10 5
null
null
class Solution { public: vector<int> rearrangeArray(vector<int>& nums) { ranges::sort(nums); vector<int> ans; int n = nums.size(); int m = (n + 1) >> 1; for (int i = 0; i < m; ++i) { ans.push_back(nums[i]); if (i + m < n) { ans.push_back(nums[i + m]); } } return ans; } };
null
null
func rearrangeArray(nums []int) (ans []int) { sort.Ints(nums) n := len(nums) m := (n + 1) >> 1 for i := 0; i < m; i++ { ans = append(ans, nums[i]) if i+m < n { ans = append(ans, nums[i+m]) } } return }
class Solution { public int[] rearrangeArray(int[] nums) { Arrays.sort(nums); int n = nums.length; int m = (n + 1) >> 1; int[] ans = new int[n]; for (int i = 0, j = 0; i < n; i += 2, j++) { ans[i] = nums[j]; if (j + m < n) { ans[i + 1] = nums[j + m]; } } return ans; } }
null
null
null
null
null
null
class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: nums.sort() n = len(nums) m = (n + 1) // 2 ans = [] for i in range(m): ans.append(nums[i]) if i + m < n: ans.append(nums[i + m]) return ans
null
null
null
null
null
function rearrangeArray(nums: number[]): number[] { nums.sort((a, b) => a - b); const n = nums.length; const m = (n + 1) >> 1; const ans: number[] = []; for (let i = 0; i < m; i++) { ans.push(nums[i]); if (i + m < n) { ans.push(nums[i + m]); } } return ans; }
Maximum Number of Coins You Can Get
There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows: In each step, you will choose any 3 piles of coins (not necessarily consecutive). Of your choice, Alice will pick the pile with the maximum number of coins. You will pick the next pile with the maximum number of coins. Your friend Bob will pick the last pile. Repeat until there are no more piles of coins. Given an array of integers piles where piles[i] is the number of coins in the i th pile. Return the maximum number of coins that you can have.   Example 1: Input: piles = [2,4,1,2,7,8] Output: 9 Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On 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. Example 2: Input: piles = [2,4,5] Output: 4 Example 3: Input: piles = [9,8,7,6,5,1,2,3,4] Output: 18   Constraints: 3 <= piles.length <= 10 5 piles.length % 3 == 0 1 <= piles[i] <= 10 4
int compare(const void* a, const void* b) { return (*(int*) a - *(int*) b); } int maxCoins(int* piles, int pilesSize) { qsort(piles, pilesSize, sizeof(int), compare); int ans = 0; for (int i = pilesSize / 3; i < pilesSize; i += 2) { ans += piles[i]; } return ans; }
null
class Solution { public: int maxCoins(vector<int>& piles) { ranges::sort(piles); int ans = 0; for (int i = piles.size() / 3; i < piles.size(); i += 2) { ans += piles[i]; } return ans; } };
null
null
func maxCoins(piles []int) (ans int) { sort.Ints(piles) for i := len(piles) / 3; i < len(piles); i += 2 { ans += piles[i] } return }
class Solution { public int maxCoins(int[] piles) { Arrays.sort(piles); int ans = 0; for (int i = piles.length / 3; i < piles.length; i += 2) { ans += piles[i]; } return ans; } }
null
null
null
null
null
null
class Solution: def maxCoins(self, piles: List[int]) -> int: piles.sort() return sum(piles[len(piles) // 3 :][::2])
null
impl Solution { pub fn max_coins(mut piles: Vec<i32>) -> i32 { piles.sort(); let mut ans = 0; for i in (piles.len() / 3..piles.len()).step_by(2) { ans += piles[i]; } ans } }
null
null
null
function maxCoins(piles: number[]): number { piles.sort((a, b) => a - b); let ans = 0; for (let i = piles.length / 3; i < piles.length; i += 2) { ans += piles[i]; } return ans; }
Check If Digits Are Equal in String After Operations I
You are given a string s consisting of digits. Perform the following operation repeatedly until the string has exactly two digits: For each pair of consecutive digits in s , starting from the first digit, calculate a new digit as the sum of the two digits modulo 10. Replace 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 .   Example 1: Input: s = "3902" Output: true Explanation: Initially, s = "3902" First operation: (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" Second operation: (s[0] + s[1]) % 10 = (2 + 9) % 10 = 1 (s[1] + s[2]) % 10 = (9 + 2) % 10 = 1 s becomes "11" Since the digits in "11" are the same, the output is true . Example 2: Input: s = "34789" Output: false Explanation: Initially, s = "34789" . After the first operation, s = "7157" . After the second operation, s = "862" . After the third operation, s = "48" . Since '4' != '8' , the output is false .   Constraints: 3 <= s.length <= 100 s consists of only digits.
null
null
class Solution { public: bool hasSameDigits(string s) { int n = s.size(); string t = s; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (t[i] - '0' + t[i + 1] - '0') % 10 + '0'; } } return t[0] == t[1]; } };
null
null
func hasSameDigits(s string) bool { t := []byte(s) n := len(t) for k := n - 1; k > 1; k-- { for i := 0; i < k; i++ { t[i] = (t[i]-'0'+t[i+1]-'0')%10 + '0' } } return t[0] == t[1] }
class Solution { public boolean hasSameDigits(String s) { char[] t = s.toCharArray(); int n = t.length; for (int k = n - 1; k > 1; --k) { for (int i = 0; i < k; ++i) { t[i] = (char) ((t[i] - '0' + t[i + 1] - '0') % 10 + '0'); } } return t[0] == t[1]; } }
null
null
null
null
null
null
class Solution: def hasSameDigits(self, s: str) -> bool: t = list(map(int, s)) n = len(t) for k in range(n - 1, 1, -1): for i in range(k): t[i] = (t[i] + t[i + 1]) % 10 return t[0] == t[1]
null
null
null
null
null
function hasSameDigits(s: string): boolean { const t = s.split('').map(Number); const n = t.length; for (let k = n - 1; k > 1; --k) { for (let i = 0; i < k; ++i) { t[i] = (t[i] + t[i + 1]) % 10; } } return t[0] === t[1]; }
Complete Binary Tree Inserter
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. Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion. Implement 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.   Example 1: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] Explanation CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // return 1 cBTInserter.insert(4); // return 2 cBTInserter.get_root(); // return [1, 2, 3, 4]   Constraints: The number of nodes in the tree will be in the range [1, 1000] . 0 <= Node.val <= 5000 root is a complete binary tree. 0 <= val <= 5000 At most 10 4 calls will be made to insert and get_root .
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class CBTInserter { public: CBTInserter(TreeNode* root) { queue<TreeNode*> q{{root}}; while (q.size()) { for (int i = q.size(); i; --i) { auto node = q.front(); q.pop(); tree.push_back(node); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } } } int insert(int val) { auto p = tree[(tree.size() - 1) / 2]; auto node = new TreeNode(val); tree.push_back(node); if (!p->left) { p->left = node; } else { p->right = node; } return p->val; } TreeNode* get_root() { return tree[0]; } private: vector<TreeNode*> tree; }; /** * Your CBTInserter object will be instantiated and called as such: * CBTInserter* obj = new CBTInserter(root); * int param_1 = obj->insert(val); * TreeNode* param_2 = obj->get_root(); */
null
null
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type CBTInserter struct { tree []*TreeNode } func Constructor(root *TreeNode) CBTInserter { q := []*TreeNode{root} tree := []*TreeNode{} for len(q) > 0 { for i := len(q); i > 0; i-- { node := q[0] q = q[1:] tree = append(tree, node) if node.Left != nil { q = append(q, node.Left) } if node.Right != nil { q = append(q, node.Right) } } } return CBTInserter{tree} } func (this *CBTInserter) Insert(val int) int { p := this.tree[(len(this.tree)-1)/2] node := &TreeNode{val, nil, nil} this.tree = append(this.tree, node) if p.Left == nil { p.Left = node } else { p.Right = node } return p.Val } func (this *CBTInserter) Get_root() *TreeNode { return this.tree[0] } /** * Your CBTInserter object will be instantiated and called as such: * obj := Constructor(root); * param_1 := obj.Insert(val); * param_2 := obj.Get_root(); */
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class CBTInserter { private List<TreeNode> tree = new ArrayList<>(); public CBTInserter(TreeNode root) { Deque<TreeNode> q = new ArrayDeque<>(); q.offer(root); while (!q.isEmpty()) { for (int i = q.size(); i > 0; --i) { TreeNode node = q.poll(); tree.add(node); if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } } } public int insert(int val) { TreeNode p = tree.get((tree.size() - 1) / 2); TreeNode node = new TreeNode(val); tree.add(node); if (p.left == null) { p.left = node; } else { p.right = node; } return p.val; } public TreeNode get_root() { return tree.get(0); } } /** * Your CBTInserter object will be instantiated and called as such: * CBTInserter obj = new CBTInserter(root); * int param_1 = obj.insert(val); * TreeNode param_2 = obj.get_root(); */
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root */ var CBTInserter = function (root) { this.tree = []; if (root === null) { return; } const q = [root]; while (q.length) { const t = []; for (const node of q) { this.tree.push(node); node.left !== null && t.push(node.left); node.right !== null && t.push(node.right); } q.splice(0, q.length, ...t); } }; /** * @param {number} val * @return {number} */ CBTInserter.prototype.insert = function (val) { const p = this.tree[(this.tree.length - 1) >> 1]; const node = new TreeNode(val); this.tree.push(node); if (p.left === null) { p.left = node; } else { p.right = node; } return p.val; }; /** * @return {TreeNode} */ CBTInserter.prototype.get_root = function () { return this.tree[0]; }; /** * Your CBTInserter object will be instantiated and called as such: * var obj = new CBTInserter(root) * var param_1 = obj.insert(val) * var param_2 = obj.get_root() */
null
null
null
null
null
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class CBTInserter: def __init__(self, root: Optional[TreeNode]): self.tree = [] q = deque([root]) while q: for _ in range(len(q)): node = q.popleft() self.tree.append(node) if node.left: q.append(node.left) if node.right: q.append(node.right) def insert(self, val: int) -> int: p = self.tree[(len(self.tree) - 1) // 2] node = TreeNode(val) self.tree.append(node) if p.left is None: p.left = node else: p.right = node return p.val def get_root(self) -> Optional[TreeNode]: return self.tree[0] # Your CBTInserter object will be instantiated and called as such: # obj = CBTInserter(root) # param_1 = obj.insert(val) # param_2 = obj.get_root()
null
null
null
null
null
/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ class CBTInserter { private tree: TreeNode[] = []; constructor(root: TreeNode | null) { if (root === null) { return; } const q: TreeNode[] = [root]; while (q.length) { const t: TreeNode[] = []; for (const node of q) { this.tree.push(node); node.left !== null && t.push(node.left); node.right !== null && t.push(node.right); } q.splice(0, q.length, ...t); } } insert(val: number): number { const p = this.tree[(this.tree.length - 1) >> 1]; const node = new TreeNode(val); this.tree.push(node); if (p.left === null) { p.left = node; } else { p.right = node; } return p.val; } get_root(): TreeNode | null { return this.tree[0]; } } /** * Your CBTInserter object will be instantiated and called as such: * var obj = new CBTInserter(root) * var param_1 = obj.insert(val) * var param_2 = obj.get_root() */
Closest Fair Integer 🔒
You are given a positive integer n . We call an integer k fair if the number of even digits in k is equal to the number of odd digits in it. Return the smallest fair integer that is greater than or equal to n .   Example 1: Input: n = 2 Output: 10 Explanation: The smallest fair integer that is greater than or equal to 2 is 10. 10 is fair because it has an equal number of even and odd digits (one odd digit and one even digit). Example 2: Input: n = 403 Output: 1001 Explanation: The smallest fair integer that is greater than or equal to 403 is 1001. 1001 is fair because it has an equal number of even and odd digits (two odd digits and two even digits).   Constraints: 1 <= n <= 10 9
null
null
class Solution { public: int closestFair(int n) { int a = 0, b = 0; int t = n, k = 0; while (t) { if ((t % 10) & 1) { ++a; } else { ++b; } ++k; t /= 10; } if (a == b) { return n; } if (k % 2 == 1) { int x = pow(10, k); int y = 0; for (int i = 0; i < k >> 1; ++i) { y = y * 10 + 1; } return x + y; } return closestFair(n + 1); } };
null
null
func closestFair(n int) int { a, b := 0, 0 t, k := n, 0 for t > 0 { if (t%10)%2 == 1 { a++ } else { b++ } k++ t /= 10 } if a == b { return n } if k%2 == 1 { x := int(math.Pow(10, float64(k))) y := 0 for i := 0; i < k>>1; i++ { y = y*10 + 1 } return x + y } return closestFair(n + 1) }
class Solution { public int closestFair(int n) { int a = 0, b = 0; int k = 0, t = n; while (t > 0) { if ((t % 10) % 2 == 1) { ++a; } else { ++b; } t /= 10; ++k; } if (k % 2 == 1) { int x = (int) Math.pow(10, k); int y = 0; for (int i = 0; i < k >> 1; ++i) { y = y * 10 + 1; } return x + y; } if (a == b) { return n; } return closestFair(n + 1); } }
null
null
null
null
null
null
class Solution: def closestFair(self, n: int) -> int: a = b = k = 0 t = n while t: if (t % 10) & 1: a += 1 else: b += 1 t //= 10 k += 1 if k & 1: x = 10**k y = int('1' * (k >> 1) or '0') return x + y if a == b: return n return self.closestFair(n + 1)
null
null
null
null
null
null
Minimum Subarrays in a Valid Split 🔒
You are given an integer array nums . Splitting of an integer array nums into subarrays is valid if: the greatest common divisor of the first and last elements of each subarray is greater than 1 , and each element of nums belongs to exactly one subarray. Return the minimum number of subarrays in a valid subarray splitting of nums . If a valid subarray splitting is not possible, return -1 . Note that: The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers. A subarray is a contiguous non-empty part of an array.   Example 1: Input: nums = [2,6,3,4,3] Output: 2 Explanation: We can create a valid split in the following way: [2,6] | [3,4,3]. - The starting element of the 1 st subarray is 2 and the ending is 6. Their greatest common divisor is 2, which is greater than 1. - The starting element of the 2 nd subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1. It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split. Example 2: Input: nums = [3,5] Output: 2 Explanation: We can create a valid split in the following way: [3] | [5]. - The starting element of the 1 st subarray is 3 and the ending is 3. Their greatest common divisor is 3, which is greater than 1. - The starting element of the 2 nd subarray is 5 and the ending is 5. Their greatest common divisor is 5, which is greater than 1. It can be proved that 2 is the minimum number of subarrays that we can obtain in a valid split. Example 3: Input: nums = [1,2,1] Output: -1 Explanation: It is impossible to create valid split.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i] <= 10 5
null
null
class Solution { public: const int inf = 0x3f3f3f3f; int validSubarraySplit(vector<int>& nums) { int n = nums.size(); vector<int> f(n); function<int(int)> dfs = [&](int i) -> int { if (i >= n) return 0; if (f[i]) return f[i]; int ans = inf; for (int j = i; j < n; ++j) { if (__gcd(nums[i], nums[j]) > 1) { ans = min(ans, 1 + dfs(j + 1)); } } f[i] = ans; return ans; }; int ans = dfs(0); return ans < inf ? ans : -1; } };
null
null
func validSubarraySplit(nums []int) int { n := len(nums) f := make([]int, n) var dfs func(int) int const inf int = 0x3f3f3f3f dfs = func(i int) int { if i >= n { return 0 } if f[i] > 0 { return f[i] } ans := inf for j := i; j < n; j++ { if gcd(nums[i], nums[j]) > 1 { ans = min(ans, 1+dfs(j+1)) } } f[i] = ans return ans } ans := dfs(0) if ans < inf { return ans } return -1 } func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) }
class Solution { private int n; private int[] f; private int[] nums; private int inf = 0x3f3f3f3f; public int validSubarraySplit(int[] nums) { n = nums.length; f = new int[n]; this.nums = nums; int ans = dfs(0); return ans < inf ? ans : -1; } private int dfs(int i) { if (i >= n) { return 0; } if (f[i] > 0) { return f[i]; } int ans = inf; for (int j = i; j < n; ++j) { if (gcd(nums[i], nums[j]) > 1) { ans = Math.min(ans, 1 + dfs(j + 1)); } } f[i] = ans; return ans; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
null
null
null
null
null
null
class Solution: def validSubarraySplit(self, nums: List[int]) -> int: @cache def dfs(i): if i >= n: return 0 ans = inf for j in range(i, n): if gcd(nums[i], nums[j]) > 1: ans = min(ans, 1 + dfs(j + 1)) return ans n = len(nums) ans = dfs(0) dfs.cache_clear() return ans if ans < inf else -1
null
null
null
null
null
null
Longest Palindrome by Concatenating Two Letter Words
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.   Example 1: Input: words = ["lc","cl","gg"] Output: 6 Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of length 6. Note that "clgglc" is another longest palindrome that can be created. Example 2: Input: words = ["ab","ty","yt","lc","cl","ab"] Output: 8 Explanation: One longest palindrome is "ty" + "lc" + "cl" + "yt" = "tylcclyt", of length 8. Note that "lcyttycl" is another longest palindrome that can be created. Example 3: Input: words = ["cc","ll","xx"] Output: 2 Explanation: One longest palindrome is "cc", of length 2. Note that "ll" is another longest palindrome that can be created, and so is "xx".   Constraints: 1 <= words.length <= 10 5 words[i].length == 2 words[i] consists of lowercase English letters.
null
null
class Solution { public: int longestPalindrome(vector<string>& words) { unordered_map<string, int> cnt; for (auto& w : words) cnt[w]++; int ans = 0, x = 0; for (auto& [k, v] : cnt) { string rk = k; reverse(rk.begin(), rk.end()); if (k[0] == k[1]) { x += v & 1; ans += v / 2 * 2 * 2; } else if (cnt.count(rk)) { ans += min(v, cnt[rk]) * 2; } } ans += x ? 2 : 0; return ans; } };
null
null
func longestPalindrome(words []string) int { cnt := map[string]int{} for _, w := range words { cnt[w]++ } ans, x := 0, 0 for k, v := range cnt { if k[0] == k[1] { x += v & 1 ans += v / 2 * 2 * 2 } else { rk := string([]byte{k[1], k[0]}) if y, ok := cnt[rk]; ok { ans += min(v, y) * 2 } } } if x > 0 { ans += 2 } return ans }
class Solution { public int longestPalindrome(String[] words) { Map<String, Integer> cnt = new HashMap<>(); for (var w : words) { cnt.merge(w, 1, Integer::sum); } int ans = 0, x = 0; for (var e : cnt.entrySet()) { var k = e.getKey(); var rk = new StringBuilder(k).reverse().toString(); int v = e.getValue(); if (k.charAt(0) == k.charAt(1)) { x += v & 1; ans += v / 2 * 2 * 2; } else { ans += Math.min(v, cnt.getOrDefault(rk, 0)) * 2; } } ans += x > 0 ? 2 : 0; return ans; } }
null
null
null
null
null
null
class Solution: def longestPalindrome(self, words: List[str]) -> int: cnt = Counter(words) ans = x = 0 for k, v in cnt.items(): if k[0] == k[1]: x += v & 1 ans += v // 2 * 2 * 2 else: ans += min(v, cnt[k[::-1]]) * 2 ans += 2 if x else 0 return ans
null
null
null
null
null
function longestPalindrome(words: string[]): number { const cnt = new Map<string, number>(); for (const w of words) cnt.set(w, (cnt.get(w) || 0) + 1); let [ans, x] = [0, 0]; for (const [k, v] of cnt.entries()) { if (k[0] === k[1]) { x += v & 1; ans += Math.floor(v / 2) * 2 * 2; } else { ans += Math.min(v, cnt.get(k[1] + k[0]) || 0) * 2; } } ans += x ? 2 : 0; return ans; }
Maximum Segment Sum After Removals
You are given two 0-indexed integer arrays nums and removeQueries , both of length n . For the i th 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 i th removal. Note: The same index will not be removed more than once.   Example 1: Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1] Output: [14,7,2,2,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 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]. Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5]. Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [14,7,2,2,0]. Example 2: Input: nums = [3,2,11,1], removeQueries = [3,2,1,0] Output: [16,5,3,0] Explanation: Using 0 to indicate a removed element, the answer is as follows: Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11]. Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2]. Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3]. Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments. Finally, we return [16,5,3,0].   Constraints: n == nums.length == removeQueries.length 1 <= n <= 10 5 1 <= nums[i] <= 10 9 0 <= removeQueries[i] < n All the values of removeQueries are unique .
null
null
using ll = long long; class Solution { public: vector<int> p; vector<ll> s; vector<long long> maximumSegmentSum(vector<int>& nums, vector<int>& removeQueries) { int n = nums.size(); p.resize(n); for (int i = 0; i < n; ++i) p[i] = i; s.assign(n, 0); vector<ll> ans(n); ll mx = 0; for (int j = n - 1; j; --j) { int i = removeQueries[j]; s[i] = nums[i]; if (i && s[find(i - 1)]) merge(i, i - 1); if (i < n - 1 && s[find(i + 1)]) merge(i, i + 1); mx = max(mx, s[find(i)]); ans[j - 1] = mx; } return ans; } int find(int x) { if (p[x] != x) p[x] = find(p[x]); return p[x]; } void merge(int a, int b) { int pa = find(a), pb = find(b); p[pa] = pb; s[pb] += s[pa]; } };
null
null
func maximumSegmentSum(nums []int, removeQueries []int) []int64 { n := len(nums) p := make([]int, n) s := make([]int, n) for i := range p { p[i] = i } var find func(x int) int find = func(x int) int { if p[x] != x { p[x] = find(p[x]) } return p[x] } merge := func(a, b int) { pa, pb := find(a), find(b) p[pa] = pb s[pb] += s[pa] } mx := 0 ans := make([]int64, n) for j := n - 1; j > 0; j-- { i := removeQueries[j] s[i] = nums[i] if i > 0 && s[find(i-1)] > 0 { merge(i, i-1) } if i < n-1 && s[find(i+1)] > 0 { merge(i, i+1) } mx = max(mx, s[find(i)]) ans[j-1] = int64(mx) } return ans }
class Solution { private int[] p; private long[] s; public long[] maximumSegmentSum(int[] nums, int[] removeQueries) { int n = nums.length; p = new int[n]; s = new long[n]; for (int i = 0; i < n; ++i) { p[i] = i; } long[] ans = new long[n]; long mx = 0; for (int j = n - 1; j > 0; --j) { int i = removeQueries[j]; s[i] = nums[i]; if (i > 0 && s[find(i - 1)] > 0) { merge(i, i - 1); } if (i < n - 1 && s[find(i + 1)] > 0) { merge(i, i + 1); } mx = Math.max(mx, s[find(i)]); ans[j - 1] = mx; } return ans; } private int find(int x) { if (p[x] != x) { p[x] = find(p[x]); } return p[x]; } private void merge(int a, int b) { int pa = find(a), pb = find(b); p[pa] = pb; s[pb] += s[pa]; } }
null
null
null
null
null
null
class Solution: def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]: def find(x): if p[x] != x: p[x] = find(p[x]) return p[x] def merge(a, b): pa, pb = find(a), find(b) p[pa] = pb s[pb] += s[pa] n = len(nums) p = list(range(n)) s = [0] * n ans = [0] * n mx = 0 for j in range(n - 1, 0, -1): i = removeQueries[j] s[i] = nums[i] if i and s[find(i - 1)]: merge(i, i - 1) if i < n - 1 and s[find(i + 1)]: merge(i, i + 1) mx = max(mx, s[find(i)]) ans[j - 1] = mx return ans
null
null
null
null
null
null
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4