"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
"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
"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
" 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
"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
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"function visitChildren(node) { let leftSubtreeHeight = 0; let rightSubtreeHeight = 0; let isChildrenBalanced = true; if (node.left) { const { isBalanced, height } = visitChildren(node.left); isChildrenBalanced = isChildrenBalanced && isBalanced; leftSubtreeHeight += height + 1; } if (isChildrenBalanced && node.right) { const { isBalanced, height } = visitChildren(node.right); isChildrenBalanced = isChildrenBalanced && isBalan"
Tiago R. - "function visitChildren(node) { let leftSubtreeHeight = 0; let rightSubtreeHeight = 0; let isChildrenBalanced = true; if (node.left) { const { isBalanced, height } = visitChildren(node.left); isChildrenBalanced = isChildrenBalanced && isBalanced; leftSubtreeHeight += height + 1; } if (isChildrenBalanced && node.right) { const { isBalanced, height } = visitChildren(node.right); isChildrenBalanced = isChildrenBalanced && isBalan"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
"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
"with cte as ( select user_id, timestamp as current_login, lag(timestamp,1) over(partition by userid order by timestamp) as previouslogin , round(abs(julianday(timestamp)-julianday(lag(timestamp,1) over(partition by userid order by timestamp)))2460)as minuteselapsed from useractivitylog where activity_type ='LOGIN' ) select userid, currentlogin, previouslogin, minuteselapsed from cte where currentlogin previouslogin `"
Gowtami K. - "with cte as ( select user_id, timestamp as current_login, lag(timestamp,1) over(partition by userid order by timestamp) as previouslogin , round(abs(julianday(timestamp)-julianday(lag(timestamp,1) over(partition by userid order by timestamp)))2460)as minuteselapsed from useractivitylog where activity_type ='LOGIN' ) select userid, currentlogin, previouslogin, minuteselapsed from cte where currentlogin previouslogin `"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
"function findRotations(nums) { if (nums.length 0 && nums[mid] > nums[mid-1]) { left = mid; } else { right = mid; } } return rig"
Tiago R. - "function findRotations(nums) { if (nums.length 0 && nums[mid] > nums[mid-1]) { left = mid; } else { right = mid; } } return rig"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
"Hi, my solution gives the exact numerical values as the proposed solution, but it doesn't pass the tests. Am I missing something, or is this a bug? def findrevenueby_city(transactions: pd.DataFrame, users: pd.DataFrame, exchange_rate: pd.DataFrame) -> pd.DataFrame: gets user city for each user id userids = users[['id', 'usercity']] and merge on transactions transactions = transactions.merge(user_ids, how='left"
Gabriel P. - "Hi, my solution gives the exact numerical values as the proposed solution, but it doesn't pass the tests. Am I missing something, or is this a bug? def findrevenueby_city(transactions: pd.DataFrame, users: pd.DataFrame, exchange_rate: pd.DataFrame) -> pd.DataFrame: gets user city for each user id userids = users[['id', 'usercity']] and merge on transactions transactions = transactions.merge(user_ids, how='left"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
"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
"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
"Schema is wrong - id from product is mapped to id from transactions, id from product should point to product_id in transcations table"
Arshad P. - "Schema is wrong - id from product is mapped to id from transactions, id from product should point to product_id in transcations table"See full answer
"function getCheapestCost(rootNode) { let cost = rootNode.cost; if (rootNode.children.length === 0) { return cost; } let minCost = Infinity; for (let child of rootNode.children) { minCost = Math.min(minCost, getCheapestCost(child)); } return cost + minCost; } `"
Tiago R. - "function getCheapestCost(rootNode) { let cost = rootNode.cost; if (rootNode.children.length === 0) { return cost; } let minCost = Infinity; for (let child of rootNode.children) { minCost = Math.min(minCost, getCheapestCost(child)); } return cost + minCost; } `"See full answer
"with base as ( select viewerid, year, month, watchhours, lag(watchhours, 2) over (partition by viewerid order by year, month) as p3, lag(watchhours, 1) over (partition by viewerid order by year, month) as p2 from watch_time ) select viewer_id from base where p3 < p2 and p2 < watch_hours group by 1 `"
- Z. - "with base as ( select viewerid, year, month, watchhours, lag(watchhours, 2) over (partition by viewerid order by year, month) as p3, lag(watchhours, 1) over (partition by viewerid order by year, month) as p2 from watch_time ) select viewer_id from base where p3 < p2 and p2 < watch_hours group by 1 `"See full answer
"too many questions for clarification on this to start"
Steven S. - "too many questions for clarification on this to start"See full answer
Interviewed recently?
Help improve our question database (and earn karma) by telling us about your experience
+ Add your interview