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
Encode N-ary Tree to Binary Tree 🔒
Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example). For example, you may encode the following 3-ary tree to a binary tree in this way: Input: root = [1,null,3,2,4,null,5,6] Note that the above is just an example which might or might not work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.   Example 1: Input: root = [1,null,3,2,4,null,5,6] Output: [1,null,3,2,4,null,5,6] Example 2: Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Output: [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14] Example 3: Input: root = [] Output: []   Constraints: The number of nodes in the tree is in the range [0, 10 4 ] . 0 <= Node.val <= 10 4 The height of the n-ary tree is less than or equal to 1000 Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
null
null
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes an n-ary tree to a binary tree. TreeNode* encode(Node* root) { if (root == nullptr) { return nullptr; } TreeNode* node = new TreeNode(root->val); if (root->children.empty()) { return node; } TreeNode* left = encode(root->children[0]); node->left = left; for (int i = 1; i < root->children.size(); i++) { left->right = encode(root->children[i]); left = left->right; } return node; } // Decodes your binary tree to an n-ary tree. Node* decode(TreeNode* data) { if (data == nullptr) { return nullptr; } Node* node = new Node(data->val, vector<Node*>()); if (data->left == nullptr) { return node; } TreeNode* left = data->left; while (left != nullptr) { node->children.push_back(decode(left)); left = left->right; } return node; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.decode(codec.encode(root));
null
null
/** * Definition for a Node. * type Node struct { * Val int * Children []*Node * } */ /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type Codec struct { } func Constructor() *Codec { return &Codec{} } // Encodes an n-ary tree to a binary tree. func (this *Codec) encode(root *Node) *TreeNode { if root == nil { return nil } node := &TreeNode{Val: root.Val} if len(root.Children) == 0 { return node } left := this.encode(root.Children[0]) node.Left = left for i := 1; i < len(root.Children); i++ { left.Right = this.encode(root.Children[i]) left = left.Right } return node } // Decodes your binary tree to an n-ary tree. func (this *Codec) decode(data *TreeNode) *Node { if data == nil { return nil } node := &Node{Val: data.Val, Children: []*Node{}} if data.Left == nil { return node } left := data.Left for left != nil { node.Children = append(node.Children, this.decode(left)) left = left.Right } return node } /** * Your Codec object will be instantiated and called as such: * obj := Constructor(); * bst := obj.encode(root); * ans := obj.decode(bst); */
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Codec { // Encodes an n-ary tree to a binary tree. public TreeNode encode(Node root) { if (root == null) { return null; } TreeNode node = new TreeNode(root.val); if (root.children == null || root.children.isEmpty()) { return node; } TreeNode left = encode(root.children.get(0)); node.left = left; for (int i = 1; i < root.children.size(); i++) { left.right = encode(root.children.get(i)); left = left.right; } return node; } // Decodes your binary tree to an n-ary tree. public Node decode(TreeNode data) { if (data == null) { return null; } Node node = new Node(data.val, new ArrayList<>()); if (data.left == null) { return node; } TreeNode left = data.left; while (left != null) { node.children.add(decode(left)); left = left.right; } return node; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(root));
null
null
null
null
null
null
""" # Definition for a Node. class Node: def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None): self.val = val self.children = children """ """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ class Codec: # Encodes an n-ary tree to a binary tree. def encode(self, root: "Optional[Node]") -> Optional[TreeNode]: if root is None: return None node = TreeNode(root.val) if not root.children: return node left = self.encode(root.children[0]) node.left = left for child in root.children[1:]: left.right = self.encode(child) left = left.right return node # Decodes your binary tree to an n-ary tree. def decode(self, data: Optional[TreeNode]) -> "Optional[Node]": if data is None: return None node = Node(data.val, []) if data.left is None: return node left = data.left while left: node.children.append(self.decode(left)) left = left.right return node # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(root))
null
null
null
null
null
/** * Definition for _Node. * class _Node { * val: number * children: _Node[] * * constructor(v: number) { * this.val = v; * this.children = []; * } * } */ /** * 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 Codec { constructor() {} // Encodes an n-ary tree to a binary tree. serialize(root: _Node | null): TreeNode | null { if (root === null) { return null; } const node = new TreeNode(root.val); if (root.children.length === 0) { return node; } let left: TreeNode | null = this.serialize(root.children[0]); node.left = left; for (let i = 1; i < root.children.length; i++) { if (left) { left.right = this.serialize(root.children[i]); left = left.right; } } return node; } // Decodes your binary tree back to an n-ary tree. deserialize(root: TreeNode | null): _Node | null { if (root === null) { return null; } const node = new _Node(root.val); if (root.left === null) { return node; } let left: TreeNode | null = root.left; while (left !== null) { node.children.push(this.deserialize(left)); left = left.right; } return node; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
Paint Fence 🔒
You are painting a fence of n posts with k different colors. You must paint the posts following these rules: Every post must be painted exactly one color. There cannot be three or more consecutive posts with the same color. Given the two integers n and k , return the number of ways you can paint the fence .   Example 1: Input: n = 3, k = 2 Output: 6 Explanation: All the possibilities are shown. Note that painting all the posts red or all the posts green is invalid because there cannot be three posts in a row with the same color. Example 2: Input: n = 1, k = 1 Output: 1 Example 3: Input: n = 7, k = 2 Output: 42   Constraints: 1 <= n <= 50 1 <= k <= 10 5 The testcases are generated such that the answer is in the range [0, 2 31 - 1] for the given n and k .
null
null
class Solution { public: int numWays(int n, int k) { int f = k, g = 0; for (int i = 1; i < n; ++i) { int ff = (f + g) * (k - 1); g = f; f = ff; } return f + g; } };
null
null
func numWays(n int, k int) int { f, g := k, 0 for i := 1; i < n; i++ { f, g = (f+g)*(k-1), f } return f + g }
class Solution { public int numWays(int n, int k) { int f = k, g = 0; for (int i = 1; i < n; ++i) { int ff = (f + g) * (k - 1); g = f; f = ff; } return f + g; } }
null
null
null
null
null
null
class Solution: def numWays(self, n: int, k: int) -> int: f, g = k, 0 for _ in range(n - 1): ff = (f + g) * (k - 1) g = f f = ff return f + g
null
null
null
null
null
function numWays(n: number, k: number): number { let [f, g] = [k, 0]; for (let i = 1; i < n; ++i) { const ff = (f + g) * (k - 1); g = f; f = ff; } return f + g; }
Smallest Good Base
Given an integer n represented as a string, return the smallest good base of n . We call k >= 2 a good base of n , if all digits of n base k are 1 's.   Example 1: Input: n = "13" Output: "3" Explanation: 13 base 3 is 111. Example 2: Input: n = "4681" Output: "8" Explanation: 4681 base 8 is 11111. Example 3: Input: n = "1000000000000000000" Output: "999999999999999999" Explanation: 1000000000000000000 base 999999999999999999 is 11.   Constraints: n is an integer in the range [3, 10 18 ] . n does not contain any leading zeros.
null
null
class Solution { public: string smallestGoodBase(string n) { long v = stol(n); int mx = floor(log(v) / log(2)); for (int m = mx; m > 1; --m) { int k = pow(v, 1.0 / m); long mul = 1, s = 1; for (int i = 0; i < m; ++i) { mul *= k; s += mul; } if (s == v) { return to_string(k); } } return to_string(v - 1); } };
null
null
null
class Solution { public String smallestGoodBase(String n) { long num = Long.parseLong(n); for (int len = 63; len >= 2; --len) { long radix = getRadix(len, num); if (radix != -1) { return String.valueOf(radix); } } return String.valueOf(num - 1); } private long getRadix(int len, long num) { long l = 2, r = num - 1; while (l < r) { long mid = l + r >>> 1; if (calc(mid, len) >= num) r = mid; else l = mid + 1; } return calc(r, len) == num ? r : -1; } private long calc(long radix, int len) { long p = 1; long sum = 0; for (int i = 0; i < len; ++i) { if (Long.MAX_VALUE - sum < p) { return Long.MAX_VALUE; } sum += p; if (Long.MAX_VALUE / p < radix) { p = Long.MAX_VALUE; } else { p *= radix; } } return sum; } }
null
null
null
null
null
null
class Solution: def smallestGoodBase(self, n: str) -> str: def cal(k, m): p = s = 1 for i in range(m): p *= k s += p return s num = int(n) for m in range(63, 1, -1): l, r = 2, num - 1 while l < r: mid = (l + r) >> 1 if cal(mid, m) >= num: r = mid else: l = mid + 1 if cal(l, m) == num: return str(l) return str(num - 1)
null
null
null
null
null
null
Valid Triangle Number
Given an integer array nums , return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle .   Example 1: Input: nums = [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Example 2: Input: nums = [4,2,3,4] Output: 4   Constraints: 1 <= nums.length <= 1000 0 <= nums[i] <= 1000
null
null
class Solution { public: int triangleNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); int ans = 0, n = nums.size(); for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { int k = lower_bound(nums.begin() + j + 1, nums.end(), nums[i] + nums[j]) - nums.begin() - 1; ans += k - j; } } return ans; } };
null
null
func triangleNumber(nums []int) int { sort.Ints(nums) ans := 0 for i, n := 0, len(nums); i < n-2; i++ { for j := i + 1; j < n-1; j++ { left, right := j+1, n for left < right { mid := (left + right) >> 1 if nums[mid] >= nums[i]+nums[j] { right = mid } else { left = mid + 1 } } ans += left - j - 1 } } return ans }
class Solution { public int triangleNumber(int[] nums) { Arrays.sort(nums); int ans = 0; for (int i = 0, n = nums.length; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { int left = j + 1, right = n; while (left < right) { int mid = (left + right) >> 1; if (nums[mid] >= nums[i] + nums[j]) { right = mid; } else { left = mid + 1; } } ans += left - j - 1; } } return ans; } }
null
null
null
null
null
null
class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() ans, n = 0, len(nums) for i in range(n - 2): for j in range(i + 1, n - 1): k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1 ans += k - j return ans
null
impl Solution { pub fn triangle_number(mut nums: Vec<i32>) -> i32 { nums.sort(); let n = nums.len(); let mut res = 0; for i in (2..n).rev() { let mut left = 0; let mut right = i - 1; while left < right { if nums[left] + nums[right] > nums[i] { res += right - left; right -= 1; } else { left += 1; } } } res as i32 } }
null
null
null
function triangleNumber(nums: number[]): number { nums.sort((a, b) => a - b); let n = nums.length; let ans = 0; for (let i = n - 1; i >= 2; i--) { let left = 0, right = i - 1; while (left < right) { if (nums[left] + nums[right] > nums[i]) { ans += right - left; right--; } else { left++; } } } return ans; }
Remove Colored Pieces if Both Neighbors are the Same Color
There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B' . You are given a string colors of length n where colors[i] is the color of the i th piece. Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first . Alice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A' . She is not allowed to remove pieces that are colored 'B' . Bob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B' . He is not allowed to remove pieces that are colored 'A' . Alice and Bob cannot remove pieces from the edge of the line. If a player cannot make a move on their turn, that player loses and the other player wins . Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins .   Example 1: Input: colors = "AAABABB" Output: true Explanation: A A ABABB -> AABABB Alice moves first. She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'. Now it's Bob's turn. Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'. Thus, Alice wins, so return true. Example 2: Input: colors = "AA" Output: false Explanation: Alice has her turn first. There are only two 'A's and both are on the edge of the line, so she cannot move on her turn. Thus, Bob wins, so return false. Example 3: Input: colors = "ABBBBBBBAAA" Output: false Explanation: ABBBBBBBA A A -> ABBBBBBBAA Alice moves first. Her only option is to remove the second to last 'A' from the right. ABBBB B BBAA -> ABBBBBBAA Next is Bob's turn. He has many options for which 'B' piece to remove. He can pick any. On Alice's second turn, she has no more pieces that she can remove. Thus, Bob wins, so return false.   Constraints: 1 <= colors.length <= 10 5 colors  consists of only the letters  'A'  and  'B'
null
null
class Solution { public: bool winnerOfGame(string colors) { int n = colors.size(); int a = 0, b = 0; for (int i = 0, j = 0; i < n; i = j) { while (j < n && colors[j] == colors[i]) { ++j; } int m = j - i - 2; if (m > 0) { if (colors[i] == 'A') { a += m; } else { b += m; } } } return a > b; } };
null
null
func winnerOfGame(colors string) bool { n := len(colors) a, b := 0, 0 for i, j := 0, 0; i < n; i = j { for j < n && colors[j] == colors[i] { j++ } m := j - i - 2 if m > 0 { if colors[i] == 'A' { a += m } else { b += m } } } return a > b }
class Solution { public boolean winnerOfGame(String colors) { int n = colors.length(); int a = 0, b = 0; for (int i = 0, j = 0; i < n; i = j) { while (j < n && colors.charAt(j) == colors.charAt(i)) { ++j; } int m = j - i - 2; if (m > 0) { if (colors.charAt(i) == 'A') { a += m; } else { b += m; } } } return a > b; } }
null
null
null
null
null
null
class Solution: def winnerOfGame(self, colors: str) -> bool: a = b = 0 for c, v in groupby(colors): m = len(list(v)) - 2 if m > 0 and c == 'A': a += m elif m > 0 and c == 'B': b += m return a > b
null
null
null
null
null
function winnerOfGame(colors: string): boolean { const n = colors.length; let [a, b] = [0, 0]; for (let i = 0, j = 0; i < n; i = j) { while (j < n && colors[j] === colors[i]) { ++j; } const m = j - i - 2; if (m > 0) { if (colors[i] === 'A') { a += m; } else { b += m; } } } return a > b; }
Unique Paths
There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0] ). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1] ). The robot can only move either down or right at any point in time. Given the two integers m and n , return the number of possible unique paths that the robot can take to reach the bottom-right corner . The test cases are generated so that the answer will be less than or equal to 2 * 10 9 .   Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down   Constraints: 1 <= m, n <= 100
null
null
class Solution { public: int uniquePaths(int m, int n) { vector<int> f(n, 1); for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { f[j] += f[j - 1]; } } return f[n - 1]; } };
null
null
func uniquePaths(m int, n int) int { f := make([]int, n+1) for i := range f { f[i] = 1 } for i := 1; i < m; i++ { for j := 1; j < n; j++ { f[j] += f[j-1] } } return f[n-1] }
class Solution { public int uniquePaths(int m, int n) { int[] f = new int[n]; Arrays.fill(f, 1); for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { f[j] += f[j - 1]; } } return f[n - 1]; } }
/** * @param {number} m * @param {number} n * @return {number} */ var uniquePaths = function (m, n) { const f = Array(n).fill(1); for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { f[j] += f[j - 1]; } } return f[n - 1]; };
null
null
null
null
null
class Solution: def uniquePaths(self, m: int, n: int) -> int: f = [1] * n for _ in range(1, m): for j in range(1, n): f[j] += f[j - 1] return f[-1]
null
impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { let (m, n) = (m as usize, n as usize); let mut f = vec![1; n]; for i in 1..m { for j in 1..n { f[j] += f[j - 1]; } } f[n - 1] } }
null
null
null
function uniquePaths(m: number, n: number): number { const f: number[] = Array(n).fill(1); for (let i = 1; i < m; ++i) { for (let j = 1; j < n; ++j) { f[j] += f[j - 1]; } } return f[n - 1]; }
Count Strictly Increasing Subarrays 🔒
You are given an array nums consisting of positive integers. Return the number of subarrays of nums that are in strictly increasing order. A subarray is a contiguous part of an array.   Example 1: Input: nums = [1,3,5,4,4,6] Output: 10 Explanation: The strictly increasing subarrays are the following: - Subarrays of length 1: [1], [3], [5], [4], [4], [6]. - Subarrays of length 2: [1,3], [3,5], [4,6]. - Subarrays of length 3: [1,3,5]. The total number of subarrays is 6 + 3 + 1 = 10. Example 2: Input: nums = [1,2,3,4,5] Output: 15 Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take.   Constraints: 1 <= nums.length <= 10 5 1 <= nums[i] <= 10 6
null
null
class Solution { public: long long countSubarrays(vector<int>& nums) { long long ans = 1, cnt = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i - 1] < nums[i]) { ++cnt; } else { cnt = 1; } ans += cnt; } return ans; } };
null
null
func countSubarrays(nums []int) int64 { ans, cnt := 1, 1 for i, x := range nums[1:] { if nums[i] < x { cnt++ } else { cnt = 1 } ans += cnt } return int64(ans) }
class Solution { public long countSubarrays(int[] nums) { long ans = 1, cnt = 1; for (int i = 1; i < nums.length; ++i) { if (nums[i - 1] < nums[i]) { ++cnt; } else { cnt = 1; } ans += cnt; } return ans; } }
null
null
null
null
null
null
class Solution: def countSubarrays(self, nums: List[int]) -> int: ans = cnt = 1 for x, y in pairwise(nums): if x < y: cnt += 1 else: cnt = 1 ans += cnt return ans
null
null
null
null
null
function countSubarrays(nums: number[]): number { let [ans, cnt] = [1, 1]; for (let i = 1; i < nums.length; ++i) { if (nums[i - 1] < nums[i]) { ++cnt; } else { cnt = 1; } ans += cnt; } return ans; }
Find Mirror Score of a String
You are given a string s . We define the mirror of a letter in the English alphabet as its corresponding letter when the alphabet is reversed. For example, the mirror of 'a' is 'z' , and the mirror of 'y' is 'b' . Initially, all characters in the string s are unmarked . You start with a score of 0, and you perform the following process on the string s : Iterate through the string from left to right. At each index i , find the closest unmarked index j such that j < i and s[j] is the mirror of s[i] . Then, mark both indices i and j , and add the value i - j to the total score. If no such index j exists for the index i , move on to the next index without making any changes. Return the total score at the end of the process.   Example 1: Input: s = "aczzx" Output: 5 Explanation: i = 0 . There is no index j that satisfies the conditions, so we skip. i = 1 . There is no index j that satisfies the conditions, so we skip. i = 2 . The closest index j that satisfies the conditions is j = 0 , so we mark both indices 0 and 2, and then add 2 - 0 = 2 to the score. i = 3 . There is no index j that satisfies the conditions, so we skip. i = 4 . The closest index j that satisfies the conditions is j = 1 , so we mark both indices 1 and 4, and then add 4 - 1 = 3 to the score. Example 2: Input: s = "abcdef" Output: 0 Explanation: For each index i , there is no index j that satisfies the conditions.   Constraints: 1 <= s.length <= 10 5 s consists only of lowercase English letters.
null
null
class Solution { public: long long calculateScore(string s) { unordered_map<char, vector<int>> d; int n = s.length(); long long ans = 0; for (int i = 0; i < n; ++i) { char x = s[i]; char y = 'a' + 'z' - x; if (d.contains(y)) { vector<int>& ls = d[y]; int j = ls.back(); ls.pop_back(); if (ls.empty()) { d.erase(y); } ans += i - j; } else { d[x].push_back(i); } } return ans; } };
null
null
func calculateScore(s string) (ans int64) { d := make(map[rune][]int) for i, x := range s { y := 'a' + 'z' - x if ls, ok := d[y]; ok { j := ls[len(ls)-1] d[y] = ls[:len(ls)-1] if len(d[y]) == 0 { delete(d, y) } ans += int64(i - j) } else { d[x] = append(d[x], i) } } return }
class Solution { public long calculateScore(String s) { Map<Character, List<Integer>> d = new HashMap<>(26); int n = s.length(); long ans = 0; for (int i = 0; i < n; ++i) { char x = s.charAt(i); char y = (char) ('a' + 'z' - x); if (d.containsKey(y)) { var ls = d.get(y); int j = ls.remove(ls.size() - 1); if (ls.isEmpty()) { d.remove(y); } ans += i - j; } else { d.computeIfAbsent(x, k -> new ArrayList<>()).add(i); } } return ans; } }
null
null
null
null
null
null
class Solution: def calculateScore(self, s: str) -> int: d = defaultdict(list) ans = 0 for i, x in enumerate(s): y = chr(ord("a") + ord("z") - ord(x)) if d[y]: j = d[y].pop() ans += i - j else: d[x].append(i) return ans
null
null
null
null
null
function calculateScore(s: string): number { const d: Map<string, number[]> = new Map(); const n = s.length; let ans = 0; for (let i = 0; i < n; i++) { const x = s[i]; const y = String.fromCharCode('a'.charCodeAt(0) + 'z'.charCodeAt(0) - x.charCodeAt(0)); if (d.has(y)) { const ls = d.get(y)!; const j = ls.pop()!; if (ls.length === 0) { d.delete(y); } ans += i - j; } else { if (!d.has(x)) { d.set(x, []); } d.get(x)!.push(i); } } return ans; }
Minimum Number of Work Sessions to Finish the Tasks
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n , where the i th task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: If you start a task in a work session, you must complete it in the same work session. You can start a new task immediately after finishing the previous one. You may complete the tasks in any order . Given tasks and sessionTime , return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i] .   Example 1: Input: tasks = [1,2,3], sessionTime = 3 Output: 2 Explanation: You can finish the tasks in two work sessions. - First work session: finish the first and the second tasks in 1 + 2 = 3 hours. - Second work session: finish the third task in 3 hours. Example 2: Input: tasks = [3,1,3,1,1], sessionTime = 8 Output: 2 Explanation: You can finish the tasks in two work sessions. - First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours. - Second work session: finish the last task in 1 hour. Example 3: Input: tasks = [1,2,3,4,5], sessionTime = 15 Output: 1 Explanation: You can finish all the tasks in one work session.   Constraints: n == tasks.length 1 <= n <= 14 1 <= tasks[i] <= 10 max(tasks[i]) <= sessionTime <= 15
null
null
class Solution { public: int minSessions(vector<int>& tasks, int sessionTime) { int n = tasks.size(); bool ok[1 << n]; memset(ok, false, sizeof(ok)); for (int i = 1; i < 1 << n; ++i) { int t = 0; for (int j = 0; j < n; ++j) { if (i >> j & 1) { t += tasks[j]; } } ok[i] = t <= sessionTime; } int f[1 << n]; memset(f, 0x3f, sizeof(f)); f[0] = 0; for (int i = 1; i < 1 << n; ++i) { for (int j = i; j; j = (j - 1) & i) { if (ok[j]) { f[i] = min(f[i], f[i ^ j] + 1); } } } return f[(1 << n) - 1]; } };
null
null
func minSessions(tasks []int, sessionTime int) int { n := len(tasks) ok := make([]bool, 1<<n) f := make([]int, 1<<n) for i := 1; i < 1<<n; i++ { t := 0 f[i] = 1 << 30 for j, x := range tasks { if i>>j&1 == 1 { t += x } } ok[i] = t <= sessionTime } for i := 1; i < 1<<n; i++ { for j := i; j > 0; j = (j - 1) & i { if ok[j] { f[i] = min(f[i], f[i^j]+1) } } } return f[1<<n-1] }
class Solution { public int minSessions(int[] tasks, int sessionTime) { int n = tasks.length; boolean[] ok = new boolean[1 << n]; for (int i = 1; i < 1 << n; ++i) { int t = 0; for (int j = 0; j < n; ++j) { if ((i >> j & 1) == 1) { t += tasks[j]; } } ok[i] = t <= sessionTime; } int[] f = new int[1 << n]; Arrays.fill(f, 1 << 30); f[0] = 0; for (int i = 1; i < 1 << n; ++i) { for (int j = i; j > 0; j = (j - 1) & i) { if (ok[j]) { f[i] = Math.min(f[i], f[i ^ j] + 1); } } } return f[(1 << n) - 1]; } }
null
null
null
null
null
null
class Solution: def minSessions(self, tasks: List[int], sessionTime: int) -> int: n = len(tasks) ok = [False] * (1 << n) for i in range(1, 1 << n): t = sum(tasks[j] for j in range(n) if i >> j & 1) ok[i] = t <= sessionTime f = [inf] * (1 << n) f[0] = 0 for i in range(1, 1 << n): j = i while j: if ok[j]: f[i] = min(f[i], f[i ^ j] + 1) j = (j - 1) & i return f[-1]
null
null
null
null
null
function minSessions(tasks: number[], sessionTime: number): number { const n = tasks.length; const ok: boolean[] = new Array(1 << n).fill(false); for (let i = 1; i < 1 << n; ++i) { let t = 0; for (let j = 0; j < n; ++j) { if (((i >> j) & 1) === 1) { t += tasks[j]; } } ok[i] = t <= sessionTime; } const f: number[] = new Array(1 << n).fill(1 << 30); f[0] = 0; for (let i = 1; i < 1 << n; ++i) { for (let j = i; j > 0; j = (j - 1) & i) { if (ok[j]) { f[i] = Math.min(f[i], f[i ^ j] + 1); } } } return f[(1 << n) - 1]; }
Repeated DNA Sequences
The DNA sequence is composed of a series of nucleotides abbreviated as 'A' , 'C' , 'G' , and 'T' . For example, "ACGAATTCCG" is a DNA sequence . When studying DNA , it is useful to identify repeated sequences within the DNA. Given a string s that represents a DNA sequence , return all the 10 -letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order .   Example 1: Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" Output: ["AAAAACCCCC","CCCCCAAAAA"] Example 2: Input: s = "AAAAAAAAAAAAA" Output: ["AAAAAAAAAA"]   Constraints: 1 <= s.length <= 10 5 s[i] is either 'A' , 'C' , 'G' , or 'T' .
null
public class Solution { public IList<string> FindRepeatedDnaSequences(string s) { var cnt = new Dictionary<string, int>(); var ans = new List<string>(); for (int i = 0; i < s.Length - 10 + 1; ++i) { var t = s.Substring(i, 10); if (!cnt.ContainsKey(t)) { cnt[t] = 0; } if (++cnt[t] == 2) { ans.Add(t); } } return ans; } }
class Solution { public: vector<string> findRepeatedDnaSequences(string s) { unordered_map<string, int> cnt; vector<string> ans; for (int i = 0, n = s.size() - 10 + 1; i < n; ++i) { auto t = s.substr(i, 10); if (++cnt[t] == 2) { ans.emplace_back(t); } } return ans; } };
null
null
func findRepeatedDnaSequences(s string) []string { hashCode := map[byte]int{'A': 0, 'C': 1, 'G': 2, 'T': 3} ans, cnt, left, right := []string{}, map[int]int{}, 0, 0 sha, multi := 0, int(math.Pow(4, 9)) for ; right < len(s); right++ { sha = sha*4 + hashCode[s[right]] if right-left+1 < 10 { continue } cnt[sha]++ if cnt[sha] == 2 { ans = append(ans, s[left:right+1]) } sha, left = sha-multi*hashCode[s[left]], left+1 } return ans }
class Solution { public List<String> findRepeatedDnaSequences(String s) { Map<String, Integer> cnt = new HashMap<>(); List<String> ans = new ArrayList<>(); for (int i = 0; i < s.length() - 10 + 1; ++i) { String t = s.substring(i, i + 10); if (cnt.merge(t, 1, Integer::sum) == 2) { ans.add(t); } } return ans; } }
/** * @param {string} s * @return {string[]} */ var findRepeatedDnaSequences = function (s) { const cnt = new Map(); const ans = []; for (let i = 0; i < s.length - 10 + 1; ++i) { const t = s.slice(i, i + 10); cnt.set(t, (cnt.get(t) || 0) + 1); if (cnt.get(t) === 2) { ans.push(t); } } return ans; };
null
null
null
null
null
class Solution: def findRepeatedDnaSequences(self, s: str) -> List[str]: cnt = Counter() ans = [] for i in range(len(s) - 10 + 1): t = s[i : i + 10] cnt[t] += 1 if cnt[t] == 2: ans.append(t) return ans
null
use std::collections::HashMap; impl Solution { pub fn find_repeated_dna_sequences(s: String) -> Vec<String> { if s.len() < 10 { return vec![]; } let mut cnt = HashMap::new(); let mut ans = Vec::new(); for i in 0..s.len() - 9 { let t = &s[i..i + 10]; let count = cnt.entry(t).or_insert(0); *count += 1; if *count == 2 { ans.push(t.to_string()); } } ans } }
null
null
null
function findRepeatedDnaSequences(s: string): string[] { const n = s.length; const cnt: Map<string, number> = new Map(); const ans: string[] = []; for (let i = 0; i <= n - 10; ++i) { const t = s.slice(i, i + 10); cnt.set(t, (cnt.get(t) ?? 0) + 1); if (cnt.get(t) === 2) { ans.push(t); } } return ans; }
Existence of a Substring in a String and Its Reverse
Given a string s , find any substring of length 2 which is also present in the reverse of s . Return true if such a substring exists, and false otherwise.   Example 1: Input: s = "leetcode" Output: true Explanation: Substring "ee" is of length 2 which is also present in reverse(s) == "edocteel" . Example 2: Input: s = "abcba" Output: true Explanation: All of the substrings of length 2 "ab" , "bc" , "cb" , "ba" are also present in reverse(s) == "abcba" . Example 3: Input: s = "abcd" Output: false Explanation: There is no substring of length 2 in s , which is also present in the reverse of s .   Constraints: 1 <= s.length <= 100 s consists only of lowercase English letters.
null
null
class Solution { public: bool isSubstringPresent(string s) { bool st[26][26]{}; int n = s.size(); for (int i = 0; i < n - 1; ++i) { st[s[i + 1] - 'a'][s[i] - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s[i] - 'a'][s[i + 1] - 'a']) { return true; } } return false; } };
null
null
func isSubstringPresent(s string) bool { st := [26][26]bool{} for i := 0; i < len(s)-1; i++ { st[s[i+1]-'a'][s[i]-'a'] = true } for i := 0; i < len(s)-1; i++ { if st[s[i]-'a'][s[i+1]-'a'] { return true } } return false }
class Solution { public boolean isSubstringPresent(String s) { boolean[][] st = new boolean[26][26]; int n = s.length(); for (int i = 0; i < n - 1; ++i) { st[s.charAt(i + 1) - 'a'][s.charAt(i) - 'a'] = true; } for (int i = 0; i < n - 1; ++i) { if (st[s.charAt(i) - 'a'][s.charAt(i + 1) - 'a']) { return true; } } return false; } }
null
null
null
null
null
null
class Solution: def isSubstringPresent(self, s: str) -> bool: st = {(a, b) for a, b in pairwise(s[::-1])} return any((a, b) in st for a, b in pairwise(s))
null
null
null
null
null
function isSubstringPresent(s: string): boolean { const st: boolean[][] = Array.from({ length: 26 }, () => Array(26).fill(false)); for (let i = 0; i < s.length - 1; ++i) { st[s.charCodeAt(i + 1) - 97][s.charCodeAt(i) - 97] = true; } for (let i = 0; i < s.length - 1; ++i) { if (st[s.charCodeAt(i) - 97][s.charCodeAt(i + 1) - 97]) { return true; } } return false; }
Maximum Profit From Trading Stocks 🔒
You are given two 0-indexed integer arrays of the same length present and future where present[i] is the current price of the i th stock and future[i] is the price of the i th stock a year in the future. You may buy each stock at most once . You are also given an integer budget representing the amount of money you currently have. Return the maximum amount of profit you can make.   Example 1: Input: present = [5,4,6,2,3], future = [8,5,4,3,5], budget = 10 Output: 6 Explanation: One possible way to maximize your profit is to: Buy the 0 th , 3 rd , and 4 th stocks for a total of 5 + 2 + 3 = 10. Next year, sell all three stocks for a total of 8 + 3 + 5 = 16. The profit you made is 16 - 10 = 6. It can be shown that the maximum profit you can make is 6. Example 2: Input: present = [2,2,5], future = [3,4,10], budget = 6 Output: 5 Explanation: The only possible way to maximize your profit is to: Buy the 2 nd stock, and make a profit of 10 - 5 = 5. It can be shown that the maximum profit you can make is 5. Example 3: Input: present = [3,3,12], future = [0,3,15], budget = 10 Output: 0 Explanation: One possible way to maximize your profit is to: Buy the 1 st stock, and make a profit of 3 - 3 = 0. It can be shown that the maximum profit you can make is 0.   Constraints: n == present.length == future.length 1 <= n <= 1000 0 <= present[i], future[i] <= 100 0 <= budget <= 1000
null
null
class Solution { public: int maximumProfit(vector<int>& present, vector<int>& future, int budget) { int n = present.size(); int f[budget + 1]; memset(f, 0, sizeof f); for (int i = 0; i < n; ++i) { int a = present[i], b = future[i]; for (int j = budget; j >= a; --j) { f[j] = max(f[j], f[j - a] + b - a); } } return f[budget]; } };
null
null
func maximumProfit(present []int, future []int, budget int) int { f := make([]int, budget+1) for i, a := range present { for j := budget; j >= a; j-- { f[j] = max(f[j], f[j-a]+future[i]-a) } } return f[budget] }
class Solution { public int maximumProfit(int[] present, int[] future, int budget) { int n = present.length; int[] f = new int[budget + 1]; for (int i = 0; i < n; ++i) { int a = present[i], b = future[i]; for (int j = budget; j >= a; --j) { f[j] = Math.max(f[j], f[j - a] + b - a); } } return f[budget]; } }
null
null
null
null
null
null
class Solution: def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int: f = [0] * (budget + 1) for a, b in zip(present, future): for j in range(budget, a - 1, -1): f[j] = max(f[j], f[j - a] + b - a) return f[-1]
null
null
null
null
null
function maximumProfit(present: number[], future: number[], budget: number): number { const f = new Array(budget + 1).fill(0); for (let i = 0; i < present.length; ++i) { const [a, b] = [present[i], future[i]]; for (let j = budget; j >= a; --j) { f[j] = Math.max(f[j], f[j - a] + b - a); } } return f[budget]; }
Number of Ways to Arrive at Destination
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [u i , v i , time i ] means that there is a road between intersections u i and v i that takes time i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time . Return the number of ways you can arrive at your destination in the shortest amount of time . Since the answer may be large, return it modulo 10 9 + 7 .   Example 1: Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] Output: 4 Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 Example 2: Input: n = 2, roads = [[1,0,10]] Output: 1 Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.   Constraints: 1 <= n <= 200 n - 1 <= roads.length <= n * (n - 1) / 2 roads[i].length == 3 0 <= u i , v i <= n - 1 1 <= time i <= 10 9 u i != v i There is at most one road connecting any two intersections. You can reach any intersection from any other intersection.
null
null
class Solution { public: int countPaths(int n, vector<vector<int>>& roads) { const long long inf = LLONG_MAX / 2; const int mod = 1e9 + 7; vector<vector<long long>> g(n, vector<long long>(n, inf)); for (auto& e : g) { fill(e.begin(), e.end(), inf); } for (auto& r : roads) { int u = r[0], v = r[1], t = r[2]; g[u][v] = t; g[v][u] = t; } g[0][0] = 0; vector<long long> dist(n, inf); fill(dist.begin(), dist.end(), inf); dist[0] = 0; vector<long long> f(n); f[0] = 1; vector<bool> vis(n); for (int i = 0; i < n; ++i) { int t = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[j] < dist[t])) { t = j; } } vis[t] = true; for (int j = 0; j < n; ++j) { if (j == t) { continue; } long long ne = dist[t] + g[t][j]; if (dist[j] > ne) { dist[j] = ne; f[j] = f[t]; } else if (dist[j] == ne) { f[j] = (f[j] + f[t]) % mod; } } } return (int) f[n - 1]; } };
null
null
func countPaths(n int, roads [][]int) int { const inf = math.MaxInt64 / 2 const mod = int(1e9 + 7) g := make([][]int, n) dist := make([]int, n) for i := range g { g[i] = make([]int, n) for j := range g[i] { g[i][j] = inf dist[i] = inf } } for _, r := range roads { u, v, t := r[0], r[1], r[2] g[u][v] = t g[v][u] = t } f := make([]int, n) vis := make([]bool, n) f[0] = 1 g[0][0] = 0 dist[0] = 0 for i := 0; i < n; i++ { t := -1 for j := 0; j < n; j++ { if !vis[j] && (t == -1 || dist[j] < dist[t]) { t = j } } vis[t] = true for j := 0; j < n; j++ { if j == t { continue } ne := dist[t] + g[t][j] if dist[j] > ne { dist[j] = ne f[j] = f[t] } else if dist[j] == ne { f[j] = (f[j] + f[t]) % mod } } } return f[n-1] }
class Solution { public int countPaths(int n, int[][] roads) { final long inf = Long.MAX_VALUE / 2; final int mod = (int) 1e9 + 7; long[][] g = new long[n][n]; for (var e : g) { Arrays.fill(e, inf); } for (var r : roads) { int u = r[0], v = r[1], t = r[2]; g[u][v] = t; g[v][u] = t; } g[0][0] = 0; long[] dist = new long[n]; Arrays.fill(dist, inf); dist[0] = 0; long[] f = new long[n]; f[0] = 1; boolean[] vis = new boolean[n]; for (int i = 0; i < n; ++i) { int t = -1; for (int j = 0; j < n; ++j) { if (!vis[j] && (t == -1 || dist[j] < dist[t])) { t = j; } } vis[t] = true; for (int j = 0; j < n; ++j) { if (j == t) { continue; } long ne = dist[t] + g[t][j]; if (dist[j] > ne) { dist[j] = ne; f[j] = f[t]; } else if (dist[j] == ne) { f[j] = (f[j] + f[t]) % mod; } } } return (int) f[n - 1]; } }
null
null
null
null
null
null
class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: g = [[inf] * n for _ in range(n)] for u, v, t in roads: g[u][v] = g[v][u] = t g[0][0] = 0 dist = [inf] * n dist[0] = 0 f = [0] * n f[0] = 1 vis = [False] * n for _ in range(n): t = -1 for j in range(n): if not vis[j] and (t == -1 or dist[j] < dist[t]): t = j vis[t] = True for j in range(n): if j == t: continue ne = dist[t] + g[t][j] if dist[j] > ne: dist[j] = ne f[j] = f[t] elif dist[j] == ne: f[j] += f[t] mod = 10**9 + 7 return f[-1] % mod
null
null
null
null
null
function countPaths(n: number, roads: number[][]): number { const mod: number = 1e9 + 7; const g: number[][] = Array.from({ length: n }, () => Array(n).fill(Infinity)); for (const [u, v, t] of roads) { g[u][v] = t; g[v][u] = t; } g[0][0] = 0; const dist: number[] = Array(n).fill(Infinity); dist[0] = 0; const f: number[] = Array(n).fill(0); f[0] = 1; const vis: boolean[] = Array(n).fill(false); for (let i = 0; i < n; ++i) { let t: number = -1; for (let j = 0; j < n; ++j) { if (!vis[j] && (t === -1 || dist[j] < dist[t])) { t = j; } } vis[t] = true; for (let j = 0; j < n; ++j) { if (j === t) { continue; } const ne: number = dist[t] + g[t][j]; if (dist[j] > ne) { dist[j] = ne; f[j] = f[t]; } else if (dist[j] === ne) { f[j] = (f[j] + f[t]) % mod; } } } return f[n - 1]; }
Number of Subarrays With LCM Equal to K
Given an integer array nums and an integer k , return the number of subarrays of nums where the least common multiple of the subarray's elements is k . A subarray is a contiguous non-empty sequence of elements within an array. The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.   Example 1: Input: nums = [3,6,2,7,1], k = 6 Output: 4 Explanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are: - [ 3 , 6 ,2,7,1] - [ 3 , 6 , 2 ,7,1] - [3, 6 ,2,7,1] - [3, 6 , 2 ,7,1] Example 2: Input: nums = [3], k = 2 Output: 0 Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i], k <= 1000
null
null
class Solution { public: int subarrayLCM(vector<int>& nums, int k) { int n = nums.size(); int ans = 0; for (int i = 0; i < n; ++i) { int a = nums[i]; for (int j = i; j < n; ++j) { int b = nums[j]; int x = lcm(a, b); ans += x == k; a = x; } } return ans; } };
null
null
func subarrayLCM(nums []int, k int) (ans int) { for i, a := range nums { for _, b := range nums[i:] { x := lcm(a, b) if x == k { ans++ } a = x } } return } func gcd(a, b int) int { if b == 0 { return a } return gcd(b, a%b) } func lcm(a, b int) int { return a * b / gcd(a, b) }
class Solution { public int subarrayLCM(int[] nums, int k) { int n = nums.length; int ans = 0; for (int i = 0; i < n; ++i) { int a = nums[i]; for (int j = i; j < n; ++j) { int b = nums[j]; int x = lcm(a, b); if (x == k) { ++ans; } a = x; } } return ans; } private int lcm(int a, int b) { return a * b / gcd(a, b); } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } }
null
null
null
null
null
null
class Solution: def subarrayLCM(self, nums: List[int], k: int) -> int: n = len(nums) ans = 0 for i in range(n): a = nums[i] for b in nums[i:]: x = lcm(a, b) ans += x == k a = x return ans
null
null
null
null
null
null
Sort the Olympic Table 🔒
Table: Olympic +---------------+---------+ | Column Name | Type | +---------------+---------+ | country | varchar | | gold_medals | int | | silver_medals | int | | bronze_medals | int | +---------------+---------+ In SQL, country is the primary key for this table. Each row in this table shows a country name and the number of gold, silver, and bronze medals it won in the Olympic games.   The Olympic table is sorted according to the following rules: The country with more gold medals comes first. If there is a tie in the gold medals, the country with more silver medals comes first. If there is a tie in the silver medals, the country with more bronze medals comes first. If there is a tie in the bronze medals, the countries with the tie are sorted in ascending order lexicographically. Write a solution to sort the Olympic table. The result format is shown in the following example.   Example 1: Input: Olympic table: +-------------+-------------+---------------+---------------+ | country | gold_medals | silver_medals | bronze_medals | +-------------+-------------+---------------+---------------+ | China | 10 | 10 | 20 | | South Sudan | 0 | 0 | 1 | | USA | 10 | 10 | 20 | | Israel | 2 | 2 | 3 | | Egypt | 2 | 2 | 2 | +-------------+-------------+---------------+---------------+ Output: +-------------+-------------+---------------+---------------+ | country | gold_medals | silver_medals | bronze_medals | +-------------+-------------+---------------+---------------+ | China | 10 | 10 | 20 | | USA | 10 | 10 | 20 | | Israel | 2 | 2 | 3 | | Egypt | 2 | 2 | 2 | | South Sudan | 0 | 0 | 1 | +-------------+-------------+---------------+---------------+ Explanation: The tie between China and USA is broken by their lexicographical names. Since "China" is lexicographically smaller than "USA", it comes first. Israel comes before Egypt because it has more bronze medals.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT * FROM Olympic ORDER BY 2 DESC, 3 DESC, 4 DESC, 1;
null
null
null
null
null
null
null
null
null
null
Find Minimum Time to Finish All Jobs II 🔒
You are given two 0-indexed integer arrays jobs and workers of equal length, where jobs[i] is the amount of time needed to complete the i th job, and workers[j] is the amount of time the j th worker can work each day. Each job should be assigned to exactly one worker, such that each worker completes exactly one job. Return the minimum number of days needed to complete all the jobs after assignment.   Example 1: Input: jobs = [5,2,4], workers = [1,7,5] Output: 2 Explanation: - Assign the 2 nd worker to the 0 th job. It takes them 1 day to finish the job. - Assign the 0 th worker to the 1 st job. It takes them 2 days to finish the job. - Assign the 1 st worker to the 2 nd job. It takes them 1 day to finish the job. It takes 2 days for all the jobs to be completed, so return 2. It can be proven that 2 days is the minimum number of days needed. Example 2: Input: jobs = [3,18,15,9], workers = [6,5,1,3] Output: 3 Explanation: - Assign the 2 nd worker to the 0 th job. It takes them 3 days to finish the job. - Assign the 0 th worker to the 1 st job. It takes them 3 days to finish the job. - Assign the 1 st worker to the 2 nd job. It takes them 3 days to finish the job. - Assign the 3 rd worker to the 3 rd job. It takes them 3 days to finish the job. It takes 3 days for all the jobs to be completed, so return 3. It can be proven that 3 days is the minimum number of days needed.   Constraints: n == jobs.length == workers.length 1 <= n <= 10 5 1 <= jobs[i], workers[i] <= 10 5
null
null
class Solution { public: int minimumTime(vector<int>& jobs, vector<int>& workers) { ranges::sort(jobs); ranges::sort(workers); int ans = 0; int n = jobs.size(); for (int i = 0; i < n; ++i) { ans = max(ans, (jobs[i] + workers[i] - 1) / workers[i]); } return ans; } };
null
null
func minimumTime(jobs []int, workers []int) (ans int) { sort.Ints(jobs) sort.Ints(workers) for i, a := range jobs { b := workers[i] ans = max(ans, (a+b-1)/b) } return }
class Solution { public int minimumTime(int[] jobs, int[] workers) { Arrays.sort(jobs); Arrays.sort(workers); int ans = 0; for (int i = 0; i < jobs.length; ++i) { ans = Math.max(ans, (jobs[i] + workers[i] - 1) / workers[i]); } return ans; } }
/** * @param {number[]} jobs * @param {number[]} workers * @return {number} */ var minimumTime = function (jobs, workers) { jobs.sort((a, b) => a - b); workers.sort((a, b) => a - b); let ans = 0; const n = jobs.length; for (let i = 0; i < n; ++i) { ans = Math.max(ans, Math.ceil(jobs[i] / workers[i])); } return ans; };
null
null
null
null
null
class Solution: def minimumTime(self, jobs: List[int], workers: List[int]) -> int: jobs.sort() workers.sort() return max((a + b - 1) // b for a, b in zip(jobs, workers))
null
impl Solution { pub fn minimum_time(mut jobs: Vec<i32>, mut workers: Vec<i32>) -> i32 { jobs.sort(); workers.sort(); jobs.iter() .zip(workers.iter()) .map(|(a, b)| (a + b - 1) / b) .max() .unwrap() } }
null
null
null
function minimumTime(jobs: number[], workers: number[]): number { jobs.sort((a, b) => a - b); workers.sort((a, b) => a - b); let ans = 0; const n = jobs.length; for (let i = 0; i < n; ++i) { ans = Math.max(ans, Math.ceil(jobs[i] / workers[i])); } return ans; }
Frog Position After T Seconds
Given an undirected tree consisting of n vertices numbered from 1 to n . A frog starts jumping from vertex 1 . In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array edges , where edges[i] = [a i , b i ] means that exists an edge connecting the vertices a i and b i . Return the probability that after t seconds the frog is on the vertex target . Answers within 10 -5 of the actual answer will be accepted.   Example 1: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4 Output: 0.16666666666666666 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2 . Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. Example 2: Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7 Output: 0.3333333333333333 Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1 .   Constraints: 1 <= n <= 100 edges.length == n - 1 edges[i].length == 2 1 <= a i , b i <= n 1 <= t <= 50 1 <= target <= n
null
public class Solution { public double FrogPosition(int n, int[][] edges, int t, int target) { List<int>[] g = new List<int>[n + 1]; for (int i = 0; i < n + 1; i++) { g[i] = new List<int>(); } foreach (int[] e in edges) { int u = e[0], v = e[1]; g[u].Add(v); g[v].Add(u); } Queue<Tuple<int, double>> q = new Queue<Tuple<int, double>>(); q.Enqueue(new Tuple<int, double>(1, 1.0)); bool[] vis = new bool[n + 1]; vis[1] = true; for (; q.Count > 0 && t >= 0; --t) { for (int k = q.Count; k > 0; --k) { (var u, var p) = q.Dequeue(); int cnt = g[u].Count - (u == 1 ? 0 : 1); if (u == target) { return cnt * t == 0 ? p : 0; } foreach (int v in g[u]) { if (!vis[v]) { vis[v] = true; q.Enqueue(new Tuple<int, double>(v, p / cnt)); } } } } return 0; } }
class Solution { public: double frogPosition(int n, vector<vector<int>>& edges, int t, int target) { vector<vector<int>> g(n + 1); for (auto& e : edges) { int u = e[0], v = e[1]; g[u].push_back(v); g[v].push_back(u); } queue<pair<int, double>> q{{{1, 1.0}}}; bool vis[n + 1]; memset(vis, false, sizeof(vis)); vis[1] = true; for (; q.size() && t >= 0; --t) { for (int k = q.size(); k; --k) { auto [u, p] = q.front(); q.pop(); int cnt = g[u].size() - (u != 1); if (u == target) { return cnt * t == 0 ? p : 0; } for (int v : g[u]) { if (!vis[v]) { vis[v] = true; q.push({v, p / cnt}); } } } } return 0; } };
null
null
func frogPosition(n int, edges [][]int, t int, target int) float64 { g := make([][]int, n+1) for _, e := range edges { u, v := e[0], e[1] g[u] = append(g[u], v) g[v] = append(g[v], u) } type pair struct { u int p float64 } q := []pair{{1, 1}} vis := make([]bool, n+1) vis[1] = true for ; len(q) > 0 && t >= 0; t-- { for k := len(q); k > 0; k-- { u, p := q[0].u, q[0].p q = q[1:] cnt := len(g[u]) if u != 1 { cnt-- } if u == target { if cnt*t == 0 { return p } return 0 } for _, v := range g[u] { if !vis[v] { vis[v] = true q = append(q, pair{v, p / float64(cnt)}) } } } } return 0 }
class Solution { public double frogPosition(int n, int[][] edges, int t, int target) { List<Integer>[] g = new List[n + 1]; Arrays.setAll(g, k -> new ArrayList<>()); for (var e : edges) { int u = e[0], v = e[1]; g[u].add(v); g[v].add(u); } Deque<Pair<Integer, Double>> q = new ArrayDeque<>(); q.offer(new Pair<>(1, 1.0)); boolean[] vis = new boolean[n + 1]; vis[1] = true; for (; !q.isEmpty() && t >= 0; --t) { for (int k = q.size(); k > 0; --k) { var x = q.poll(); int u = x.getKey(); double p = x.getValue(); int cnt = g[u].size() - (u == 1 ? 0 : 1); if (u == target) { return cnt * t == 0 ? p : 0; } for (int v : g[u]) { if (!vis[v]) { vis[v] = true; q.offer(new Pair<>(v, p / cnt)); } } } } return 0; } }
null
null
null
null
null
null
class Solution: def frogPosition( self, n: int, edges: List[List[int]], t: int, target: int ) -> float: g = defaultdict(list) for u, v in edges: g[u].append(v) g[v].append(u) q = deque([(1, 1.0)]) vis = [False] * (n + 1) vis[1] = True while q and t >= 0: for _ in range(len(q)): u, p = q.popleft() cnt = len(g[u]) - int(u != 1) if u == target: return p if cnt * t == 0 else 0 for v in g[u]: if not vis[v]: vis[v] = True q.append((v, p / cnt)) t -= 1 return 0
null
null
null
null
null
function frogPosition(n: number, edges: number[][], t: number, target: number): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); for (const [u, v] of edges) { g[u].push(v); g[v].push(u); } const q: number[][] = [[1, 1]]; const vis: boolean[] = Array.from({ length: n + 1 }, () => false); vis[1] = true; for (; q.length > 0 && t >= 0; --t) { for (let k = q.length; k > 0; --k) { const [u, p] = q.shift()!; const cnt = g[u].length - (u === 1 ? 0 : 1); if (u === target) { return cnt * t === 0 ? p : 0; } for (const v of g[u]) { if (!vis[v]) { vis[v] = true; q.push([v, p / cnt]); } } } } return 0; }
Transformed Array
You are given an integer array nums that represents a circular array. Your task is to create a new array result of the same size, following these rules: For each index i (where 0 <= i < nums.length ), perform the following independent actions: If nums[i] > 0 : Start at index i and move nums[i] steps to the right in the circular array. Set result[i] to the value of the index where you land. If nums[i] < 0 : Start at index i and move abs(nums[i]) steps to the left in the circular array. Set result[i] to the value of the index where you land. If nums[i] == 0 : Set result[i] to nums[i] . Return the new array result . Note: Since nums is circular, moving past the last element wraps around to the beginning, and moving before the first element wraps back to the end.   Example 1: Input: nums = [3,-2,1,1] Output: [1,1,1,3] Explanation: For nums[0] that is equal to 3, If we move 3 steps to right, we reach nums[3] . So result[0] should be 1. For nums[1] that is equal to -2, If we move 2 steps to left, we reach nums[3] . So result[1] should be 1. For nums[2] that is equal to 1, If we move 1 step to right, we reach nums[3] . So result[2] should be 1. For nums[3] that is equal to 1, If we move 1 step to right, we reach nums[0] . So result[3] should be 3. Example 2: Input: nums = [-1,4,-1] Output: [-1,-1,4] Explanation: For nums[0] that is equal to -1, If we move 1 step to left, we reach nums[2] . So result[0] should be -1. For nums[1] that is equal to 4, If we move 4 steps to right, we reach nums[2] . So result[1] should be -1. For nums[2] that is equal to -1, If we move 1 step to left, we reach nums[1] . So result[2] should be 4.   Constraints: 1 <= nums.length <= 100 -100 <= nums[i] <= 100
null
null
class Solution { public: vector<int> constructTransformedArray(vector<int>& nums) { int n = nums.size(); vector<int> ans(n); for (int i = 0; i < n; ++i) { ans[i] = nums[i] ? nums[(i + nums[i] % n + n) % n] : 0; } return ans; } };
null
null
func constructTransformedArray(nums []int) []int { n := len(nums) ans := make([]int, n) for i, x := range nums { if x != 0 { ans[i] = nums[(i+x%n+n)%n] } } return ans }
class Solution { public int[] constructTransformedArray(int[] nums) { int n = nums.length; int[] ans = new int[n]; for (int i = 0; i < n; ++i) { ans[i] = nums[i] != 0 ? nums[(i + nums[i] % n + n) % n] : 0; } return ans; } }
null
null
null
null
null
null
class Solution: def constructTransformedArray(self, nums: List[int]) -> List[int]: ans = [] n = len(nums) for i, x in enumerate(nums): ans.append(nums[(i + x + n) % n] if x else 0) return ans
null
null
null
null
null
function constructTransformedArray(nums: number[]): number[] { const n = nums.length; const ans: number[] = []; for (let i = 0; i < n; ++i) { ans.push(nums[i] ? nums[(i + (nums[i] % n) + n) % n] : 0); } return ans; }
Count Substrings That Differ by One Character
Given two strings s and t , find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t . In other words, find the number of substrings in s that differ from some substring in t by exactly one character. For example, the underlined substrings in " compute r" and " computa tion" only differ by the 'e' / 'a' , so this is a valid way. Return the number of substrings that satisfy the condition above. A substring is a contiguous sequence of characters within a string.   Example 1: Input: s = "aba", t = "baba" Output: 6 Explanation: The following are the pairs of substrings from s and t that differ by exactly 1 character: (" a ba", " b aba") (" a ba", "ba b a") ("ab a ", " b aba") ("ab a ", "ba b a") ("a b a", "b a ba") ("a b a", "bab a ") The underlined portions are the substrings that are chosen from s and t. ​​ Example 2: Input: s = "ab", t = "bb" Output: 3 Explanation: The following are the pairs of substrings from s and t that differ by 1 character: (" a b", " b b") (" a b", "b b ") (" ab ", " bb ") ​​​​The underlined portions are the substrings that are chosen from s and t.   Constraints: 1 <= s.length, t.length <= 100 s and t consist of lowercase English letters only.
null
null
class Solution { public: int countSubstrings(string s, string t) { int ans = 0; int m = s.length(), n = t.length(); int f[m + 1][n + 1]; int g[m + 1][n + 1]; memset(f, 0, sizeof(f)); memset(g, 0, sizeof(g)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (s[i] == t[j]) { f[i + 1][j + 1] = f[i][j] + 1; } } } for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (s[i] == t[j]) { g[i][j] = g[i + 1][j + 1] + 1; } else { ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); } } } return ans; } };
null
null
func countSubstrings(s string, t string) (ans int) { m, n := len(s), len(t) f := make([][]int, m+1) g := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) g[i] = make([]int, n+1) } for i, a := range s { for j, b := range t { if a == b { f[i+1][j+1] = f[i][j] + 1 } } } for i := m - 1; i >= 0; i-- { for j := n - 1; j >= 0; j-- { if s[i] == t[j] { g[i][j] = g[i+1][j+1] + 1 } else { ans += (f[i][j] + 1) * (g[i+1][j+1] + 1) } } } return }
class Solution { public int countSubstrings(String s, String t) { int ans = 0; int m = s.length(), n = t.length(); int[][] f = new int[m + 1][n + 1]; int[][] g = new int[m + 1][n + 1]; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (s.charAt(i) == t.charAt(j)) { f[i + 1][j + 1] = f[i][j] + 1; } } } for (int i = m - 1; i >= 0; --i) { for (int j = n - 1; j >= 0; --j) { if (s.charAt(i) == t.charAt(j)) { g[i][j] = g[i + 1][j + 1] + 1; } else { ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1); } } } return ans; } }
null
null
null
null
null
null
class Solution: def countSubstrings(self, s: str, t: str) -> int: ans = 0 m, n = len(s), len(t) f = [[0] * (n + 1) for _ in range(m + 1)] g = [[0] * (n + 1) for _ in range(m + 1)] for i, a in enumerate(s, 1): for j, b in enumerate(t, 1): if a == b: f[i][j] = f[i - 1][j - 1] + 1 for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): if s[i] == t[j]: g[i][j] = g[i + 1][j + 1] + 1 else: ans += (f[i][j] + 1) * (g[i + 1][j + 1] + 1) return ans
null
null
null
null
null
null
Maximum Enemy Forts That Can Be Captured
You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1 , 0 , or 1 where: -1 represents there is no fort at the i th position. 0 indicates there is an enemy fort at the i th position. 1 indicates the fort at the i th the position is under your command. Now you have decided to move your army from one of your forts at position i to an empty position j such that: 0 <= i, j <= n - 1 The army travels over enemy forts only . Formally, for all k where min(i,j) < k < max(i,j) , forts[k] == 0. While moving the army, all the enemy forts that come in the way are captured . Return the maximum number of enemy forts that can be captured . In case it is impossible to move your army, or you do not have any fort under your command, return 0 .   Example 1: Input: forts = [1,0,0,-1,0,0,0,0,1] Output: 4 Explanation: - Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2. - Moving the army from position 8 to position 3 captures 4 enemy forts. Since 4 is the maximum number of enemy forts that can be captured, we return 4. Example 2: Input: forts = [0,0,1,-1] Output: 0 Explanation: Since no enemy fort can be captured, 0 is returned.   Constraints: 1 <= forts.length <= 1000 -1 <= forts[i] <= 1
null
null
class Solution { public: int captureForts(vector<int>& forts) { int n = forts.size(); int ans = 0, i = 0; while (i < n) { int j = i + 1; if (forts[i] != 0) { while (j < n && forts[j] == 0) { ++j; } if (j < n && forts[i] + forts[j] == 0) { ans = max(ans, j - i - 1); } } i = j; } return ans; } };
null
null
func captureForts(forts []int) (ans int) { n := len(forts) i := 0 for i < n { j := i + 1 if forts[i] != 0 { for j < n && forts[j] == 0 { j++ } if j < n && forts[i]+forts[j] == 0 { ans = max(ans, j-i-1) } } i = j } return }
class Solution { public int captureForts(int[] forts) { int n = forts.length; int ans = 0, i = 0; while (i < n) { int j = i + 1; if (forts[i] != 0) { while (j < n && forts[j] == 0) { ++j; } if (j < n && forts[i] + forts[j] == 0) { ans = Math.max(ans, j - i - 1); } } i = j; } return ans; } }
null
null
null
null
null
null
class Solution: def captureForts(self, forts: List[int]) -> int: n = len(forts) i = ans = 0 while i < n: j = i + 1 if forts[i]: while j < n and forts[j] == 0: j += 1 if j < n and forts[i] + forts[j] == 0: ans = max(ans, j - i - 1) i = j return ans
null
impl Solution { pub fn capture_forts(forts: Vec<i32>) -> i32 { let n = forts.len(); let mut ans = 0; let mut i = 0; while i < n { let mut j = i + 1; if forts[i] != 0 { while j < n && forts[j] == 0 { j += 1; } if j < n && forts[i] + forts[j] == 0 { ans = ans.max(j - i - 1); } } i = j; } ans as i32 } }
null
null
null
function captureForts(forts: number[]): number { const n = forts.length; let ans = 0; let i = 0; while (i < n) { let j = i + 1; if (forts[i] !== 0) { while (j < n && forts[j] === 0) { j++; } if (j < n && forts[i] + forts[j] === 0) { ans = Math.max(ans, j - i - 1); } } i = j; } return ans; }
Last Moment Before All Ants Fall Out of a Plank
We have a wooden plank of the length n units . Some ants are walking on the plank, each ant moves with a speed of 1 unit per second . Some of the ants move to the left , the other move to the right . When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t , it falls out of the plank immediately. Given an integer n and two integer arrays left and right , the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank .   Example 1: Input: n = 4, left = [4,3], right = [0,1] Output: 4 Explanation: In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). Example 2: Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7] Output: 7 Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall. Example 3: Input: n = 7, left = [0,1,2,3,4,5,6,7], right = [] Output: 7 Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.   Constraints: 1 <= n <= 10 4 0 <= left.length <= n + 1 0 <= left[i] <= n 0 <= right.length <= n + 1 0 <= right[i] <= n 1 <= left.length + right.length <= n + 1 All values of left and right are unique, and each value can appear only in one of the two arrays.
null
null
class Solution { public: int getLastMoment(int n, vector<int>& left, vector<int>& right) { int ans = 0; for (int& x : left) { ans = max(ans, x); } for (int& x : right) { ans = max(ans, n - x); } return ans; } };
null
null
func getLastMoment(n int, left []int, right []int) (ans int) { for _, x := range left { ans = max(ans, x) } for _, x := range right { ans = max(ans, n-x) } return }
class Solution { public int getLastMoment(int n, int[] left, int[] right) { int ans = 0; for (int x : left) { ans = Math.max(ans, x); } for (int x : right) { ans = Math.max(ans, n - x); } return ans; } }
null
null
null
null
null
null
class Solution: def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int: ans = 0 for x in left: ans = max(ans, x) for x in right: ans = max(ans, n - x) return ans
null
null
null
null
null
function getLastMoment(n: number, left: number[], right: number[]): number { let ans = 0; for (const x of left) { ans = Math.max(ans, x); } for (const x of right) { ans = Math.max(ans, n - x); } return ans; }
Minimum Distance Between BST Nodes
Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree .   Example 1: Input: root = [4,2,6,1,3] Output: 1 Example 2: Input: root = [1,0,48,null,null,12,49] Output: 1   Constraints: The number of nodes in the tree is in the range [2, 100] . 0 <= Node.val <= 10 5   Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/
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 Solution { public: int minDiffInBST(TreeNode* root) { const int inf = 1 << 30; int ans = inf, pre = -inf; auto dfs = [&](this auto&& dfs, TreeNode* root) -> void { if (!root) { return; } dfs(root->left); ans = min(ans, root->val - pre); pre = root->val; dfs(root->right); }; dfs(root); return ans; } };
null
null
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func minDiffInBST(root *TreeNode) int { const inf int = 1 << 30 ans, pre := inf, -inf var dfs func(*TreeNode) dfs = func(root *TreeNode) { if root == nil { return } dfs(root.Left) ans = min(ans, root.Val-pre) pre = root.Val dfs(root.Right) } dfs(root) return ans }
/** * 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 Solution { private final int inf = 1 << 30; private int ans = inf; private int pre = -inf; public int minDiffInBST(TreeNode root) { dfs(root); return ans; } private void dfs(TreeNode root) { if (root == null) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); } }
/** * 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 * @return {number} */ var minDiffInBST = function (root) { let [ans, pre] = [Infinity, -Infinity]; const dfs = root => { if (!root) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); }; dfs(root); return ans; };
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 Solution: def minDiffInBST(self, root: Optional[TreeNode]) -> int: def dfs(root: Optional[TreeNode]): if root is None: return dfs(root.left) nonlocal pre, ans ans = min(ans, root.val - pre) pre = root.val dfs(root.right) pre = -inf ans = inf dfs(root) return ans
null
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn min_diff_in_bst(root: Option<Rc<RefCell<TreeNode>>>) -> i32 { const inf: i32 = 1 << 30; let mut ans = inf; let mut pre = -inf; fn dfs(node: Option<Rc<RefCell<TreeNode>>>, ans: &mut i32, pre: &mut i32) { if let Some(n) = node { let n = n.borrow(); dfs(n.left.clone(), ans, pre); *ans = (*ans).min(n.val - *pre); *pre = n.val; dfs(n.right.clone(), ans, pre); } } dfs(root, &mut ans, &mut pre); ans } }
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) * } * } */ function minDiffInBST(root: TreeNode | null): number { let [ans, pre] = [Infinity, -Infinity]; const dfs = (root: TreeNode | null) => { if (!root) { return; } dfs(root.left); ans = Math.min(ans, root.val - pre); pre = root.val; dfs(root.right); }; dfs(root); return ans; }
Minimum Time to Reach Destination in Directed Graph
You are given an integer n and a directed graph with n nodes labeled from 0 to n - 1 . This is represented by a 2D array edges , where edges[i] = [u i , v i , start i , end i ] indicates an edge from node u i to v i that can only be used at any integer time t such that start i <= t <= end i . You start at node 0 at time 0. In one unit of time, you can either: Wait at your current node without moving, or Travel along an outgoing edge from your current node if the current time t satisfies start i <= t <= end i . Return the minimum time required to reach node n - 1 . If it is impossible, return -1 .   Example 1: Input: n = 3, edges = [[0,1,0,1],[1,2,2,5]] Output: 3 Explanation: The optimal path is: At time t = 0 , take the edge (0 → 1) which is available from 0 to 1. You arrive at node 1 at time t = 1 , then wait until t = 2 . At time t = 2 , take the edge (1 → 2) which is available from 2 to 5. You arrive at node 2 at time 3. Hence, the minimum time to reach node 2 is 3. Example 2: Input: n = 4, edges = [[0,1,0,3],[1,3,7,8],[0,2,1,5],[2,3,4,7]] Output: 5 Explanation: The optimal path is: Wait at node 0 until time t = 1 , then take the edge (0 → 2) which is available from 1 to 5. You arrive at node 2 at t = 2 . Wait at node 2 until time t = 4 , then take the edge (2 → 3) which is available from 4 to 7. You arrive at node 3 at t = 5 . Hence, the minimum time to reach node 3 is 5. Example 3: Input: n = 3, edges = [[1,0,1,3],[1,2,3,5]] Output: -1 Explanation: Since there is no outgoing edge from node 0, it is impossible to reach node 2. Hence, the output is -1.   Constraints: 1 <= n <= 10 5 0 <= edges.length <= 10 5 edges[i] == [u i , v i , start i , end i ] 0 <= u i , v i <= n - 1 u i != v i 0 <= start i <= end i <= 10 9
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Find the Length of the Longest Common Prefix
You are given two arrays with positive integers arr1 and arr2 . A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345 , while 234 is not . A common prefix of two integers a and b is an integer c , such that c is a prefix of both a and b . For example, 5655359 and 56554 have common prefixes 565 and 5655 while 1223 and 43456 do not have a common prefix. You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2 . Return the length of the longest common prefix among all pairs . If no common prefix exists among them , return 0 .   Example 1: Input: arr1 = [1,10,100], arr2 = [1000] Output: 3 Explanation: There are 3 pairs (arr1[i], arr2[j]): - The longest common prefix of (1, 1000) is 1. - The longest common prefix of (10, 1000) is 10. - The longest common prefix of (100, 1000) is 100. The longest common prefix is 100 with a length of 3. Example 2: Input: arr1 = [1,2,3], arr2 = [4,4,4] Output: 0 Explanation: There exists no common prefix for any pair (arr1[i], arr2[j]), hence we return 0. Note that common prefixes between elements of the same array do not count.   Constraints: 1 <= arr1.length, arr2.length <= 5 * 10 4 1 <= arr1[i], arr2[i] <= 10 8
null
null
class Solution { public: int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) { unordered_set<int> s; for (int x : arr1) { for (; x; x /= 10) { s.insert(x); } } int ans = 0; for (int x : arr2) { for (; x; x /= 10) { if (s.count(x)) { ans = max(ans, (int) log10(x) + 1); break; } } } return ans; } };
null
null
func longestCommonPrefix(arr1 []int, arr2 []int) (ans int) { s := map[int]bool{} for _, x := range arr1 { for ; x > 0; x /= 10 { s[x] = true } } for _, x := range arr2 { for ; x > 0; x /= 10 { if s[x] { ans = max(ans, int(math.Log10(float64(x)))+1) break } } } return }
class Solution { public int longestCommonPrefix(int[] arr1, int[] arr2) { Set<Integer> s = new HashSet<>(); for (int x : arr1) { for (; x > 0; x /= 10) { s.add(x); } } int ans = 0; for (int x : arr2) { for (; x > 0; x /= 10) { if (s.contains(x)) { ans = Math.max(ans, String.valueOf(x).length()); break; } } } return ans; } }
/** * @param {number[]} arr1 * @param {number[]} arr2 * @return {number} */ var longestCommonPrefix = function (arr1, arr2) { const s = new Set(); for (let x of arr1) { for (; x; x = Math.floor(x / 10)) { s.add(x); } } let ans = 0; for (let x of arr2) { for (; x; x = Math.floor(x / 10)) { if (s.has(x)) { ans = Math.max(ans, Math.floor(Math.log10(x)) + 1); } } } return ans; };
null
null
null
null
null
class Solution: def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int: s = set() for x in arr1: while x: s.add(x) x //= 10 ans = 0 for x in arr2: while x: if x in s: ans = max(ans, len(str(x))) break x //= 10 return ans
null
null
null
null
null
function longestCommonPrefix(arr1: number[], arr2: number[]): number { const s: Set<number> = new Set<number>(); for (let x of arr1) { for (; x; x = Math.floor(x / 10)) { s.add(x); } } let ans: number = 0; for (let x of arr2) { for (; x; x = Math.floor(x / 10)) { if (s.has(x)) { ans = Math.max(ans, Math.floor(Math.log10(x)) + 1); } } } return ans; }
Find Champion I
There are n teams numbered from 0 to n - 1 in a tournament. Given a 0-indexed 2D boolean matrix grid of size n * n . For all i, j that 0 <= i, j <= n - 1 and i != j team i is stronger than team j if grid[i][j] == 1 , otherwise, team j is stronger than team i . Team a will be the champion of the tournament if there is no team b that is stronger than team a . Return the team that will be the champion of the tournament.   Example 1: Input: grid = [[0,1],[0,0]] Output: 0 Explanation: There are two teams in this tournament. grid[0][1] == 1 means that team 0 is stronger than team 1. So team 0 will be the champion. Example 2: Input: grid = [[0,0,1],[1,0,1],[0,0,0]] Output: 1 Explanation: There are three teams in this tournament. grid[1][0] == 1 means that team 1 is stronger than team 0. grid[1][2] == 1 means that team 1 is stronger than team 2. So team 1 will be the champion.   Constraints: n == grid.length n == grid[i].length 2 <= n <= 100 grid[i][j] is either 0 or 1 . For all i grid[i][i] is 0. For all i, j that i != j , grid[i][j] != grid[j][i] . The input is generated such that if team a is stronger than team b and team b is stronger than team c , then team a is stronger than team c .
null
null
class Solution { public: int findChampion(vector<vector<int>>& grid) { int n = grid.size(); for (int i = 0;; ++i) { int cnt = 0; for (int j = 0; j < n; ++j) { if (i != j && grid[i][j] == 1) { ++cnt; } } if (cnt == n - 1) { return i; } } } };
null
null
func findChampion(grid [][]int) int { n := len(grid) for i := 0; ; i++ { cnt := 0 for j, x := range grid[i] { if i != j && x == 1 { cnt++ } } if cnt == n-1 { return i } } }
class Solution { public int findChampion(int[][] grid) { int n = grid.length; for (int i = 0;; ++i) { int cnt = 0; for (int j = 0; j < n; ++j) { if (i != j && grid[i][j] == 1) { ++cnt; } } if (cnt == n - 1) { return i; } } } }
null
null
null
null
null
null
class Solution: def findChampion(self, grid: List[List[int]]) -> int: for i, row in enumerate(grid): if all(x == 1 for j, x in enumerate(row) if i != j): return i
null
null
null
null
null
function findChampion(grid: number[][]): number { for (let i = 0, n = grid.length; ; ++i) { let cnt = 0; for (let j = 0; j < n; ++j) { if (i !== j && grid[i][j] === 1) { ++cnt; } } if (cnt === n - 1) { return i; } } }
Running Total for Different Genders 🔒
Table: Scores +---------------+---------+ | Column Name | Type | +---------------+---------+ | player_name | varchar | | gender | varchar | | day | date | | score_points | int | +---------------+---------+ (gender, day) is the primary key (combination of columns with unique values) for this table. A competition is held between the female team and the male team. Each row of this table indicates that a player_name and with gender has scored score_point in someday. Gender is 'F' if the player is in the female team and 'M' if the player is in the male team.   Write a solution to find the total score for each gender on each day. Return the result table ordered by gender and day in ascending order . The result format is in the following example.   Example 1: Input: Scores table: +-------------+--------+------------+--------------+ | player_name | gender | day | score_points | +-------------+--------+------------+--------------+ | Aron | F | 2020-01-01 | 17 | | Alice | F | 2020-01-07 | 23 | | Bajrang | M | 2020-01-07 | 7 | | Khali | M | 2019-12-25 | 11 | | Slaman | M | 2019-12-30 | 13 | | Joe | M | 2019-12-31 | 3 | | Jose | M | 2019-12-18 | 2 | | Priya | F | 2019-12-31 | 23 | | Priyanka | F | 2019-12-30 | 17 | +-------------+--------+------------+--------------+ Output: +--------+------------+-------+ | gender | day | total | +--------+------------+-------+ | F | 2019-12-30 | 17 | | F | 2019-12-31 | 40 | | F | 2020-01-01 | 57 | | F | 2020-01-07 | 80 | | M | 2019-12-18 | 2 | | M | 2019-12-25 | 13 | | M | 2019-12-30 | 26 | | M | 2019-12-31 | 29 | | M | 2020-01-07 | 36 | +--------+------------+-------+ Explanation: For the female team: The first day is 2019-12-30, Priyanka scored 17 points and the total score for the team is 17. The second day is 2019-12-31, Priya scored 23 points and the total score for the team is 40. The third day is 2020-01-01, Aron scored 17 points and the total score for the team is 57. The fourth day is 2020-01-07, Alice scored 23 points and the total score for the team is 80. For the male team: The first day is 2019-12-18, Jose scored 2 points and the total score for the team is 2. The second day is 2019-12-25, Khali scored 11 points and the total score for the team is 13. The third day is 2019-12-30, Slaman scored 13 points and the total score for the team is 26. The fourth day is 2019-12-31, Joe scored 3 points and the total score for the team is 29. The fifth day is 2020-01-07, Bajrang scored 7 points and the total score for the team is 36.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT gender, day, SUM(score_points) OVER ( PARTITION BY gender ORDER BY gender, day ) AS total FROM Scores;
null
null
null
null
null
null
null
null
null
null
Check If a Number Is Majority Element in a Sorted Array 🔒
Given an integer array nums sorted in non-decreasing order and an integer target , return true if target is a majority element, or false otherwise . A majority element in an array nums is an element that appears more than nums.length / 2 times in the array.   Example 1: Input: nums = [2,4,5,5,5,5,5,6,6], target = 5 Output: true Explanation: The value 5 appears 5 times and the length of the array is 9. Thus, 5 is a majority element because 5 > 9/2 is true. Example 2: Input: nums = [10,100,101,101], target = 101 Output: false Explanation: The value 101 appears 2 times and the length of the array is 4. Thus, 101 is not a majority element because 2 > 4/2 is false.   Constraints: 1 <= nums.length <= 1000 1 <= nums[i], target <= 10 9 nums is sorted in non-decreasing order.
null
null
class Solution { public: bool isMajorityElement(vector<int>& nums, int target) { int n = nums.size(); int left = lower_bound(nums.begin(), nums.end(), target) - nums.begin(); int right = left + n / 2; return right < n && nums[right] == target; } };
null
null
func isMajorityElement(nums []int, target int) bool { n := len(nums) left := sort.SearchInts(nums, target) right := left + n/2 return right < n && nums[right] == target }
class Solution { public boolean isMajorityElement(int[] nums, int target) { int n = nums.length; int left = search(nums, target); int right = left + n / 2; return right < n && nums[right] == target; } private int search(int[] nums, int x) { int left = 0, right = nums.length; while (left < right) { int mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; } }
null
null
null
null
null
null
class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: left = bisect_left(nums, target) right = left + len(nums) // 2 return right < len(nums) and nums[right] == target
null
null
null
null
null
function isMajorityElement(nums: number[], target: number): boolean { const search = (x: number) => { let left = 0; let right = n; while (left < right) { const mid = (left + right) >> 1; if (nums[mid] >= x) { right = mid; } else { left = mid + 1; } } return left; }; const n = nums.length; const left = search(target); const right = left + (n >> 1); return right < n && nums[right] === target; }
Generate a String With Characters That Have Odd Counts
Given an integer n , return a string with n  characters such that each character in such string occurs an odd number of times . The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them.     Example 1: Input: n = 4 Output: "pppz" Explanation: "pppz" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as "ohhh" and "love". Example 2: Input: n = 2 Output: "xy" Explanation: "xy" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as "ag" and "ur". Example 3: Input: n = 7 Output: "holasss"   Constraints: 1 <= n <= 500
null
null
class Solution { public: string generateTheString(int n) { string ans(n, 'a'); if (n % 2 == 0) { ans[0] = 'b'; } return ans; } };
null
null
func generateTheString(n int) string { ans := strings.Repeat("a", n-1) if n%2 == 0 { ans += "b" } else { ans += "a" } return ans }
class Solution { public String generateTheString(int n) { return (n % 2 == 1) ? "a".repeat(n) : "a".repeat(n - 1) + "b"; } }
null
null
null
null
null
null
class Solution: def generateTheString(self, n: int) -> str: return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'
null
null
null
null
null
function generateTheString(n: number): string { const ans = Array(n).fill('a'); if (n % 2 === 0) { ans[0] = 'b'; } return ans.join(''); }
Unique Binary Search Trees
Given an integer n , return the number of structurally unique BST' s (binary search trees) which has exactly n nodes of unique values from 1 to n .   Example 1: Input: n = 3 Output: 5 Example 2: Input: n = 1 Output: 1   Constraints: 1 <= n <= 19
null
public class Solution { public int NumTrees(int n) { int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } }
class Solution { public: int numTrees(int n) { vector<int> f(n + 1); f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } };
null
null
func numTrees(n int) int { f := make([]int, n+1) f[0] = 1 for i := 1; i <= n; i++ { for j := 0; j < i; j++ { f[i] += f[j] * f[i-j-1] } } return f[n] }
class Solution { public int numTrees(int n) { int[] f = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; } }
null
null
null
null
null
null
class Solution: def numTrees(self, n: int) -> int: f = [1] + [0] * n for i in range(n + 1): for j in range(i): f[i] += f[j] * f[i - j - 1] return f[n]
null
impl Solution { pub fn num_trees(n: i32) -> i32 { let n = n as usize; let mut f = vec![0; n + 1]; f[0] = 1; for i in 1..=n { for j in 0..i { f[i] += f[j] * f[i - j - 1]; } } f[n] as i32 } }
null
null
null
function numTrees(n: number): number { const f: number[] = Array(n + 1).fill(0); f[0] = 1; for (let i = 1; i <= n; ++i) { for (let j = 0; j < i; ++j) { f[i] += f[j] * f[i - j - 1]; } } return f[n]; }
Rearrange Array to Maximize Prefix Score
You are given a 0-indexed integer array nums . You can rearrange the elements of nums to any order (including the given order). Let prefix be the array containing the prefix sums of nums after rearranging it. In other words, prefix[i] is the sum of the elements from 0 to i in nums after rearranging it. The score of nums is the number of positive integers in the array prefix . Return the maximum score you can achieve .   Example 1: Input: nums = [2,-1,0,1,-3,3,-3] Output: 6 Explanation: We can rearrange the array into nums = [2,3,1,-1,-3,0,-3]. prefix = [2,5,6,5,2,2,-1], so the score is 6. It can be shown that 6 is the maximum score we can obtain. Example 2: Input: nums = [-2,-3,0] Output: 0 Explanation: Any rearrangement of the array will result in a score of 0.   Constraints: 1 <= nums.length <= 10 5 -10 6 <= nums[i] <= 10 6
null
null
class Solution { public: int maxScore(vector<int>& nums) { sort(nums.rbegin(), nums.rend()); long long s = 0; int n = nums.size(); for (int i = 0; i < n; ++i) { s += nums[i]; if (s <= 0) { return i; } } return n; } };
null
null
func maxScore(nums []int) int { sort.Ints(nums) n := len(nums) s := 0 for i := range nums { s += nums[n-i-1] if s <= 0 { return i } } return n }
class Solution { public int maxScore(int[] nums) { Arrays.sort(nums); int n = nums.length; long s = 0; for (int i = 0; i < n; ++i) { s += nums[n - i - 1]; if (s <= 0) { return i; } } return n; } }
null
null
null
null
null
null
class Solution: def maxScore(self, nums: List[int]) -> int: nums.sort(reverse=True) s = 0 for i, x in enumerate(nums): s += x if s <= 0: return i return len(nums)
null
impl Solution { pub fn max_score(mut nums: Vec<i32>) -> i32 { nums.sort_by(|a, b| b.cmp(a)); let mut s: i64 = 0; for (i, &x) in nums.iter().enumerate() { s += x as i64; if s <= 0 { return i as i32; } } nums.len() as i32 } }
null
null
null
function maxScore(nums: number[]): number { nums.sort((a, b) => a - b); const n = nums.length; let s = 0; for (let i = 0; i < n; ++i) { s += nums[n - i - 1]; if (s <= 0) { return i; } } return n; }
Digit Count in Range 🔒
Given a single-digit integer d and two integers low and high , return the number of times that d occurs as a digit in all integers in the inclusive range [low, high] .   Example 1: Input: d = 1, low = 1, high = 13 Output: 6 Explanation: The digit d = 1 occurs 6 times in 1, 10, 11, 12, 13. Note that the digit d = 1 occurs twice in the number 11. Example 2: Input: d = 3, low = 100, high = 250 Output: 35 Explanation: The digit d = 3 occurs 35 times in 103,113,123,130,131,...,238,239,243.   Constraints: 0 <= d <= 9 1 <= low <= high <= 2 * 10 8
null
null
class Solution { public: int d; int a[11]; int dp[11][11]; int digitsCount(int d, int low, int high) { this->d = d; return f(high) - f(low - 1); } int f(int n) { memset(dp, -1, sizeof dp); int len = 0; while (n) { a[++len] = n % 10; n /= 10; } return dfs(len, 0, true, true); } int dfs(int pos, int cnt, bool lead, bool limit) { if (pos <= 0) { return cnt; } if (!lead && !limit && dp[pos][cnt] != -1) { return dp[pos][cnt]; } int up = limit ? a[pos] : 9; int ans = 0; for (int i = 0; i <= up; ++i) { if (i == 0 && lead) { ans += dfs(pos - 1, cnt, lead, limit && i == up); } else { ans += dfs(pos - 1, cnt + (i == d), false, limit && i == up); } } if (!lead && !limit) { dp[pos][cnt] = ans; } return ans; } };
null
null
func digitsCount(d int, low int, high int) int { f := func(n int) int { a := make([]int, 11) dp := make([][]int, 11) for i := range dp { dp[i] = make([]int, 11) for j := range dp[i] { dp[i][j] = -1 } } l := 0 for n > 0 { l++ a[l] = n % 10 n /= 10 } var dfs func(int, int, bool, bool) int dfs = func(pos, cnt int, lead, limit bool) int { if pos <= 0 { return cnt } if !lead && !limit && dp[pos][cnt] != -1 { return dp[pos][cnt] } up := 9 if limit { up = a[pos] } ans := 0 for i := 0; i <= up; i++ { if i == 0 && lead { ans += dfs(pos-1, cnt, lead, limit && i == up) } else { t := cnt if d == i { t++ } ans += dfs(pos-1, t, false, limit && i == up) } } if !lead && !limit { dp[pos][cnt] = ans } return ans } return dfs(l, 0, true, true) } return f(high) - f(low-1) }
class Solution { private int d; private int[] a = new int[11]; private int[][] dp = new int[11][11]; public int digitsCount(int d, int low, int high) { this.d = d; return f(high) - f(low - 1); } private int f(int n) { for (var e : dp) { Arrays.fill(e, -1); } int len = 0; while (n > 0) { a[++len] = n % 10; n /= 10; } return dfs(len, 0, true, true); } private int dfs(int pos, int cnt, boolean lead, boolean limit) { if (pos <= 0) { return cnt; } if (!lead && !limit && dp[pos][cnt] != -1) { return dp[pos][cnt]; } int up = limit ? a[pos] : 9; int ans = 0; for (int i = 0; i <= up; ++i) { if (i == 0 && lead) { ans += dfs(pos - 1, cnt, lead, limit && i == up); } else { ans += dfs(pos - 1, cnt + (i == d ? 1 : 0), false, limit && i == up); } } if (!lead && !limit) { dp[pos][cnt] = ans; } return ans; } }
null
null
null
null
null
null
class Solution: def digitsCount(self, d: int, low: int, high: int) -> int: return self.f(high, d) - self.f(low - 1, d) def f(self, n, d): @cache def dfs(pos, cnt, lead, limit): if pos <= 0: return cnt up = a[pos] if limit else 9 ans = 0 for i in range(up + 1): if i == 0 and lead: ans += dfs(pos - 1, cnt, lead, limit and i == up) else: ans += dfs(pos - 1, cnt + (i == d), False, limit and i == up) return ans a = [0] * 11 l = 0 while n: l += 1 a[l] = n % 10 n //= 10 return dfs(l, 0, True, True)
null
null
null
null
null
null
Convert Object to JSON String 🔒
Given a value, return a valid JSON string of that value. The value can be a string, number, array, object, boolean, or null. The returned string should not include extra spaces. The order of keys should be the same as the order returned by  Object.keys() . Please solve it without using the built-in JSON.stringify method.   Example 1: Input: object = {"y":1,"x":2} Output: {"y":1,"x":2} Explanation: Return the JSON representation. Note that the order of keys should be the same as the order returned by Object.keys(). Example 2: Input: object = {"a":"str","b":-12,"c":true,"d":null} Output: {"a":"str","b":-12,"c":true,"d":null} Explanation: The primitives of JSON are strings, numbers, booleans, and null. Example 3: Input: object = {"key":{"a":1,"b":[{},null,"Hello"]}} Output: {"key":{"a":1,"b":[{},null,"Hello"]}} Explanation: Objects and arrays can include other objects and arrays. Example 4: Input: object = true Output: true Explanation: Primitive types are valid inputs.   Constraints: value is a valid JSON value 1 <= JSON.stringify(object).length <= 10 5 maxNestingLevel <= 1000 all strings contain only alphanumeric characters
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
function jsonStringify(object: any): string { if (object === null) { return 'null'; } if (typeof object === 'string') { return `"${object}"`; } if (typeof object === 'number' || typeof object === 'boolean') { return object.toString(); } if (Array.isArray(object)) { return `[${object.map(jsonStringify).join(',')}]`; } if (typeof object === 'object') { return `{${Object.entries(object) .map(([key, value]) => `${jsonStringify(key)}:${jsonStringify(value)}`) .join(',')}}`; } return ''; }
Neighboring Bitwise XOR
A 0-indexed array derived with length n is derived by computing the bitwise XOR  (⊕) of adjacent values in a binary array original of length n . Specifically, for each index i in the range [0, n - 1] : If i = n - 1 , then derived[i] = original[i] ⊕ original[0] . Otherwise, derived[i] = original[i] ⊕ original[i + 1] . Given an array derived , your task is to determine whether there exists a valid binary array original that could have formed derived . Return true if such an array exists or false otherwise. A binary array is an array containing only 0's and 1's   Example 1: Input: derived = [1,1,0] Output: true Explanation: A valid original array that gives derived is [0,1,0]. derived[0] = original[0] ⊕ original[1] = 0 ⊕ 1 = 1 derived[1] = original[1] ⊕ original[2] = 1 ⊕ 0 = 1 derived[2] = original[2] ⊕ original[0] = 0 ⊕ 0 = 0 Example 2: Input: derived = [1,1] Output: true Explanation: A valid original array that gives derived is [0,1]. derived[0] = original[0] ⊕ original[1] = 1 derived[1] = original[1] ⊕ original[0] = 1 Example 3: Input: derived = [1,0] Output: false Explanation: There is no valid original array that gives derived.   Constraints: n == derived.length 1 <= n <= 10 5 The values in derived  are either 0's or 1's
null
public class Solution { public bool DoesValidArrayExist(int[] derived) { return derived.Aggregate(0, (acc, x) => acc ^ x) == 0; } }
class Solution { public: bool doesValidArrayExist(vector<int>& derived) { int s = 0; for (int x : derived) { s ^= x; } return s == 0; } };
null
null
func doesValidArrayExist(derived []int) bool { s := 0 for _, x := range derived { s ^= x } return s == 0 }
class Solution { public boolean doesValidArrayExist(int[] derived) { int s = 0; for (int x : derived) { s ^= x; } return s == 0; } }
/** * @param {number[]} derived * @return {boolean} */ var doesValidArrayExist = function (derived) { return derived.reduce((acc, x) => acc ^ x) === 0; };
null
null
null
null
null
class Solution: def doesValidArrayExist(self, derived: List[int]) -> bool: return reduce(xor, derived) == 0
null
impl Solution { pub fn does_valid_array_exist(derived: Vec<i32>) -> bool { derived.iter().fold(0, |acc, &x| acc ^ x) == 0 } }
null
null
null
function doesValidArrayExist(derived: number[]): boolean { return derived.reduce((acc, x) => acc ^ x) === 0; }
Minimum Number of Keypresses 🔒
You have a keypad with 9 buttons, numbered from 1 to 9 , each mapped to lowercase English letters. You can choose which characters each button is matched to as long as: All 26 lowercase English letters are mapped to. Each character is mapped to by exactly 1 button. Each button maps to at most 3 characters. To type the first character matched to a button, you press the button once. To type the second character, you press the button twice, and so on. Given a string s , return the minimum number of keypresses needed to type s using your keypad. Note that the characters mapped to by each button, and the order they are mapped in cannot be changed.   Example 1: Input: s = "apple" Output: 5 Explanation: One optimal way to setup your keypad is shown above. Type 'a' by pressing button 1 once. Type 'p' by pressing button 6 once. Type 'p' by pressing button 6 once. Type 'l' by pressing button 5 once. Type 'e' by pressing button 3 once. A total of 5 button presses are needed, so return 5. Example 2: Input: s = "abcdefghijkl" Output: 15 Explanation: One optimal way to setup your keypad is shown above. The letters 'a' to 'i' can each be typed by pressing a button once. Type 'j' by pressing button 1 twice. Type 'k' by pressing button 2 twice. Type 'l' by pressing button 3 twice. A total of 15 button presses are needed, so return 15.   Constraints: 1 <= s.length <= 10 5 s consists of lowercase English letters.
null
null
class Solution { public: int minimumKeypresses(string s) { int cnt[26]{}; for (char& c : s) { ++cnt[c - 'a']; } sort(begin(cnt), end(cnt), greater<int>()); int ans = 0, k = 1; for (int i = 1; i <= 26; ++i) { ans += k * cnt[i - 1]; if (i % 9 == 0) { ++k; } } return ans; } };
null
null
func minimumKeypresses(s string) (ans int) { cnt := make([]int, 26) for _, c := range s { cnt[c-'a']++ } sort.Ints(cnt) k := 1 for i := 1; i <= 26; i++ { ans += k * cnt[26-i] if i%9 == 0 { k++ } } return }
class Solution { public int minimumKeypresses(String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } Arrays.sort(cnt); int ans = 0, k = 1; for (int i = 1; i <= 26; ++i) { ans += k * cnt[26 - i]; if (i % 9 == 0) { ++k; } } return ans; } }
null
null
null
null
null
null
class Solution: def minimumKeypresses(self, s: str) -> int: cnt = Counter(s) ans, k = 0, 1 for i, x in enumerate(sorted(cnt.values(), reverse=True), 1): ans += k * x if i % 9 == 0: k += 1 return ans
null
null
null
null
null
function minimumKeypresses(s: string): number { const cnt: number[] = Array(26).fill(0); const a = 'a'.charCodeAt(0); for (const c of s) { ++cnt[c.charCodeAt(0) - a]; } cnt.sort((a, b) => b - a); let [ans, k] = [0, 1]; for (let i = 1; i <= 26; ++i) { ans += k * cnt[i - 1]; if (i % 9 === 0) { ++k; } } return ans; }
Find All Good Indices
You are given a 0-indexed integer array nums of size n and a positive integer k . We call an index i in the range k <= i < n - k good if the following conditions are satisfied: The k elements that are just before the index i are in non-increasing order. The k elements that are just after the index i are in non-decreasing order. Return an array of all good indices sorted in increasing order .   Example 1: Input: nums = [2,1,1,1,3,4,1], k = 2 Output: [2,3] Explanation: There are two good indices in the array: - Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order. - Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order. Note that the index 4 is not good because [4,1] is not non-decreasing. Example 2: Input: nums = [2,1,1,2], k = 2 Output: [] Explanation: There are no good indices in this array.   Constraints: n == nums.length 3 <= n <= 10 5 1 <= nums[i] <= 10 6 1 <= k <= n / 2
null
null
class Solution { public: vector<int> goodIndices(vector<int>& nums, int k) { int n = nums.size(); vector<int> decr(n, 1); vector<int> incr(n, 1); for (int i = 2; i < n; ++i) { if (nums[i - 1] <= nums[i - 2]) { decr[i] = decr[i - 1] + 1; } } for (int i = n - 3; ~i; --i) { if (nums[i + 1] <= nums[i + 2]) { incr[i] = incr[i + 1] + 1; } } vector<int> ans; for (int i = k; i < n - k; ++i) { if (decr[i] >= k && incr[i] >= k) { ans.push_back(i); } } return ans; } };
null
null
func goodIndices(nums []int, k int) []int { n := len(nums) decr := make([]int, n) incr := make([]int, n) for i := range decr { decr[i] = 1 incr[i] = 1 } for i := 2; i < n; i++ { if nums[i-1] <= nums[i-2] { decr[i] = decr[i-1] + 1 } } for i := n - 3; i >= 0; i-- { if nums[i+1] <= nums[i+2] { incr[i] = incr[i+1] + 1 } } ans := []int{} for i := k; i < n-k; i++ { if decr[i] >= k && incr[i] >= k { ans = append(ans, i) } } return ans }
class Solution { public List<Integer> goodIndices(int[] nums, int k) { int n = nums.length; int[] decr = new int[n]; int[] incr = new int[n]; Arrays.fill(decr, 1); Arrays.fill(incr, 1); for (int i = 2; i < n - 1; ++i) { if (nums[i - 1] <= nums[i - 2]) { decr[i] = decr[i - 1] + 1; } } for (int i = n - 3; i >= 0; --i) { if (nums[i + 1] <= nums[i + 2]) { incr[i] = incr[i + 1] + 1; } } List<Integer> ans = new ArrayList<>(); for (int i = k; i < n - k; ++i) { if (decr[i] >= k && incr[i] >= k) { ans.add(i); } } return ans; } }
null
null
null
null
null
null
class Solution: def goodIndices(self, nums: List[int], k: int) -> List[int]: n = len(nums) decr = [1] * (n + 1) incr = [1] * (n + 1) for i in range(2, n - 1): if nums[i - 1] <= nums[i - 2]: decr[i] = decr[i - 1] + 1 for i in range(n - 3, -1, -1): if nums[i + 1] <= nums[i + 2]: incr[i] = incr[i + 1] + 1 return [i for i in range(k, n - k) if decr[i] >= k and incr[i] >= k]
null
null
null
null
null
null
Maximum Number of Words Found in Sentences
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences , where each sentences[i] represents a single sentence . Return the maximum number of words that appear in a single sentence .   Example 1: Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much" ] Output: 6 Explanation: - The first sentence, "alice and bob love leetcode", has 5 words in total. - The second sentence, "i think so too", has 4 words in total. - The third sentence, "this is great thanks very much", has 6 words in total. Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words. Example 2: Input: sentences = ["please wait", "continue to fight" , "continue to win" ] Output: 3 Explanation: It is possible that multiple sentences contain the same number of words. In this example, the second and third sentences (underlined) have the same number of words.   Constraints: 1 <= sentences.length <= 100 1 <= sentences[i].length <= 100 sentences[i] consists only of lowercase English letters and ' ' only. sentences[i] does not have leading or trailing spaces. All the words in sentences[i] are separated by a single space.
#define max(a, b) (((a) > (b)) ? (a) : (b)) int mostWordsFound(char** sentences, int sentencesSize) { int ans = 0; for (int i = 0; i < sentencesSize; i++) { char* s = sentences[i]; int count = 1; for (int j = 0; s[j]; j++) { if (s[j] == ' ') { count++; } } ans = max(ans, count); } return ans; }
null
class Solution { public: int mostWordsFound(vector<string>& sentences) { int ans = 0; for (auto& s : sentences) { int cnt = 1 + count(s.begin(), s.end(), ' '); ans = max(ans, cnt); } return ans; } };
null
null
func mostWordsFound(sentences []string) (ans int) { for _, s := range sentences { cnt := 1 + strings.Count(s, " ") if ans < cnt { ans = cnt } } return }
class Solution { public int mostWordsFound(String[] sentences) { int ans = 0; for (var s : sentences) { int cnt = 1; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == ' ') { ++cnt; } } ans = Math.max(ans, cnt); } return ans; } }
null
null
null
null
null
null
class Solution: def mostWordsFound(self, sentences: List[str]) -> int: return 1 + max(s.count(' ') for s in sentences)
null
impl Solution { pub fn most_words_found(sentences: Vec<String>) -> i32 { let mut ans = 0; for s in sentences.iter() { let mut count = 1; for c in s.as_bytes() { if *c == b' ' { count += 1; } } ans = ans.max(count); } ans } }
null
null
null
function mostWordsFound(sentences: string[]): number { return sentences.reduce( (r, s) => Math.max( r, [...s].reduce((r, c) => r + (c === ' ' ? 1 : 0), 1), ), 0, ); }
Merge In Between Linked Lists
You are given two linked lists: list1 and list2 of sizes n and m respectively. Remove list1 's nodes from the a th node to the b th node, and put list2 in their place. The blue edges and nodes in the following figure indicate the result: Build the result list and return its head.   Example 1: Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002] Output: [10,1,13,1000000,1000001,1000002,5] Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. Example 2: Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004] Output: [0,1,1000000,1000001,1000002,1000003,1000004,6] Explanation: The blue edges and nodes in the above figure indicate the result.   Constraints: 3 <= list1.length <= 10 4 1 <= a <= b < list1.length - 1 1 <= list2.length <= 10 4
null
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public ListNode MergeInBetween(ListNode list1, int a, int b, ListNode list2) { ListNode p = list1, q = list1; while (--a > 0) { p = p.next; } while (b-- > 0) { q = q.next; } p.next = list2; while (p.next != null) { p = p.next; } p.next = q.next; q.next = null; return list1; } }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { auto p = list1, q = list1; while (--a) { p = p->next; } while (b--) { q = q->next; } p->next = list2; while (p->next) { p = p->next; } p->next = q->next; q->next = nullptr; return list1; } };
null
null
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func mergeInBetween(list1 *ListNode, a int, b int, list2 *ListNode) *ListNode { p, q := list1, list1 for ; a > 1; a-- { p = p.Next } for ; b > 0; b-- { q = q.Next } p.Next = list2 for p.Next != nil { p = p.Next } p.Next = q.Next q.Next = nil return list1 }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { ListNode p = list1, q = list1; while (--a > 0) { p = p.next; } while (b-- > 0) { q = q.next; } p.next = list2; while (p.next != null) { p = p.next; } p.next = q.next; q.next = null; return list1; } }
null
null
null
null
null
null
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeInBetween( self, list1: ListNode, a: int, b: int, list2: ListNode ) -> ListNode: p = q = list1 for _ in range(a - 1): p = p.next for _ in range(b): q = q.next p.next = list2 while p.next: p = p.next p.next = q.next q.next = None return list1
null
null
null
null
null
/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * constructor(val?: number, next?: ListNode | null) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } * } */ function mergeInBetween( list1: ListNode | null, a: number, b: number, list2: ListNode | null, ): ListNode | null { let p = list1; let q = list1; while (--a > 0) { p = p.next; } while (b-- > 0) { q = q.next; } p.next = list2; while (p.next) { p = p.next; } p.next = q.next; q.next = null; return list1; }
Divide Two Integers
Given two integers dividend and divisor , divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8 , and -2.7335 would be truncated to -2 . Return the quotient after dividing dividend by divisor . Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2 31 , 2 31 − 1] . For this problem, if the quotient is strictly greater than 2 31 - 1 , then return 2 31 - 1 , and if the quotient is strictly less than -2 31 , then return -2 31 .   Example 1: Input: dividend = 10, divisor = 3 Output: 3 Explanation: 10/3 = 3.33333.. which is truncated to 3. Example 2: Input: dividend = 7, divisor = -3 Output: -2 Explanation: 7/-3 = -2.33333.. which is truncated to -2.   Constraints: -2 31 <= dividend, divisor <= 2 31 - 1 divisor != 0
null
public class Solution { public int Divide(int a, int b) { if (b == 1) { return a; } if (a == int.MinValue && b == -1) { return int.MaxValue; } bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (int.MinValue >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } }
class Solution { public: int divide(int a, int b) { if (b == 1) { return a; } if (a == INT_MIN && b == -1) { return INT_MAX; } bool sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (INT_MIN >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } };
null
null
func divide(a int, b int) int { if b == 1 { return a } if a == math.MinInt32 && b == -1 { return math.MaxInt32 } sign := (a > 0 && b > 0) || (a < 0 && b < 0) if a > 0 { a = -a } if b > 0 { b = -b } ans := 0 for a <= b { x := b cnt := 1 for x >= (math.MinInt32>>1) && a <= (x<<1) { x <<= 1 cnt <<= 1 } ans += cnt a -= x } if sign { return ans } return -ans }
class Solution { public int divide(int a, int b) { if (b == 1) { return a; } if (a == Integer.MIN_VALUE && b == -1) { return Integer.MAX_VALUE; } boolean sign = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; int ans = 0; while (a <= b) { int x = b; int cnt = 1; while (x >= (Integer.MIN_VALUE >> 1) && a <= (x << 1)) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; } }
null
null
null
null
class Solution { /** * @param integer $a * @param integer $b * @return integer */ function divide($a, $b) { if ($b == 0) { throw new Exception('Can not divide by 0'); } elseif ($a == 0) { return 0; } if ($a == -2147483648 && $b == -1) { return 2147483647; } $sign = $a < 0 != $b < 0; $a = abs($a); $b = abs($b); $ans = 0; while ($a >= $b) { $x = $b; $cnt = 1; while ($a >= $x << 1) { $x <<= 1; $cnt <<= 1; } $a -= $x; $ans += $cnt; } return $sign ? -$ans : $ans; } }
null
class Solution: def divide(self, a: int, b: int) -> int: if b == 1: return a if a == -(2**31) and b == -1: return 2**31 - 1 sign = (a > 0 and b > 0) or (a < 0 and b < 0) a = -a if a > 0 else a b = -b if b > 0 else b ans = 0 while a <= b: x = b cnt = 1 while x >= (-(2**30)) and a <= (x << 1): x <<= 1 cnt <<= 1 a -= x ans += cnt return ans if sign else -ans
null
null
null
null
null
function divide(a: number, b: number): number { if (b === 1) { return a; } if (a === -(2 ** 31) && b === -1) { return 2 ** 31 - 1; } const sign: boolean = (a > 0 && b > 0) || (a < 0 && b < 0); a = a > 0 ? -a : a; b = b > 0 ? -b : b; let ans: number = 0; while (a <= b) { let x: number = b; let cnt: number = 1; while (x >= -(2 ** 30) && a <= x << 1) { x <<= 1; cnt <<= 1; } ans += cnt; a -= x; } return sign ? ans : -ans; }
Array Transformation 🔒
Given an initial array arr , every day you produce a new array using the array of the previous day. On the i -th day, you do the following operations on the array of day  i-1  to produce the array of day i : If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented. The first and last elements never change. After some days, the array does not change. Return that final array.   Example 1: Input: arr = [6,2,3,4] Output: [6,3,3,4] Explanation: On the first day, the array is changed from [6,2,3,4] to [6,3,3,4]. No more operations can be done to this array. Example 2: Input: arr = [1,6,3,4,3,5] Output: [1,4,4,4,4,5] Explanation: On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5]. On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5]. No more operations can be done to this array.   Constraints: 3 <= arr.length <= 100 1 <= arr[i] <= 100
null
null
class Solution { public: vector<int> transformArray(vector<int>& arr) { bool f = true; while (f) { f = false; vector<int> t = arr; for (int i = 1; i < arr.size() - 1; ++i) { if (t[i] > t[i - 1] && t[i] > t[i + 1]) { --arr[i]; f = true; } if (t[i] < t[i - 1] && t[i] < t[i + 1]) { ++arr[i]; f = true; } } } return arr; } };
null
null
func transformArray(arr []int) []int { f := true for f { f = false t := make([]int, len(arr)) copy(t, arr) for i := 1; i < len(arr)-1; i++ { if t[i] > t[i-1] && t[i] > t[i+1] { arr[i]-- f = true } if t[i] < t[i-1] && t[i] < t[i+1] { arr[i]++ f = true } } } return arr }
class Solution { public List<Integer> transformArray(int[] arr) { boolean f = true; while (f) { f = false; int[] t = arr.clone(); for (int i = 1; i < t.length - 1; ++i) { if (t[i] > t[i - 1] && t[i] > t[i + 1]) { --arr[i]; f = true; } if (t[i] < t[i - 1] && t[i] < t[i + 1]) { ++arr[i]; f = true; } } } List<Integer> ans = new ArrayList<>(); for (int x : arr) { ans.add(x); } return ans; } }
null
null
null
null
null
null
class Solution: def transformArray(self, arr: List[int]) -> List[int]: f = True while f: f = False t = arr[:] for i in range(1, len(t) - 1): if t[i] > t[i - 1] and t[i] > t[i + 1]: arr[i] -= 1 f = True if t[i] < t[i - 1] and t[i] < t[i + 1]: arr[i] += 1 f = True return arr
null
null
null
null
null
null
Longest Happy Prefix
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). Given a string s , return the longest happy prefix of s . Return an empty string "" if no such prefix exists.   Example 1: Input: s = "level" Output: "l" Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "leve"), and suffix ("l", "el", "vel", "evel"). The largest prefix which is also suffix is given by "l". Example 2: Input: s = "ababab" Output: "abab" Explanation: "abab" is the largest prefix which is also suffix. They can overlap in the original string.   Constraints: 1 <= s.length <= 10 5 s contains only lowercase English letters.
null
null
class Solution { public: string longestPrefix(string s) { s.push_back('#'); int n = s.size(); int next[n]; next[0] = -1; next[1] = 0; for (int i = 2, j = 0; i < n;) { if (s[i - 1] == s[j]) { next[i++] = ++j; } else if (j > 0) { j = next[j]; } else { next[i++] = 0; } } return s.substr(0, next[n - 1]); } };
null
null
func longestPrefix(s string) string { s += "#" n := len(s) next := make([]int, n) next[0], next[1] = -1, 0 for i, j := 2, 0; i < n; { if s[i-1] == s[j] { j++ next[i] = j i++ } else if j > 0 { j = next[j] } else { next[i] = 0 i++ } } return s[:next[n-1]] }
class Solution { public String longestPrefix(String s) { s += "#"; int n = s.length(); int[] next = new int[n]; next[0] = -1; for (int i = 2, j = 0; i < n;) { if (s.charAt(i - 1) == s.charAt(j)) { next[i++] = ++j; } else if (j > 0) { j = next[j]; } else { next[i++] = 0; } } return s.substring(0, next[n - 1]); } }
null
null
null
null
null
null
class Solution: def longestPrefix(self, s: str) -> str: s += "#" n = len(s) next = [0] * n next[0] = -1 i, j = 2, 0 while i < n: if s[i - 1] == s[j]: j += 1 next[i] = j i += 1 elif j: j = next[j] else: next[i] = 0 i += 1 return s[: next[-1]]
null
impl Solution { pub fn longest_prefix(s: String) -> String { let n = s.len(); for i in (0..n).rev() { if s[0..i] == s[n - i..n] { return s[0..i].to_string(); } } String::new() } }
null
null
null
function longestPrefix(s: string): string { s += '#'; const n = s.length; const next: number[] = Array(n).fill(0); next[0] = -1; for (let i = 2, j = 0; i < n; ) { if (s[i - 1] === s[j]) { next[i++] = ++j; } else if (j > 0) { j = next[j]; } else { next[i++] = 0; } } return s.slice(0, next[n - 1]); }
Article Views II 🔒
Table: Views +---------------+---------+ | Column Name | Type | +---------------+---------+ | article_id | int | | author_id | int | | viewer_id | int | | view_date | date | +---------------+---------+ This table may have duplicate rows. Each row of this table indicates that some viewer viewed an article (written by some author) on some date. Note that equal author_id and viewer_id indicate the same person.   Write a solution to find all the people who viewed more than one article on the same date. Return the result table sorted by id in ascending order. The result format is in the following example.   Example 1: Input: Views table: +------------+-----------+-----------+------------+ | article_id | author_id | viewer_id | view_date | +------------+-----------+-----------+------------+ | 1 | 3 | 5 | 2019-08-01 | | 3 | 4 | 5 | 2019-08-01 | | 1 | 3 | 6 | 2019-08-02 | | 2 | 7 | 7 | 2019-08-01 | | 2 | 7 | 6 | 2019-08-02 | | 4 | 7 | 1 | 2019-07-22 | | 3 | 4 | 4 | 2019-07-21 | | 3 | 4 | 4 | 2019-07-21 | +------------+-----------+-----------+------------+ Output: +------+ | id | +------+ | 5 | | 6 | +------+
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT DISTINCT viewer_id AS id FROM Views GROUP BY viewer_id, view_date HAVING COUNT(DISTINCT article_id) > 1 ORDER BY 1;
null
null
null
null
null
null
null
null
null
null
Flipping an Image
Given an n x n binary matrix image , flip the image horizontally , then invert it, and return the resulting image . To flip an image horizontally means that each row of the image is reversed. For example, flipping [1,1,0] horizontally results in [0,1,1] . To invert an image means that each 0 is replaced by 1 , and each 1 is replaced by 0 . For example, inverting [0,1,1] results in [1,0,0] .   Example 1: Input: image = [[1,1,0],[1,0,1],[0,0,0]] Output: [[1,0,0],[0,1,0],[1,1,1]] Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]]. Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]] Example 2: Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]. Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]   Constraints: n == image.length n == image[i].length 1 <= n <= 20 images[i][j] is either 0 or 1 .
null
null
class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& image) { for (auto& row : image) { int i = 0, j = row.size() - 1; for (; i < j; ++i, --j) { if (row[i] == row[j]) { row[i] ^= 1; row[j] ^= 1; } } if (i == j) { row[i] ^= 1; } } return image; } };
null
null
func flipAndInvertImage(image [][]int) [][]int { for _, row := range image { i, j := 0, len(row)-1 for ; i < j; i, j = i+1, j-1 { if row[i] == row[j] { row[i] ^= 1 row[j] ^= 1 } } if i == j { row[i] ^= 1 } } return image }
class Solution { public int[][] flipAndInvertImage(int[][] image) { for (var row : image) { int i = 0, j = row.length - 1; for (; i < j; ++i, --j) { if (row[i] == row[j]) { row[i] ^= 1; row[j] ^= 1; } } if (i == j) { row[i] ^= 1; } } return image; } }
/** * @param {number[][]} image * @return {number[][]} */ var flipAndInvertImage = function (image) { for (const row of image) { let i = 0; let j = row.length - 1; for (; i < j; ++i, --j) { if (row[i] == row[j]) { row[i] ^= 1; row[j] ^= 1; } } if (i == j) { row[i] ^= 1; } } return image; };
null
null
null
null
null
class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: n = len(image) for row in image: i, j = 0, n - 1 while i < j: if row[i] == row[j]: row[i] ^= 1 row[j] ^= 1 i, j = i + 1, j - 1 if i == j: row[i] ^= 1 return image
null
null
null
null
null
null
Minimum Suffix Flips
You are given a 0-indexed binary string target of length n . You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target . In one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1] . Flip means changing '0' to '1' and '1' to '0' . Return the minimum number of operations needed to make s equal to target .   Example 1: Input: target = "10111" Output: 3 Explanation: Initially, s = "00000". Choose index i = 2: "00 000 " -> "00 111 " Choose index i = 0: " 00111 " -> " 11000 " Choose index i = 1: "1 1000 " -> "1 0111 " We need at least 3 flip operations to form target. Example 2: Input: target = "101" Output: 3 Explanation: Initially, s = "000". Choose index i = 0: " 000 " -> " 111 " Choose index i = 1: "1 11 " -> "1 00 " Choose index i = 2: "10 0 " -> "10 1 " We need at least 3 flip operations to form target. Example 3: Input: target = "00000" Output: 0 Explanation: We do not need any operations since the initial s already equals target.   Constraints: n == target.length 1 <= n <= 10 5 target[i] is either '0' or '1' .
null
null
class Solution { public: int minFlips(string target) { int ans = 0; for (char c : target) { int v = c - '0'; if ((ans & 1) ^ v) { ++ans; } } return ans; } };
null
null
func minFlips(target string) int { ans := 0 for _, c := range target { v := int(c - '0') if ((ans & 1) ^ v) != 0 { ans++ } } return ans }
class Solution { public int minFlips(String target) { int ans = 0; for (int i = 0; i < target.length(); ++i) { int v = target.charAt(i) - '0'; if (((ans & 1) ^ v) != 0) { ++ans; } } return ans; } }
null
null
null
null
null
null
class Solution: def minFlips(self, target: str) -> int: ans = 0 for v in target: if (ans & 1) ^ int(v): ans += 1 return ans
null
null
null
null
null
null
Friday Purchases I 🔒
Table: Purchases +---------------+------+ | Column Name | Type | +---------------+------+ | user_id | int | | purchase_date | date | | amount_spend | int | +---------------+------+ (user_id, purchase_date, amount_spend) is the primary key (combination of columns with unique values) for this table. purchase_date will range from November 1, 2023, to November 30, 2023, inclusive of both dates. Each row contains user id, purchase date, and amount spend. Write a solution to calculate the total spending by users on each Friday of every week in November 2023 . Output only weeks that include at least one purchase on a Friday . Return the result table ordered by week of month in ascending order. The result format is in the following example.   Example 1: Input: Purchases table: +---------+---------------+--------------+ | user_id | purchase_date | amount_spend | +---------+---------------+--------------+ | 11 | 2023-11-07 | 1126 | | 15 | 2023-11-30 | 7473 | | 17 | 2023-11-14 | 2414 | | 12 | 2023-11-24 | 9692 | | 8 | 2023-11-03 | 5117 | | 1 | 2023-11-16 | 5241 | | 10 | 2023-11-12 | 8266 | | 13 | 2023-11-24 | 12000 | +---------+---------------+--------------+ Output: +---------------+---------------+--------------+ | week_of_month | purchase_date | total_amount | +---------------+---------------+--------------+ | 1 | 2023-11-03 | 5117 | | 4 | 2023-11-24 | 21692 | +---------------+---------------+--------------+ Explanation: - During the first week of November 2023, transactions amounting to $5,117 occurred on Friday, 2023-11-03. - For the second week of November 2023, there were no transactions on Friday, 2023-11-10. - Similarly, during the third week of November 2023, there were no transactions on Friday, 2023-11-17. - In the fourth week of November 2023, two transactions took place on Friday, 2023-11-24, amounting to $12,000 and $9,692 respectively, summing up to a total of $21,692. Output table is ordered by week_of_month in ascending order.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below SELECT CEIL(DAYOFMONTH(purchase_date) / 7) AS week_of_month, purchase_date, SUM(amount_spend) AS total_amount FROM Purchases WHERE DATE_FORMAT(purchase_date, '%Y%m') = '202311' AND DAYOFWEEK(purchase_date) = 6 GROUP BY 2 ORDER BY 1;
null
null
null
null
null
null
null
null
null
null
Depth of BST Given Insertion Order 🔒
You are given a 0-indexed integer array order of length n , a permutation of integers from 1 to n representing the order of insertion into a binary search tree . A binary search tree is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. The binary search tree is constructed as follows: order[0] will be the root of the binary search tree. All subsequent elements are inserted as the child of any existing node such that the binary search tree properties hold. Return the depth of the binary search tree . A binary tree's depth is the number of nodes along the longest path from the root node down to the farthest leaf node.   Example 1: Input: order = [2,1,4,3] Output: 3 Explanation: The binary search tree has a depth of 3 with path 2->3->4. Example 2: Input: order = [2,1,3,4] Output: 3 Explanation: The binary search tree has a depth of 3 with path 2->3->4. Example 3: Input: order = [1,2,3,4] Output: 4 Explanation: The binary search tree has a depth of 4 with path 1->2->3->4.   Constraints: n == order.length 1 <= n <= 10 5 order is a permutation of integers between 1 and n .
null
null
null
null
null
null
class Solution { public int maxDepthBST(int[] order) { TreeMap<Integer, Integer> tm = new TreeMap<>(); tm.put(0, 0); tm.put(Integer.MAX_VALUE, 0); tm.put(order[0], 1); int ans = 1; for (int i = 1; i < order.length; ++i) { int v = order[i]; Map.Entry<Integer, Integer> lower = tm.lowerEntry(v); Map.Entry<Integer, Integer> higher = tm.higherEntry(v); int depth = 1 + Math.max(lower.getValue(), higher.getValue()); ans = Math.max(ans, depth); tm.put(v, depth); } return ans; } }
null
null
null
null
null
null
class Solution: def maxDepthBST(self, order: List[int]) -> int: sd = SortedDict({0: 0, inf: 0, order[0]: 1}) ans = 1 for v in order[1:]: lower = sd.bisect_left(v) - 1 higher = lower + 1 depth = 1 + max(sd.values()[lower], sd.values()[higher]) ans = max(ans, depth) sd[v] = depth return ans
null
null
null
null
null
null
Detect Squares
You are given a stream of points on the X-Y plane. Design an algorithm that: Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points. Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area . An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class: DetectSquares() Initializes the object with an empty data structure. void add(int[] point) Adds a new point point = [x, y] to the data structure. int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.   Example 1: Input ["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] Output [null, null, null, null, 1, 0, null, 2] Explanation DetectSquares detectSquares = new DetectSquares(); detectSquares.add([3, 10]); detectSquares.add([11, 2]); detectSquares.add([3, 2]); detectSquares.count([11, 10]); // return 1. You can choose: // - The first, second, and third points detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure. detectSquares.add([11, 2]); // Adding duplicate points is allowed. detectSquares.count([11, 10]); // return 2. You can choose: // - The first, second, and third points // - The first, third, and fourth points   Constraints: point.length == 2 0 <= x, y <= 1000 At most 3000 calls in total will be made to add and count .
null
null
class DetectSquares { public: DetectSquares() { } void add(vector<int> point) { int x = point[0], y = point[1]; ++cnt[x][y]; } int count(vector<int> point) { int x1 = point[0], y1 = point[1]; if (!cnt.count(x1)) { return 0; } int ans = 0; for (auto& [x2, cnt2] : cnt) { if (x2 != x1) { int d = x2 - x1; auto& cnt1 = cnt[x1]; ans += cnt2[y1] * cnt1[y1 + d] * cnt2[y1 + d]; ans += cnt2[y1] * cnt1[y1 - d] * cnt2[y1 - d]; } } return ans; } private: unordered_map<int, unordered_map<int, int>> cnt; }; /** * Your DetectSquares object will be instantiated and called as such: * DetectSquares* obj = new DetectSquares(); * obj->add(point); * int param_2 = obj->count(point); */
null
null
type DetectSquares struct { cnt map[int]map[int]int } func Constructor() DetectSquares { return DetectSquares{map[int]map[int]int{}} } func (this *DetectSquares) Add(point []int) { x, y := point[0], point[1] if _, ok := this.cnt[x]; !ok { this.cnt[x] = map[int]int{} } this.cnt[x][y]++ } func (this *DetectSquares) Count(point []int) (ans int) { x1, y1 := point[0], point[1] if cnt1, ok := this.cnt[x1]; ok { for x2, cnt2 := range this.cnt { if x2 != x1 { d := x2 - x1 ans += cnt2[y1] * cnt1[y1+d] * cnt2[y1+d] ans += cnt2[y1] * cnt1[y1-d] * cnt2[y1-d] } } } return } /** * Your DetectSquares object will be instantiated and called as such: * obj := Constructor(); * obj.Add(point); * param_2 := obj.Count(point); */
class DetectSquares { private Map<Integer, Map<Integer, Integer>> cnt = new HashMap<>(); public DetectSquares() { } public void add(int[] point) { int x = point[0], y = point[1]; cnt.computeIfAbsent(x, k -> new HashMap<>()).merge(y, 1, Integer::sum); } public int count(int[] point) { int x1 = point[0], y1 = point[1]; if (!cnt.containsKey(x1)) { return 0; } int ans = 0; for (var e : cnt.entrySet()) { int x2 = e.getKey(); if (x2 != x1) { int d = x2 - x1; var cnt1 = cnt.get(x1); var cnt2 = e.getValue(); ans += cnt2.getOrDefault(y1, 0) * cnt1.getOrDefault(y1 + d, 0) * cnt2.getOrDefault(y1 + d, 0); ans += cnt2.getOrDefault(y1, 0) * cnt1.getOrDefault(y1 - d, 0) * cnt2.getOrDefault(y1 - d, 0); } } return ans; } } /** * Your DetectSquares object will be instantiated and called as such: * DetectSquares obj = new DetectSquares(); * obj.add(point); * int param_2 = obj.count(point); */
null
null
null
null
null
null
class DetectSquares: def __init__(self): self.cnt = defaultdict(Counter) def add(self, point: List[int]) -> None: x, y = point self.cnt[x][y] += 1 def count(self, point: List[int]) -> int: x1, y1 = point if x1 not in self.cnt: return 0 ans = 0 for x2 in self.cnt.keys(): if x2 != x1: d = x2 - x1 ans += self.cnt[x2][y1] * self.cnt[x1][y1 + d] * self.cnt[x2][y1 + d] ans += self.cnt[x2][y1] * self.cnt[x1][y1 - d] * self.cnt[x2][y1 - d] return ans # Your DetectSquares object will be instantiated and called as such: # obj = DetectSquares() # obj.add(point) # param_2 = obj.count(point)
null
null
null
null
null
null
Circular Array Loop
You are playing a game involving a circular array of non-zero integers nums . Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i : If nums[i] is positive, move nums[i] steps forward , and If nums[i] is negative, move nums[i] steps backward . Since the array is circular , you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices seq of length k where: Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ... Every nums[seq[j]] is either all positive or all negative . k > 1 Return true if there is a cycle in nums , or false otherwise .   Example 1: Input: nums = [2,-1,1,2,2] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction). Example 2: Input: nums = [-1,-2,-3,-4,-5,6] Output: false Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. The only cycle is of size 1, so we return false. Example 3: Input: nums = [1,-1,5,1,4] Output: true Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward. We can see the cycle 0 --> 1 --> 0 --> ..., and while it is of size > 1, it has a node jumping forward and a node jumping backward, so it is not a cycle . We can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction).   Constraints: 1 <= nums.length <= 5000 -1000 <= nums[i] <= 1000 nums[i] != 0   Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?
null
null
class Solution { public: bool circularArrayLoop(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { if (!nums[i]) continue; int slow = i, fast = next(nums, i); while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(nums, fast)] > 0) { if (slow == fast) { if (slow != next(nums, slow)) return true; break; } slow = next(nums, slow); fast = next(nums, next(nums, fast)); } int j = i; while (nums[j] * nums[next(nums, j)] > 0) { nums[j] = 0; j = next(nums, j); } } return false; } int next(vector<int>& nums, int i) { int n = nums.size(); return (i + nums[i] % n + n) % n; } };
null
null
func circularArrayLoop(nums []int) bool { for i, num := range nums { if num == 0 { continue } slow, fast := i, next(nums, i) for nums[slow]*nums[fast] > 0 && nums[slow]*nums[next(nums, fast)] > 0 { if slow == fast { if slow != next(nums, slow) { return true } break } slow, fast = next(nums, slow), next(nums, next(nums, fast)) } j := i for nums[j]*nums[next(nums, j)] > 0 { nums[j] = 0 j = next(nums, j) } } return false } func next(nums []int, i int) int { n := len(nums) return (i + nums[i]%n + n) % n }
class Solution { private int n; private int[] nums; public boolean circularArrayLoop(int[] nums) { n = nums.length; this.nums = nums; for (int i = 0; i < n; ++i) { if (nums[i] == 0) { continue; } int slow = i, fast = next(i); while (nums[slow] * nums[fast] > 0 && nums[slow] * nums[next(fast)] > 0) { if (slow == fast) { if (slow != next(slow)) { return true; } break; } slow = next(slow); fast = next(next(fast)); } int j = i; while (nums[j] * nums[next(j)] > 0) { nums[j] = 0; j = next(j); } } return false; } private int next(int i) { return (i + nums[i] % n + n) % n; } }
null
null
null
null
null
null
class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: n = len(nums) def next(i): return (i + nums[i] % n + n) % n for i in range(n): if nums[i] == 0: continue slow, fast = i, next(i) while nums[slow] * nums[fast] > 0 and nums[slow] * nums[next(fast)] > 0: if slow == fast: if slow != next(slow): return True break slow, fast = next(slow), next(next(fast)) j = i while nums[j] * nums[next(j)] > 0: nums[j] = 0 j = next(j) return False
null
null
null
null
null
null
Count Integers in Intervals
Given an empty set of intervals, implement a data structure that can: Add an interval to the set of intervals. Count the number of integers that are present in at least one interval. Implement the CountIntervals class: CountIntervals() Initializes the object with an empty set of intervals. void add(int left, int right) Adds the interval [left, right] to the set of intervals. int count() Returns the number of integers that are present in at least one interval. Note that an interval [left, right] denotes all the integers x where left <= x <= right .   Example 1: Input ["CountIntervals", "add", "add", "count", "add", "count"] [[], [2, 3], [7, 10], [], [5, 8], []] Output [null, null, null, 6, null, 8] Explanation CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. countIntervals.add(2, 3); // add [2, 3] to the set of intervals. countIntervals.add(7, 10); // add [7, 10] to the set of intervals. countIntervals.count(); // return 6 // the integers 2 and 3 are present in the interval [2, 3]. // the integers 7, 8, 9, and 10 are present in the interval [7, 10]. countIntervals.add(5, 8); // add [5, 8] to the set of intervals. countIntervals.count(); // return 8 // the integers 2 and 3 are present in the interval [2, 3]. // the integers 5 and 6 are present in the interval [5, 8]. // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10]. // the integers 9 and 10 are present in the interval [7, 10].   Constraints: 1 <= left <= right <= 10 9 At most 10 5 calls in total will be made to add and count . At least one call will be made to count .
null
null
class Node { public: Node(int l, int r) : l(l) , r(r) , mid((l + r) / 2) , v(0) , add(0) , left(nullptr) , right(nullptr) {} int l, r, mid, v, add; Node* left; Node* right; }; class SegmentTree { public: SegmentTree() : root(new Node(1, 1000000001)) {} void modify(int l, int r, int v, Node* node = nullptr) { if (node == nullptr) { node = root; } if (l > r) { return; } if (node->l >= l && node->r <= r) { node->v = node->r - node->l + 1; node->add = v; return; } pushdown(node); if (l <= node->mid) { modify(l, r, v, node->left); } if (r > node->mid) { modify(l, r, v, node->right); } pushup(node); } int query(int l, int r, Node* node = nullptr) { if (node == nullptr) { node = root; } if (l > r) { return 0; } if (node->l >= l && node->r <= r) { return node->v; } pushdown(node); int v = 0; if (l <= node->mid) { v += query(l, r, node->left); } if (r > node->mid) { v += query(l, r, node->right); } return v; } private: Node* root; void pushup(Node* node) { node->v = node->left->v + node->right->v; } void pushdown(Node* node) { if (node->left == nullptr) { node->left = new Node(node->l, node->mid); } if (node->right == nullptr) { node->right = new Node(node->mid + 1, node->r); } if (node->add != 0) { Node* left = node->left; Node* right = node->right; left->add = node->add; right->add = node->add; left->v = left->r - left->l + 1; right->v = right->r - right->l + 1; node->add = 0; } } }; class CountIntervals { public: CountIntervals() {} void add(int left, int right) { tree.modify(left, right, 1); } int count() { return tree.query(1, 1000000000); } private: SegmentTree tree; }; /** * Your CountIntervals object will be instantiated and called as such: * CountIntervals* obj = new CountIntervals(); * obj->add(left,right); * int param_2 = obj->count(); */
null
null
type Node struct { left *Node right *Node l int r int mid int v int add int } type SegmentTree struct { root *Node } func newNode(l, r int) *Node { return &Node{ left: nil, right: nil, l: l, r: r, mid: (l + r) / 2, v: 0, add: 0, } } func newSegmentTree() *SegmentTree { return &SegmentTree{ root: newNode(1, 1000000001), } } func (st *SegmentTree) modify(l, r, v int, node *Node) { if node == nil { node = st.root } if l > r { return } if node.l >= l && node.r <= r { node.v = node.r - node.l + 1 node.add = v return } st.pushdown(node) if l <= node.mid { st.modify(l, r, v, node.left) } if r > node.mid { st.modify(l, r, v, node.right) } st.pushup(node) } func (st *SegmentTree) query(l, r int, node *Node) int { if node == nil { node = st.root } if l > r { return 0 } if node.l >= l && node.r <= r { return node.v } st.pushdown(node) v := 0 if l <= node.mid { v += st.query(l, r, node.left) } if r > node.mid { v += st.query(l, r, node.right) } return v } func (st *SegmentTree) pushup(node *Node) { node.v = node.left.v + node.right.v } func (st *SegmentTree) pushdown(node *Node) { if node.left == nil { node.left = newNode(node.l, node.mid) } if node.right == nil { node.right = newNode(node.mid+1, node.r) } if node.add != 0 { left := node.left right := node.right left.add = node.add right.add = node.add left.v = left.r - left.l + 1 right.v = right.r - right.l + 1 node.add = 0 } } type CountIntervals struct { tree *SegmentTree } func Constructor() CountIntervals { return CountIntervals{ tree: newSegmentTree(), } } func (ci *CountIntervals) Add(left, right int) { ci.tree.modify(left, right, 1, nil) } func (ci *CountIntervals) Count() int { return ci.tree.query(1, 1000000000, nil) } /** * Your CountIntervals object will be instantiated and called as such: * obj := Constructor(); * obj.Add(left,right); * param_2 := obj.Count(); */
class Node { Node left; Node right; int l; int r; int mid; int v; int add; public Node(int l, int r) { this.l = l; this.r = r; this.mid = (l + r) >> 1; } } class SegmentTree { private Node root = new Node(1, (int) 1e9 + 1); public SegmentTree() { } public void modify(int l, int r, int v) { modify(l, r, v, root); } public void modify(int l, int r, int v, Node node) { if (l > r) { return; } if (node.l >= l && node.r <= r) { node.v = node.r - node.l + 1; node.add = v; return; } pushdown(node); if (l <= node.mid) { modify(l, r, v, node.left); } if (r > node.mid) { modify(l, r, v, node.right); } pushup(node); } public int query(int l, int r) { return query(l, r, root); } public int query(int l, int r, Node node) { if (l > r) { return 0; } if (node.l >= l && node.r <= r) { return node.v; } pushdown(node); int v = 0; if (l <= node.mid) { v += query(l, r, node.left); } if (r > node.mid) { v += query(l, r, node.right); } return v; } public void pushup(Node node) { node.v = node.left.v + node.right.v; } public void pushdown(Node node) { if (node.left == null) { node.left = new Node(node.l, node.mid); } if (node.right == null) { node.right = new Node(node.mid + 1, node.r); } if (node.add != 0) { Node left = node.left, right = node.right; left.add = node.add; right.add = node.add; left.v = left.r - left.l + 1; right.v = right.r - right.l + 1; node.add = 0; } } } class CountIntervals { private SegmentTree tree = new SegmentTree(); public CountIntervals() { } public void add(int left, int right) { tree.modify(left, right, 1); } public int count() { return tree.query(1, (int) 1e9); } } /** * Your CountIntervals object will be instantiated and called as such: * CountIntervals obj = new CountIntervals(); * obj.add(left,right); * int param_2 = obj.count(); */
null
null
null
null
null
null
class Node: __slots__ = ("left", "right", "l", "r", "mid", "v", "add") def __init__(self, l, r): self.left = None self.right = None self.l = l self.r = r self.mid = (l + r) // 2 self.v = 0 self.add = 0 class SegmentTree: def __init__(self): self.root = Node(1, int(1e9) + 1) def modify(self, l, r, v, node=None): if node is None: node = self.root if l > r: return if node.l >= l and node.r <= r: node.v = node.r - node.l + 1 node.add = v return self.pushdown(node) if l <= node.mid: self.modify(l, r, v, node.left) if r > node.mid: self.modify(l, r, v, node.right) self.pushup(node) def query(self, l, r, node=None): if node is None: node = self.root if l > r: return 0 if node.l >= l and node.r <= r: return node.v self.pushdown(node) v = 0 if l <= node.mid: v += self.query(l, r, node.left) if r > node.mid: v += self.query(l, r, node.right) return v def pushup(self, node): node.v = node.left.v + node.right.v def pushdown(self, node): if node.left is None: node.left = Node(node.l, node.mid) if node.right is None: node.right = Node(node.mid + 1, node.r) if node.add != 0: left, right = node.left, node.right left.add = node.add right.add = node.add left.v = left.r - left.l + 1 right.v = right.r - right.l + 1 node.add = 0 class CountIntervals: def __init__(self): self.tree = SegmentTree() def add(self, left, right): self.tree.modify(left, right, 1) def count(self): return self.tree.query(1, int(1e9)) # Your CountIntervals object will be instantiated and called as such: # obj = CountIntervals() # obj.add(left, right) # param_2 = obj.count()
null
null
null
null
null
class CountIntervals { left: null | CountIntervals; right: null | CountIntervals; start: number; end: number; sum: number; constructor(start: number = 0, end: number = 10 ** 9) { this.left = null; this.right = null; this.start = start; this.end = end; this.sum = 0; } add(left: number, right: number): void { if (this.sum == this.end - this.start + 1) return; if (left <= this.start && right >= this.end) { this.sum = this.end - this.start + 1; return; } let mid = (this.start + this.end) >> 1; if (!this.left) this.left = new CountIntervals(this.start, mid); if (!this.right) this.right = new CountIntervals(mid + 1, this.end); if (left <= mid) this.left.add(left, right); if (right > mid) this.right.add(left, right); this.sum = this.left.sum + this.right.sum; } count(): number { return this.sum; } } /** * Your CountIntervals object will be instantiated and called as such: * var obj = new CountIntervals() * obj.add(left,right) * var param_2 = obj.count() */
Delete Columns to Make Sorted
You are given an array of n strings strs , all of the same length. The strings can be arranged such that there is one on each line, making a grid. For example, strs = ["abc", "bce", "cae"] can be arranged as follows: abc bce cae You want to delete the columns that are not sorted lexicographically . In the above example ( 0-indexed ), columns 0 ( 'a' , 'b' , 'c' ) and 2 ( 'c' , 'e' , 'e' ) are sorted, while column 1 ( 'b' , 'c' , 'a' ) is not, so you would delete column 1. Return the number of columns that you will delete .   Example 1: Input: strs = ["cba","daf","ghi"] Output: 1 Explanation: The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. Example 2: Input: strs = ["a","b"] Output: 0 Explanation: The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. Example 3: Input: strs = ["zyx","wvu","tsr"] Output: 3 Explanation: The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3.   Constraints: n == strs.length 1 <= n <= 100 1 <= strs[i].length <= 1000 strs[i] consists of lowercase English letters.
null
null
class Solution { public: int minDeletionSize(vector<string>& strs) { int m = strs[0].size(), n = strs.size(); int ans = 0; for (int j = 0; j < m; ++j) { for (int i = 1; i < n; ++i) { if (strs[i][j] < strs[i - 1][j]) { ++ans; break; } } } return ans; } };
null
null
func minDeletionSize(strs []string) (ans int) { m, n := len(strs[0]), len(strs) for j := 0; j < m; j++ { for i := 1; i < n; i++ { if strs[i][j] < strs[i-1][j] { ans++ break } } } return }
class Solution { public int minDeletionSize(String[] strs) { int m = strs[0].length(), n = strs.length; int ans = 0; for (int j = 0; j < m; ++j) { for (int i = 1; i < n; ++i) { if (strs[i].charAt(j) < strs[i - 1].charAt(j)) { ++ans; break; } } } return ans; } }
null
null
null
null
null
null
class Solution: def minDeletionSize(self, strs: List[str]) -> int: m, n = len(strs[0]), len(strs) ans = 0 for j in range(m): for i in range(1, n): if strs[i][j] < strs[i - 1][j]: ans += 1 break return ans
null
impl Solution { pub fn min_deletion_size(strs: Vec<String>) -> i32 { let n = strs.len(); let m = strs[0].len(); let mut ans = 0; for j in 0..m { for i in 1..n { if strs[i].as_bytes()[j] < strs[i - 1].as_bytes()[j] { ans += 1; break; } } } ans } }
null
null
null
function minDeletionSize(strs: string[]): number { const [m, n] = [strs[0].length, strs.length]; let ans = 0; for (let j = 0; j < m; ++j) { for (let i = 1; i < n; ++i) { if (strs[i][j] < strs[i - 1][j]) { ++ans; break; } } } return ans; }
Binary Subarrays With Sum
Given a binary array nums and an integer goal , return the number of non-empty subarrays with a sum goal . A subarray is a contiguous part of the array.   Example 1: Input: nums = [1,0,1,0,1], goal = 2 Output: 4 Explanation: The 4 subarrays are bolded and underlined below: [ 1,0,1 ,0,1] [ 1,0,1,0 ,1] [1, 0,1,0,1 ] [1,0, 1,0,1 ] Example 2: Input: nums = [0,0,0,0,0], goal = 0 Output: 15   Constraints: 1 <= nums.length <= 3 * 10 4 nums[i] is either 0 or 1 . 0 <= goal <= nums.length
null
null
class Solution { public: int numSubarraysWithSum(vector<int>& nums, int goal) { int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; int n = nums.size(); while (j < n) { s1 += nums[j]; s2 += nums[j]; while (i1 <= j && s1 > goal) s1 -= nums[i1++]; while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; ans += i2 - i1; ++j; } return ans; } };
null
null
func numSubarraysWithSum(nums []int, goal int) int { i1, i2, s1, s2, j, ans, n := 0, 0, 0, 0, 0, 0, len(nums) for j < n { s1 += nums[j] s2 += nums[j] for i1 <= j && s1 > goal { s1 -= nums[i1] i1++ } for i2 <= j && s2 >= goal { s2 -= nums[i2] i2++ } ans += i2 - i1 j++ } return ans }
class Solution { public int numSubarraysWithSum(int[] nums, int goal) { int i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; int n = nums.length; while (j < n) { s1 += nums[j]; s2 += nums[j]; while (i1 <= j && s1 > goal) { s1 -= nums[i1++]; } while (i2 <= j && s2 >= goal) { s2 -= nums[i2++]; } ans += i2 - i1; ++j; } return ans; } }
/** * @param {number[]} nums * @param {number} goal * @return {number} */ var numSubarraysWithSum = function (nums, goal) { let i1 = 0, i2 = 0, s1 = 0, s2 = 0, j = 0, ans = 0; const n = nums.length; while (j < n) { s1 += nums[j]; s2 += nums[j]; while (i1 <= j && s1 > goal) s1 -= nums[i1++]; while (i2 <= j && s2 >= goal) s2 -= nums[i2++]; ans += i2 - i1; ++j; } return ans; };
null
null
null
null
null
class Solution: def numSubarraysWithSum(self, nums: List[int], goal: int) -> int: i1 = i2 = s1 = s2 = j = ans = 0 n = len(nums) while j < n: s1 += nums[j] s2 += nums[j] while i1 <= j and s1 > goal: s1 -= nums[i1] i1 += 1 while i2 <= j and s2 >= goal: s2 -= nums[i2] i2 += 1 ans += i2 - i1 j += 1 return ans
null
null
null
null
null
null
Shortest Word Distance 🔒
Given an array of strings wordsDict and two different strings that already exist in the array word1 and word2 , return the shortest distance between these two words in the list .   Example 1: Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice" Output: 3 Example 2: Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding" Output: 1   Constraints: 2 <= wordsDict.length <= 3 * 10 4 1 <= wordsDict[i].length <= 10 wordsDict[i] consists of lowercase English letters. word1 and word2 are in wordsDict . word1 != word2
null
null
class Solution { public: int shortestDistance(vector<string>& wordsDict, string word1, string word2) { int ans = INT_MAX; for (int k = 0, i = -1, j = -1; k < wordsDict.size(); ++k) { if (wordsDict[k] == word1) { i = k; } if (wordsDict[k] == word2) { j = k; } if (i != -1 && j != -1) { ans = min(ans, abs(i - j)); } } return ans; } };
null
null
func shortestDistance(wordsDict []string, word1 string, word2 string) int { ans := 0x3f3f3f3f i, j := -1, -1 for k, w := range wordsDict { if w == word1 { i = k } if w == word2 { j = k } if i != -1 && j != -1 { ans = min(ans, abs(i-j)) } } return ans } func abs(x int) int { if x < 0 { return -x } return x }
class Solution { public int shortestDistance(String[] wordsDict, String word1, String word2) { int ans = 0x3f3f3f3f; for (int k = 0, i = -1, j = -1; k < wordsDict.length; ++k) { if (wordsDict[k].equals(word1)) { i = k; } if (wordsDict[k].equals(word2)) { j = k; } if (i != -1 && j != -1) { ans = Math.min(ans, Math.abs(i - j)); } } return ans; } }
null
null
null
null
null
null
class Solution: def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int: i = j = -1 ans = inf for k, w in enumerate(wordsDict): if w == word1: i = k if w == word2: j = k if i != -1 and j != -1: ans = min(ans, abs(i - j)) return ans
null
null
null
null
null
null
Find the K-or of an Array
You are given an integer array nums , and an integer k . Let's introduce  K-or operation by extending the standard bitwise OR. In K-or, a bit position in the result is set to 1  if at least k numbers in nums have a 1 in that position. Return the K-or of nums .   Example 1: Input: nums = [7,12,9,8,9,15], k = 4 Output: 9 Explanation: Represent numbers in binary: Number Bit 3 Bit 2 Bit 1 Bit 0 7 0 1 1 1 12 1 1 0 0 9 1 0 0 1 8 1 0 0 0 9 1 0 0 1 15 1 1 1 1 Result = 9 1 0 0 1 Bit 0 is set in 7, 9, 9, and 15. Bit 3 is set in 12, 9, 8, 9, and 15. Only bits 0 and 3 qualify. The result is (1001) 2 = 9 . Example 2: Input: nums = [2,12,1,11,4,5], k = 6 Output: 0 Explanation:  No bit appears as 1 in all six array numbers, as required for K-or with k = 6 . Thus, the result is 0. Example 3: Input: nums = [10,8,5,9,11,6,8], k = 1 Output: 15 Explanation: Since k == 1 , the 1-or of the array is equal to the bitwise OR of all its elements. Hence, the answer is 10 OR 8 OR 5 OR 9 OR 11 OR 6 OR 8 = 15 .   Constraints: 1 <= nums.length <= 50 0 <= nums[i] < 2 31 1 <= k <= nums.length
null
public class Solution { public int FindKOr(int[] nums, int k) { int ans = 0; for (int i = 0; i < 32; ++i) { int cnt = 0; foreach (int x in nums) { cnt += (x >> i & 1); } if (cnt >= k) { ans |= 1 << i; } } return ans; } }
class Solution { public: int findKOr(vector<int>& nums, int k) { int ans = 0; for (int i = 0; i < 32; ++i) { int cnt = 0; for (int x : nums) { cnt += (x >> i & 1); } if (cnt >= k) { ans |= 1 << i; } } return ans; } };
null
null
func findKOr(nums []int, k int) (ans int) { for i := 0; i < 32; i++ { cnt := 0 for _, x := range nums { cnt += (x >> i & 1) } if cnt >= k { ans |= 1 << i } } return }
class Solution { public int findKOr(int[] nums, int k) { int ans = 0; for (int i = 0; i < 32; ++i) { int cnt = 0; for (int x : nums) { cnt += (x >> i & 1); } if (cnt >= k) { ans |= 1 << i; } } return ans; } }
null
null
null
null
null
null
class Solution: def findKOr(self, nums: List[int], k: int) -> int: ans = 0 for i in range(32): cnt = sum(x >> i & 1 for x in nums) if cnt >= k: ans |= 1 << i return ans
null
null
null
null
null
function findKOr(nums: number[], k: number): number { let ans = 0; for (let i = 0; i < 32; ++i) { let cnt = 0; for (const x of nums) { cnt += (x >> i) & 1; } if (cnt >= k) { ans |= 1 << i; } } return ans; }
Find Sum of Array Product of Magical Sequences
You are given two integers, m and k , and an integer array nums . A sequence of integers seq is called magical if: seq has a size of m . 0 <= seq[i] < nums.length The binary representation of 2 seq[0] + 2 seq[1] + ... + 2 seq[m - 1] has k set bits . The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m - 1]]) . Return the sum of the array products for all valid magical sequences. Since the answer may be large, return it modulo 10 9 + 7 . A set bit refers to a bit in the binary representation of a number that has a value of 1.   Example 1: Input: m = 5, k = 5, nums = [1,10,100,10000,1000000] Output: 991600007 Explanation: All permutations of [0, 1, 2, 3, 4] are magical sequences, each with an array product of 10 13 . Example 2: Input: m = 2, k = 2, nums = [5,4,3,2,1] Output: 170 Explanation: The magical sequences are [0, 1] , [0, 2] , [0, 3] , [0, 4] , [1, 0] , [1, 2] , [1, 3] , [1, 4] , [2, 0] , [2, 1] , [2, 3] , [2, 4] , [3, 0] , [3, 1] , [3, 2] , [3, 4] , [4, 0] , [4, 1] , [4, 2] , and [4, 3] . Example 3: Input: m = 1, k = 1, nums = [28] Output: 28 Explanation: The only magical sequence is [0] .   Constraints: 1 <= k <= m <= 30 1 <= nums.length <= 50 1 <= nums[i] <= 10 8
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
null
Jump Game V
Given an array of integers arr and an integer d . In one step you can jump from index i to index: i + x where:  i + x < arr.length and 0 < x <= d . i - x where:  i - x >= 0 and 0 < x <= d . In addition, you can only jump from index i to index j  if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j) ). You can choose any index of the array and start jumping. Return the maximum number of indices  you can visit. Notice that you can not jump outside of the array at any time.   Example 1: Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 Output: 4 Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown. Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9. Similarly You cannot jump from index 3 to index 2 or index 1. Example 2: Input: arr = [3,3,3,3,3], d = 3 Output: 1 Explanation: You can start at any index. You always cannot jump to any index. Example 3: Input: arr = [7,6,5,4,3,2,1], d = 1 Output: 7 Explanation: Start at index 0. You can visit all the indicies.   Constraints: 1 <= arr.length <= 1000 1 <= arr[i] <= 10 5 1 <= d <= arr.length
null
null
class Solution { public: int maxJumps(vector<int>& arr, int d) { int n = arr.size(); vector<int> idx(n); iota(idx.begin(), idx.end(), 0); sort(idx.begin(), idx.end(), [&](int i, int j) { return arr[i] < arr[j]; }); vector<int> f(n, 1); for (int i : idx) { for (int j = i - 1; j >= 0; --j) { if (i - j > d || arr[j] >= arr[i]) { break; } f[i] = max(f[i], 1 + f[j]); } for (int j = i + 1; j < n; ++j) { if (j - i > d || arr[j] >= arr[i]) { break; } f[i] = max(f[i], 1 + f[j]); } } return *max_element(f.begin(), f.end()); } };
null
null
func maxJumps(arr []int, d int) int { n := len(arr) idx := make([]int, n) f := make([]int, n) for i := range f { idx[i] = i f[i] = 1 } sort.Slice(idx, func(i, j int) bool { return arr[idx[i]] < arr[idx[j]] }) for _, i := range idx { for j := i - 1; j >= 0; j-- { if i-j > d || arr[j] >= arr[i] { break } f[i] = max(f[i], 1+f[j]) } for j := i + 1; j < n; j++ { if j-i > d || arr[j] >= arr[i] { break } f[i] = max(f[i], 1+f[j]) } } return slices.Max(f) }
class Solution { public int maxJumps(int[] arr, int d) { int n = arr.length; Integer[] idx = new Integer[n]; Arrays.setAll(idx, i -> i); Arrays.sort(idx, (i, j) -> arr[i] - arr[j]); int[] f = new int[n]; Arrays.fill(f, 1); int ans = 0; for (int i : idx) { for (int j = i - 1; j >= 0; --j) { if (i - j > d || arr[j] >= arr[i]) { break; } f[i] = Math.max(f[i], 1 + f[j]); } for (int j = i + 1; j < n; ++j) { if (j - i > d || arr[j] >= arr[i]) { break; } f[i] = Math.max(f[i], 1 + f[j]); } ans = Math.max(ans, f[i]); } return ans; } }
null
null
null
null
null
null
class Solution: def maxJumps(self, arr: List[int], d: int) -> int: n = len(arr) f = [1] * n for x, i in sorted(zip(arr, range(n))): for j in range(i - 1, -1, -1): if i - j > d or arr[j] >= x: break f[i] = max(f[i], 1 + f[j]) for j in range(i + 1, n): if j - i > d or arr[j] >= x: break f[i] = max(f[i], 1 + f[j]) return max(f)
null
null
null
null
null
null
Check if Number Has Equal Digit Count and Digit Value
You are given a 0-indexed string num of length n consisting of digits. Return true if for every index i in the range 0 <= i < n , the digit i occurs num[i] times in num , otherwise return false .   Example 1: Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] = '2'. The digit 1 occurs twice in num. num[2] = '1'. The digit 2 occurs once in num. num[3] = '0'. The digit 3 occurs zero times in num. The condition holds true for every index in "1210", so return true. Example 2: Input: num = "030" Output: false Explanation: num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num. num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num. num[2] = '0'. The digit 2 occurs zero times in num. The indices 0 and 1 both violate the condition, so return false.   Constraints: n == num.length 1 <= n <= 10 num consists of digits.
bool digitCount(char* num) { int cnt[10] = {0}; for (int i = 0; num[i] != '\0'; ++i) { ++cnt[num[i] - '0']; } for (int i = 0; num[i] != '\0'; ++i) { if (cnt[i] != num[i] - '0') { return false; } } return true; }
null
class Solution { public: bool digitCount(string num) { int cnt[10]{}; for (char& c : num) { ++cnt[c - '0']; } for (int i = 0; i < num.size(); ++i) { if (cnt[i] != num[i] - '0') { return false; } } return true; } };
null
null
func digitCount(num string) bool { cnt := [10]int{} for _, c := range num { cnt[c-'0']++ } for i, c := range num { if int(c-'0') != cnt[i] { return false } } return true }
class Solution { public boolean digitCount(String num) { int[] cnt = new int[10]; int n = num.length(); for (int i = 0; i < n; ++i) { ++cnt[num.charAt(i) - '0']; } for (int i = 0; i < n; ++i) { if (num.charAt(i) - '0' != cnt[i]) { return false; } } return true; } }
null
null
null
null
null
null
class Solution: def digitCount(self, num: str) -> bool: cnt = Counter(int(x) for x in num) return all(cnt[i] == int(x) for i, x in enumerate(num))
null
impl Solution { pub fn digit_count(num: String) -> bool { let mut cnt = vec![0; 10]; for c in num.chars() { let x = c.to_digit(10).unwrap() as usize; cnt[x] += 1; } for (i, c) in num.chars().enumerate() { let x = c.to_digit(10).unwrap() as usize; if cnt[i] != x { return false; } } true } }
null
null
null
function digitCount(num: string): boolean { const cnt: number[] = Array(10).fill(0); for (const c of num) { ++cnt[+c]; } for (let i = 0; i < num.length; ++i) { if (cnt[i] !== +num[i]) { return false; } } return true; }
Design Tic-Tac-Toe 🔒
Assume the following rules are for the tic-tac-toe game on an n x n board between two players: A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves are allowed. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game. Implement the TicTacToe class: TicTacToe(int n) Initializes the object the size of the board n . int move(int row, int col, int player) Indicates that the player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return 0 if there is no winner after the move, 1 if player 1 is the winner after the move, or 2 if player 2 is the winner after the move.   Example 1: Input ["TicTacToe", "move", "move", "move", "move", "move", "move", "move"] [[3], [0, 0, 1], [0, 2, 2], [2, 2, 1], [1, 1, 2], [2, 0, 1], [1, 0, 2], [2, 1, 1]] Output [null, 0, 0, 0, 0, 0, 0, 1] Explanation TicTacToe ticTacToe = new TicTacToe(3); Assume that player 1 is "X" and player 2 is "O" in the board. ticTacToe.move(0, 0, 1); // return 0 (no one wins) |X| | | | | | | // Player 1 makes a move at (0, 0). | | | | ticTacToe.move(0, 2, 2); // return 0 (no one wins) |X| |O| | | | | // Player 2 makes a move at (0, 2). | | | | ticTacToe.move(2, 2, 1); // return 0 (no one wins) |X| |O| | | | | // Player 1 makes a move at (2, 2). | | |X| ticTacToe.move(1, 1, 2); // return 0 (no one wins) |X| |O| | |O| | // Player 2 makes a move at (1, 1). | | |X| ticTacToe.move(2, 0, 1); // return 0 (no one wins) |X| |O| | |O| | // Player 1 makes a move at (2, 0). |X| |X| ticTacToe.move(1, 0, 2); // return 0 (no one wins) |X| |O| |O|O| | // Player 2 makes a move at (1, 0). |X| |X| ticTacToe.move(2, 1, 1); // return 1 (player 1 wins) |X| |O| |O|O| | // Player 1 makes a move at (2, 1). |X|X|X|   Constraints: 2 <= n <= 100 player is 1 or 2 . 0 <= row, col < n (row, col) are unique for each different call to move . At most n 2 calls will be made to move .   Follow-up: Could you do better than O(n 2 ) per move() operation?
null
null
class TicTacToe { private: int n; vector<vector<int>> cnt; public: TicTacToe(int n) : n(n) , cnt(2, vector<int>((n << 1) + 2, 0)) { } int move(int row, int col, int player) { vector<int>& cur = cnt[player - 1]; ++cur[row]; ++cur[n + col]; if (row == col) { ++cur[n << 1]; } if (row + col == n - 1) { ++cur[n << 1 | 1]; } if (cur[row] == n || cur[n + col] == n || cur[n << 1] == n || cur[n << 1 | 1] == n) { return player; } return 0; } }; /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe* obj = new TicTacToe(n); * int param_1 = obj->move(row,col,player); */
null
null
type TicTacToe struct { n int cnt [][]int } func Constructor(n int) TicTacToe { cnt := make([][]int, 2) for i := range cnt { cnt[i] = make([]int, (n<<1)+2) } return TicTacToe{n, cnt} } func (this *TicTacToe) Move(row int, col int, player int) int { cur := this.cnt[player-1] cur[row]++ cur[this.n+col]++ if row == col { cur[this.n<<1]++ } if row+col == this.n-1 { cur[this.n<<1|1]++ } if cur[row] == this.n || cur[this.n+col] == this.n || cur[this.n<<1] == this.n || cur[this.n<<1|1] == this.n { return player } return 0 } /** * Your TicTacToe object will be instantiated and called as such: * obj := Constructor(n); * param_1 := obj.Move(row,col,player); */
class TicTacToe { private int n; private int[][] cnt; public TicTacToe(int n) { this.n = n; cnt = new int[2][(n << 1) + 2]; } public int move(int row, int col, int player) { int[] cur = cnt[player - 1]; ++cur[row]; ++cur[n + col]; if (row == col) { ++cur[n << 1]; } if (row + col == n - 1) { ++cur[n << 1 | 1]; } if (cur[row] == n || cur[n + col] == n || cur[n << 1] == n || cur[n << 1 | 1] == n) { return player; } return 0; } } /** * Your TicTacToe object will be instantiated and called as such: * TicTacToe obj = new TicTacToe(n); * int param_1 = obj.move(row,col,player); */
null
null
null
null
null
null
class TicTacToe: def __init__(self, n: int): self.n = n self.cnt = [defaultdict(int), defaultdict(int)] def move(self, row: int, col: int, player: int) -> int: cur = self.cnt[player - 1] n = self.n cur[row] += 1 cur[n + col] += 1 if row == col: cur[n << 1] += 1 if row + col == n - 1: cur[n << 1 | 1] += 1 if any(cur[i] == n for i in (row, n + col, n << 1, n << 1 | 1)): return player return 0 # Your TicTacToe object will be instantiated and called as such: # obj = TicTacToe(n) # param_1 = obj.move(row,col,player)
null
null
null
null
null
class TicTacToe { private n: number; private cnt: number[][]; constructor(n: number) { this.n = n; this.cnt = [Array((n << 1) + 2).fill(0), Array((n << 1) + 2).fill(0)]; } move(row: number, col: number, player: number): number { const cur = this.cnt[player - 1]; cur[row]++; cur[this.n + col]++; if (row === col) { cur[this.n << 1]++; } if (row + col === this.n - 1) { cur[(this.n << 1) | 1]++; } if ( cur[row] === this.n || cur[this.n + col] === this.n || cur[this.n << 1] === this.n || cur[(this.n << 1) | 1] === this.n ) { return player; } return 0; } } /** * Your TicTacToe object will be instantiated and called as such: * var obj = new TicTacToe(n) * var param_1 = obj.move(row,col,player) */
Find the Sum of Encrypted Integers
You are given an integer array nums containing positive integers. We define a function encrypt such that encrypt(x) replaces every digit in x with the largest digit in x . For example, encrypt(523) = 555 and encrypt(213) = 333 . Return the sum of encrypted elements .   Example 1: Input: nums = [1,2,3] Output: 6 Explanation: The encrypted elements are  [1,2,3] . The sum of encrypted elements is 1 + 2 + 3 == 6 . Example 2: Input: nums = [10,21,31] Output: 66 Explanation: The encrypted elements are [11,22,33] . The sum of encrypted elements is 11 + 22 + 33 == 66 .   Constraints: 1 <= nums.length <= 50 1 <= nums[i] <= 1000
null
null
class Solution { public: int sumOfEncryptedInt(vector<int>& nums) { auto encrypt = [&](int x) { int mx = 0, p = 0; for (; x; x /= 10) { mx = max(mx, x % 10); p = p * 10 + 1; } return mx * p; }; int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } };
null
null
func sumOfEncryptedInt(nums []int) (ans int) { encrypt := func(x int) int { mx, p := 0, 0 for ; x > 0; x /= 10 { mx = max(mx, x%10) p = p*10 + 1 } return mx * p } for _, x := range nums { ans += encrypt(x) } return }
class Solution { public int sumOfEncryptedInt(int[] nums) { int ans = 0; for (int x : nums) { ans += encrypt(x); } return ans; } private int encrypt(int x) { int mx = 0, p = 0; for (; x > 0; x /= 10) { mx = Math.max(mx, x % 10); p = p * 10 + 1; } return mx * p; } }
null
null
null
null
null
null
class Solution: def sumOfEncryptedInt(self, nums: List[int]) -> int: def encrypt(x: int) -> int: mx = p = 0 while x: x, v = divmod(x, 10) mx = max(mx, v) p = p * 10 + 1 return mx * p return sum(encrypt(x) for x in nums)
null
null
null
null
null
function sumOfEncryptedInt(nums: number[]): number { const encrypt = (x: number): number => { let [mx, p] = [0, 0]; for (; x > 0; x = Math.floor(x / 10)) { mx = Math.max(mx, x % 10); p = p * 10 + 1; } return mx * p; }; return nums.reduce((acc, x) => acc + encrypt(x), 0); }
Maximum Matrix Sum
You are given an n x n integer matrix . You can do the following operation any number of times: Choose any two adjacent elements of matrix and multiply each of them by -1 . Two elements are considered adjacent if and only if they share a border . Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.   Example 1: Input: matrix = [[1,-1],[-1,1]] Output: 4 Explanation: We can follow the following steps to reach sum equals 4: - Multiply the 2 elements in the first row by -1. - Multiply the 2 elements in the first column by -1. Example 2: Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]] Output: 16 Explanation: We can follow the following step to reach sum equals 16: - Multiply the 2 last elements in the second row by -1.   Constraints: n == matrix.length == matrix[i].length 2 <= n <= 250 -10 5 <= matrix[i][j] <= 10 5
null
null
class Solution { public: long long maxMatrixSum(vector<vector<int>>& matrix) { long long s = 0; int mi = 1 << 30, cnt = 0; for (const auto& row : matrix) { for (int x : row) { cnt += x < 0 ? 1 : 0; int y = abs(x); mi = min(mi, y); s += y; } } return cnt % 2 == 0 ? s : s - mi * 2; } };
null
null
func maxMatrixSum(matrix [][]int) int64 { var s int64 mi, cnt := 1<<30, 0 for _, row := range matrix { for _, x := range row { if x < 0 { cnt++ x = -x } mi = min(mi, x) s += int64(x) } } if cnt%2 == 0 { return s } return s - int64(mi*2) }
class Solution { public long maxMatrixSum(int[][] matrix) { long s = 0; int mi = 1 << 30, cnt = 0; for (var row : matrix) { for (int x : row) { cnt += x < 0 ? 1 : 0; int y = Math.abs(x); mi = Math.min(mi, y); s += y; } } return cnt % 2 == 0 ? s : s - mi * 2; } }
/** * @param {number[][]} matrix * @return {number} */ var maxMatrixSum = function (matrix) { let [s, cnt, mi] = [0, 0, Infinity]; for (const row of matrix) { for (const x of row) { if (x < 0) { ++cnt; } const y = Math.abs(x); s += y; mi = Math.min(mi, y); } } return cnt % 2 === 0 ? s : s - 2 * mi; };
null
null
null
null
null
class Solution: def maxMatrixSum(self, matrix: List[List[int]]) -> int: mi = inf s = cnt = 0 for row in matrix: for x in row: cnt += x < 0 y = abs(x) mi = min(mi, y) s += y return s if cnt % 2 == 0 else s - mi * 2
null
impl Solution { pub fn max_matrix_sum(matrix: Vec<Vec<i32>>) -> i64 { let mut s = 0; let mut mi = i32::MAX; let mut cnt = 0; for row in matrix { for &x in row.iter() { cnt += if x < 0 { 1 } else { 0 }; let y = x.abs(); mi = mi.min(y); s += y as i64; } } if cnt % 2 == 0 { s } else { s - (mi as i64 * 2) } } }
null
null
null
function maxMatrixSum(matrix: number[][]): number { let [s, cnt, mi] = [0, 0, Infinity]; for (const row of matrix) { for (const x of row) { if (x < 0) { ++cnt; } const y = Math.abs(x); s += y; mi = Math.min(mi, y); } } return cnt % 2 === 0 ? s : s - 2 * mi; }
Change Null Values in a Table to the Previous Value 🔒
Table: CoffeeShop +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | drink | varchar | +-------------+---------+ id is the primary key (column with unique values) for this table. Each row in this table shows the order id and the name of the drink ordered. Some drink rows are nulls.   Write a solution to replace the null values of the drink with the name of the drink of the previous row that is not null . It is guaranteed that the drink on the first row of the table is not null . Return the result table in the same order as the input . The result format is shown in the following example.   Example 1: Input: CoffeeShop table: +----+-------------------+ | id | drink | +----+-------------------+ | 9 | Rum and Coke | | 6 | null | | 7 | null | | 3 | St Germain Spritz | | 1 | Orange Margarita | | 2 | null | +----+-------------------+ Output: +----+-------------------+ | id | drink | +----+-------------------+ | 9 | Rum and Coke | | 6 | Rum and Coke | | 7 | Rum and Coke | | 3 | St Germain Spritz | | 1 | Orange Margarita | | 2 | Orange Margarita | +----+-------------------+ Explanation: For ID 6, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke". For ID 7, the previous value that is not null is from ID 9. We replace the null with "Rum and Coke;. For ID 2, the previous value that is not null is from ID 1. We replace the null with "Orange Margarita". Note that the rows in the output are the same as in the input.
null
null
null
null
null
null
null
null
null
# Write your MySQL query statement below WITH S AS ( SELECT *, ROW_NUMBER() OVER () AS rk FROM CoffeeShop ), T AS ( SELECT *, SUM( CASE WHEN drink IS NULL THEN 0 ELSE 1 END ) OVER (ORDER BY rk) AS gid FROM S ) SELECT id, MAX(drink) OVER ( PARTITION BY gid ORDER BY rk ) AS drink FROM T;
null
null
null
null
null
null
null
null
null
null