"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
"This problem can be solved with two approaches
Iterative approach
Recursive approach
Quite easy to think about the iterative approach, you can make use of a while loop in that case. But what if you want to make use of previously computed values? That case going for the recursive solution is quite useful.
class Collatz:
def init(self) -> None:
self.cache = {}
self.steps = 0
def steps_from(self, n) -> int:
# base case
if n == 1:
"
Frederick A. - "This problem can be solved with two approaches
Iterative approach
Recursive approach
Quite easy to think about the iterative approach, you can make use of a while loop in that case. But what if you want to make use of previously computed values? That case going for the recursive solution is quite useful.
class Collatz:
def init(self) -> None:
self.cache = {}
self.steps = 0
def steps_from(self, n) -> int:
# base case
if n == 1:
"See full answer
"with login_data as (
select *
from useractivitylog
where activity_type = 'LOGIN'
)
,cte as (
select userid, timestamp as currentlogin
,lag(timestamp,1,timestamp) over (partition by user_id order by timestamp asc)
as previous_login,
round((julianday(timestamp) - julianday(lag(timestamp,1,timestamp) over (partition by user_id order by timestamp asc))) * 24 * 60)
as minutes_elapsed
from login_data
)
select * from cte where currentlogin previouslogin;"
Kedar W. - "with login_data as (
select *
from useractivitylog
where activity_type = 'LOGIN'
)
,cte as (
select userid, timestamp as currentlogin
,lag(timestamp,1,timestamp) over (partition by user_id order by timestamp asc)
as previous_login,
round((julianday(timestamp) - julianday(lag(timestamp,1,timestamp) over (partition by user_id order by timestamp asc))) * 24 * 60)
as minutes_elapsed
from login_data
)
select * from cte where currentlogin previouslogin;"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
Coding
Data Structures & Algorithms
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"SELECT
a.marketing_channel,
AVG(a.purchasevalue) AS avgpurchase_value,
SUM(CASE WHEN a.purchasevalue > 0 THEN 1 ELSE 0 END) * 100 / COUNT(a.sessionid) AS conversion_rate
FROM
attribution a
LEFT JOIN
user_sessions u
ON
a.sessionid = u.sessionid
GROUP BY
a.marketing_channel
ORDER BY
conversion_rate DESC;
"
Soma R. - "SELECT
a.marketing_channel,
AVG(a.purchasevalue) AS avgpurchase_value,
SUM(CASE WHEN a.purchasevalue > 0 THEN 1 ELSE 0 END) * 100 / COUNT(a.sessionid) AS conversion_rate
FROM
attribution a
LEFT JOIN
user_sessions u
ON
a.sessionid = u.sessionid
GROUP BY
a.marketing_channel
ORDER BY
conversion_rate DESC;
"See full answer
"
CODE INSTRUCTIONS:
1) The method findInOrderSuccessor you're asked
to implement is located at line 30.
2) Use the helper code below to implement it.
3) In a nutshell, the helper code allows you to
to build a Binary Search Tree.
4) Jump to line 88 to see an example for how the
helper code is used"
Akash C. - "
CODE INSTRUCTIONS:
1) The method findInOrderSuccessor you're asked
to implement is located at line 30.
2) Use the helper code below to implement it.
3) In a nutshell, the helper code allows you to
to build a Binary Search Tree.
4) Jump to line 88 to see an example for how the
helper code is used"See full answer
"Test case is wrong. It expects to sort in asc order of month_year.
-- Write your query here
SELECT
strftime('%Y-%m', createdat) AS monthyear,
COUNT(DISTINCT userid) AS numcustomers,
COUNT(t.id) AS num_orders,
SUM(price * quantity) AS order_amt
FROM
transactions t
INNER JOIN products p
ON t.product_id = p.id
GROUP BY
month_year
ORDER BY
month_year
;
"
Aneesha K. - "Test case is wrong. It expects to sort in asc order of month_year.
-- Write your query here
SELECT
strftime('%Y-%m', createdat) AS monthyear,
COUNT(DISTINCT userid) AS numcustomers,
COUNT(t.id) AS num_orders,
SUM(price * quantity) AS order_amt
FROM
transactions t
INNER JOIN products p
ON t.product_id = p.id
GROUP BY
month_year
ORDER BY
month_year
;
"See full answer
"SELECT
i.item_category,
o.order_date,
SUM(o.orderquantity) AS totalunits_ordered
FROM
orders o
JOIN
items i ON o.itemid = i.itemid
WHERE
o.order_date >= DATE('now', '-6 days')
GROUP BY
i.item_category,
o.order_date
ORDER BY
i.item_category ASC,
o.order_date ASC;"
Anonymous Tortoise - "SELECT
i.item_category,
o.order_date,
SUM(o.orderquantity) AS totalunits_ordered
FROM
orders o
JOIN
items i ON o.itemid = i.itemid
WHERE
o.order_date >= DATE('now', '-6 days')
GROUP BY
i.item_category,
o.order_date
ORDER BY
i.item_category ASC,
o.order_date ASC;"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
"def getcheapestcost(rootNode):
\# need to do DFS for each branch
\# but this can be done recursively
n = len(rootNode.children)
if n == 0:
return 0
else:
min_cost = float('inf')
for i in range(len(n)):
tempcost = getcheapest_cost(rootNode.children[i])
if (tempcost < mincost):
mincost = tempcost
return min_cost + rootNode.cost
\# A node
class Node:
\# Constructor to create a new node
def init\(self, cost):
self.cost = cost
self.children = []
self.parent = None"
Anonymous Owl - "def getcheapestcost(rootNode):
\# need to do DFS for each branch
\# but this can be done recursively
n = len(rootNode.children)
if n == 0:
return 0
else:
min_cost = float('inf')
for i in range(len(n)):
tempcost = getcheapest_cost(rootNode.children[i])
if (tempcost < mincost):
mincost = tempcost
return min_cost + rootNode.cost
\# A node
class Node:
\# Constructor to create a new node
def init\(self, cost):
self.cost = cost
self.children = []
self.parent = None"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
"I couldn't follow the solution offered here, but my solution seemed to pass 6/6 tests. Any feedback is welcome, thank you!
def encrypt(word):
en_word = ""
for i in range(len(word)):
if i == 0:
en_word += chr(ord(word[0])+1)
else:
num = ord(word[i]) + ord(en_word[i-1])
while num > 122:
num -= 26
en_word += chr(num)
return en_word
def decrypt(word):
de_word = ""
for i in range(len(word)):
if i == 0:
de_word += chr(ord(word[i]"
Anonymous Armadillo - "I couldn't follow the solution offered here, but my solution seemed to pass 6/6 tests. Any feedback is welcome, thank you!
def encrypt(word):
en_word = ""
for i in range(len(word)):
if i == 0:
en_word += chr(ord(word[0])+1)
else:
num = ord(word[i]) + ord(en_word[i-1])
while num > 122:
num -= 26
en_word += chr(num)
return en_word
def decrypt(word):
de_word = ""
for i in range(len(word)):
if i == 0:
de_word += chr(ord(word[i]"See full answer
"int main()
{
int a1[7]={1,2,3,4,5,6,7};
int a2[7]={1,9,10,11,12,13,14};
vectorv;
v.insert(v.begin(),begin(a1),end(a1));
v.insert(v.begin(),begin(a2),end(a2));
int a3[v.size()];
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
a3[i]=v[i];
}
}
`"
Aryan D. - "int main()
{
int a1[7]={1,2,3,4,5,6,7};
int a2[7]={1,9,10,11,12,13,14};
vectorv;
v.insert(v.begin(),begin(a1),end(a1));
v.insert(v.begin(),begin(a2),end(a2));
int a3[v.size()];
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
{
a3[i]=v[i];
}
}
`"See full answer
"WITH previous AS(SELECT
viewer_id,
watch_hours,
LAG(watchhours) OVER(PARTITION BY viewerid ORDER BY year, month) AS previous_hours,
year,
month
FROM watch_time
GROUP BY viewer_id, year, month
),
streaks AS(SELECT
viewer_id,
SUM(CASE WHEN previoushours IS NOT NULL AND previoushours = 3
`"
Alvin P. - "WITH previous AS(SELECT
viewer_id,
watch_hours,
LAG(watchhours) OVER(PARTITION BY viewerid ORDER BY year, month) AS previous_hours,
year,
month
FROM watch_time
GROUP BY viewer_id, year, month
),
streaks AS(SELECT
viewer_id,
SUM(CASE WHEN previoushours IS NOT NULL AND previoushours = 3
`"See full answer