"function knapsack(weights, values, cap) {
const indicesByValue = Object.keys(weights).map(weight => parseInt(weight));
indicesByValue.sort((a, b) => values[b]-values[a]);
const steps = new Map();
function knapsackStep(cap, sack) {
if (steps.has(sack)) {
return steps.get(sack);
}
let maxOutput = 0;
for (let index of indicesByValue) {
if (!sack.has(index) && weights[index] <= cap) {
maxOutput ="
Tiago R. - "function knapsack(weights, values, cap) {
const indicesByValue = Object.keys(weights).map(weight => parseInt(weight));
indicesByValue.sort((a, b) => values[b]-values[a]);
const steps = new Map();
function knapsackStep(cap, sack) {
if (steps.has(sack)) {
return steps.get(sack);
}
let maxOutput = 0;
for (let index of indicesByValue) {
if (!sack.has(index) && weights[index] <= cap) {
maxOutput ="See full answer
"with t1 as (select
employee_name,
department_id,
salary,
avg(salary) over (partition by departmentid) as avgsalary,
abs(salary - avg(salary) over (partition by department_id)) as diff
from employees
)
select
employee_name,
department_id,
salary,
avg_salary,
denserank() over (partition by departmentid order by diff desc) as deviation_rank
from t1
order by departmentid asc, deviationrank asc, employee_name
`"
Alexey T. - "with t1 as (select
employee_name,
department_id,
salary,
avg(salary) over (partition by departmentid) as avgsalary,
abs(salary - avg(salary) over (partition by department_id)) as diff
from employees
)
select
employee_name,
department_id,
salary,
avg_salary,
denserank() over (partition by departmentid order by diff desc) as deviation_rank
from t1
order by departmentid asc, deviationrank asc, employee_name
`"See full answer
"
from typing import Optional
class Node:
def init(self, val: int, prev: Optional['Node'] = None, next: Optional['Node'] = None):
self.val = val
self.prev = prev
self.next = next
def split(head):
if not head or not head.next:
return head
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
if mid:
mid.prev = None
"
Akash C. - "
from typing import Optional
class Node:
def init(self, val: int, prev: Optional['Node'] = None, next: Optional['Node'] = None):
self.val = val
self.prev = prev
self.next = next
def split(head):
if not head or not head.next:
return head
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
if mid:
mid.prev = None
"See full answer
Coding
Data Structures & Algorithms
+1 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"Implemented the Java code to find the largest island. It is similar to count the island. But in this we need to keep track of max island and compute its perimeter."
Techzen I. - "Implemented the Java code to find the largest island. It is similar to count the island. But in this we need to keep track of max island and compute its perimeter."See full answer
"function spiralCopy(inputMatrix) {
if (inputMatrix.length === 1) return inputMatrix[0];
let lowerY = 0;
let upperY = inputMatrix.length-1;
let lowerX = 0;
let upperX = inputMatrix[0].length-1;
const output = [];
while (true) {
if (lowerX > upperX) break;
for (let x = lowerX; x upperY) break;
for (let y = lowerY; y <= upperY; y++) {
output.push(inputMatrix[y][u"
Tiago R. - "function spiralCopy(inputMatrix) {
if (inputMatrix.length === 1) return inputMatrix[0];
let lowerY = 0;
let upperY = inputMatrix.length-1;
let lowerX = 0;
let upperX = inputMatrix[0].length-1;
const output = [];
while (true) {
if (lowerX > upperX) break;
for (let x = lowerX; x upperY) break;
for (let y = lowerY; y <= upperY; y++) {
output.push(inputMatrix[y][u"See full answer
"not sure what's wrong here>
select
a.marketing_channel,
avg(purchasevalue) as avgpurchase_value,
sum(case when a.purchasevalue > 0 then 1 else 0 end) * 1.0 /count(a.sessionid) as conversion_rate
from attribution a
left join usersessions u on a.sessionid = u.session_id
group by a.marketing_channel
order by conversion_rate desc
`"
Shriganesh K. - "not sure what's wrong here>
select
a.marketing_channel,
avg(purchasevalue) as avgpurchase_value,
sum(case when a.purchasevalue > 0 then 1 else 0 end) * 1.0 /count(a.sessionid) as conversion_rate
from attribution a
left join usersessions u on a.sessionid = u.session_id
group by a.marketing_channel
order by conversion_rate desc
`"See full answer
"A red-black tree is a self-balancing binary search tree. The motivation for this is that the benefits of O(logN) search, insertion, and deletion that a binary tree provides us will disappear if we let the tree get too "imbalanced" (e.g. there are too many nodes on one side of the tree or some branches have a depth that is way out of proportion to the average branch depth). This imbalance will occur if we don't adjust the tree after inserting or deleting nodes, hence our need for self-balancing c"
Alex M. - "A red-black tree is a self-balancing binary search tree. The motivation for this is that the benefits of O(logN) search, insertion, and deletion that a binary tree provides us will disappear if we let the tree get too "imbalanced" (e.g. there are too many nodes on one side of the tree or some branches have a depth that is way out of proportion to the average branch depth). This imbalance will occur if we don't adjust the tree after inserting or deleting nodes, hence our need for self-balancing c"See full answer
"My solution is simple; it does an in-order DFS traversal to create an array of in-order elements then it searches through the array to find the node we want the successor of. finally we return the node that is 1 after the input node, in the case our input node is the last element of our DFS we know there is no successor, therefore it returns None/null.
CODE INSTRUCTIONS:
1) The method fi"
Rohan M. - "My solution is simple; it does an in-order DFS traversal to create an array of in-order elements then it searches through the array to find the node we want the successor of. finally we return the node that is 1 after the input node, in the case our input node is the last element of our DFS we know there is no successor, therefore it returns None/null.
CODE INSTRUCTIONS:
1) The method fi"See full answer
"SELECT u.id as user_id, u.name,
COUNT(t.product_id) AS orders
FROM users u
JOIN transactions t
ON
t.user_id = u.id
JOIN products p
ON
p.id = t.product_id
GROUP BY u.id, u.name
ORDER BY orders DESC
LIMIT 1
`"
Derrick M. - "SELECT u.id as user_id, u.name,
COUNT(t.product_id) AS orders
FROM users u
JOIN transactions t
ON
t.user_id = u.id
JOIN products p
ON
p.id = t.product_id
GROUP BY u.id, u.name
ORDER BY orders DESC
LIMIT 1
`"See full answer
"bool isValidBST(TreeNode* root, long min = LONGMIN, long max = LONGMAX){
if (root == NULL)
return true;
if (root->val val >= max)
return false;
return isValidBST(root->left, min, root->val) &&
isValidBST(root->right, root->val, max);
}
`"
Alvaro R. - "bool isValidBST(TreeNode* root, long min = LONGMIN, long max = LONGMAX){
if (root == NULL)
return true;
if (root->val val >= max)
return false;
return isValidBST(root->left, min, root->val) &&
isValidBST(root->right, root->val, max);
}
`"See full answer
"Not my answer, but rather the details of this question. It should include the following functions:
int insertNewCustomer(double revenue) -> returns a customer ID (assume auto-incremented & 0-based)
int insertNewCustomer(double revenue, int referrerID) -> returns a customer ID (assume auto-incremented & 0-based)
Set getLowestKCustomersByMinTotalRevenue(int k, double minTotalRevenue) -> returns customer IDs
Note: The total revenue consists of the revenue that this customer bring"
Anzhe M. - "Not my answer, but rather the details of this question. It should include the following functions:
int insertNewCustomer(double revenue) -> returns a customer ID (assume auto-incremented & 0-based)
int insertNewCustomer(double revenue, int referrerID) -> returns a customer ID (assume auto-incremented & 0-based)
Set getLowestKCustomersByMinTotalRevenue(int k, double minTotalRevenue) -> returns customer IDs
Note: The total revenue consists of the revenue that this customer bring"See full answer
"WITH logins AS(SELECT
user_id,
timestamp,
RANK() OVER(PARTITION BY userid ORDER BY timestamp ASC) AS loginorder
FROM useractivitylog
WHERE activity_type = 'LOGIN')
SELECT
l1.user_id,
l1.timestamp AS current_login,
l2.timestamp AS previous_login,
(strftime('%s', l1.timestamp) - strftime('%s', l2.timestamp)) / 60 AS minutes_elapsed
FROM logins AS l1
JOIN logins AS l2
ON l1.userid = l2.userid
AND l1.loginorder - l2.loginorder = 1
GROUP BY l1.user_id,"
Alvin P. - "WITH logins AS(SELECT
user_id,
timestamp,
RANK() OVER(PARTITION BY userid ORDER BY timestamp ASC) AS loginorder
FROM useractivitylog
WHERE activity_type = 'LOGIN')
SELECT
l1.user_id,
l1.timestamp AS current_login,
l2.timestamp AS previous_login,
(strftime('%s', l1.timestamp) - strftime('%s', l2.timestamp)) / 60 AS minutes_elapsed
FROM logins AS l1
JOIN logins AS l2
ON l1.userid = l2.userid
AND l1.loginorder - l2.loginorder = 1
GROUP BY l1.user_id,"See full answer
"This could be done using two-pointer approach assuming array is sorted: left and right pointers. We need track two sums (left and right) as we move pointers. For moving pointers we will move left to right by 1 (increment) when right sum is greater. We will move right pointer to left by 1 (decrement) when left sum is greater. at some point we will either get the sum same and that's when we exit from the loop. 0-left will be one array and right-(n-1) will be another array.
We are not going to mo"
Bhaskar B. - "This could be done using two-pointer approach assuming array is sorted: left and right pointers. We need track two sums (left and right) as we move pointers. For moving pointers we will move left to right by 1 (increment) when right sum is greater. We will move right pointer to left by 1 (decrement) when left sum is greater. at some point we will either get the sum same and that's when we exit from the loop. 0-left will be one array and right-(n-1) will be another array.
We are not going to mo"See full answer
"Example:
bucket A: 3 liters capacity
bucket B: 5 liters capacity
goal: 4 liters
You are asked to print the logical sequence to get to the 4 liters of water in one bucket.
Follow up:
How would you solve the problem if you have more than 2 buckets of water?"
B. T. - "Example:
bucket A: 3 liters capacity
bucket B: 5 liters capacity
goal: 4 liters
You are asked to print the logical sequence to get to the 4 liters of water in one bucket.
Follow up:
How would you solve the problem if you have more than 2 buckets of water?"See full answer