"import string
from collections import defaultdict
def mostcommonwords(text):
d = defaultdict(int)
s = text.translate(str.maketrans('', '', string.punctuation))
for w in s.lower().split():
d[w] = d[w] + 1
return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1])
`"
Michael S. - "import string
from collections import defaultdict
def mostcommonwords(text):
d = defaultdict(int)
s = text.translate(str.maketrans('', '', string.punctuation))
for w in s.lower().split():
d[w] = d[w] + 1
return sorted(sorted(d.items()), reverse=True, key=lambda x: x[1])
`"See full answer
"Approach 1: Use sorting and return the kth largest element from the sorted list. Time complexity: O(nlogn)
Approach 2: Use max heap and then select the kth largest element. time complexity: O(n+logn)
Approach 3: Quickselect. Time complexity O(n)
I explained my interviewer the 3 approaches. He told me to solve in a naive manner. Used Approach 1 had some time left so coded approach 3 also
The average time complexity of Quickselect is O(n), making it very efficient for its purpose. However, in"
GalacticInterviewer - "Approach 1: Use sorting and return the kth largest element from the sorted list. Time complexity: O(nlogn)
Approach 2: Use max heap and then select the kth largest element. time complexity: O(n+logn)
Approach 3: Quickselect. Time complexity O(n)
I explained my interviewer the 3 approaches. He told me to solve in a naive manner. Used Approach 1 had some time left so coded approach 3 also
The average time complexity of Quickselect is O(n), making it very efficient for its purpose. However, in"See full answer
"def encode(root):
if not root:
return []
def dfs(node):
if not node:
return
res.append(node.val)
res.append(len(node,children))
for child_node in node.children:
dfs(child_node)
res = []
dfs(root)
return res
def decode(arr):
if not arr:
return None
n = len(arr)
i = 0
def dfs(val, children_count):
if children_count == 0:
return Node(val)
cur_node = Node(val)
cur_node.children = []
for j in range(children_count):
nonlocal i
i += 2
cur_node.children.append(dfs(arr[i], arr[i"
Ying T. - "def encode(root):
if not root:
return []
def dfs(node):
if not node:
return
res.append(node.val)
res.append(len(node,children))
for child_node in node.children:
dfs(child_node)
res = []
dfs(root)
return res
def decode(arr):
if not arr:
return None
n = len(arr)
i = 0
def dfs(val, children_count):
if children_count == 0:
return Node(val)
cur_node = Node(val)
cur_node.children = []
for j in range(children_count):
nonlocal i
i += 2
cur_node.children.append(dfs(arr[i], arr[i"See full answer
"def changeString(org: str,target:str) -> bool:
lOrg = len(org)
lTarget = len(target)
\# They have to be equal in lenght
if lOrg != lTarget:
return False
counter1 = Counter(org)
counter2 = Counter(target)
\# Counter internally iterates through the input sequence, counts the number of times a given object occurs, and stores objects as keys and the counts as values.
if counter1 != counter2:
return False
diff = sum(org[i] != target[i] for i in range(n))
return diff == 2 or (diff == 0 and any(v > 1 f"
Rafał P. - "def changeString(org: str,target:str) -> bool:
lOrg = len(org)
lTarget = len(target)
\# They have to be equal in lenght
if lOrg != lTarget:
return False
counter1 = Counter(org)
counter2 = Counter(target)
\# Counter internally iterates through the input sequence, counts the number of times a given object occurs, and stores objects as keys and the counts as values.
if counter1 != counter2:
return False
diff = sum(org[i] != target[i] for i in range(n))
return diff == 2 or (diff == 0 and any(v > 1 f"See full answer
Coding
Data Structures & Algorithms
🧠Want an expert answer to a question? Saving questions lets us know what content to make next.
"Any cycle would cause the prerequisite to be greater than the course. This passes all the tests:
function canFinish(_numCourses, prerequisites) {
for (const [a, b] of prerequisites) {
if (b > a) return false
}
return true
}
`"
Jeremy D. - "Any cycle would cause the prerequisite to be greater than the course. This passes all the tests:
function canFinish(_numCourses, prerequisites) {
for (const [a, b] of prerequisites) {
if (b > a) return false
}
return true
}
`"See full answer
"The user table no longer exists as expected - I get an error that user does not contain user_id.
Note that querying the table results in only user:swuoevkivrjfta
select * FROM user
`"
Evan R. - "The user table no longer exists as expected - I get an error that user does not contain user_id.
Note that querying the table results in only user:swuoevkivrjfta
select * FROM user
`"See full answer
"WITH RECURSIVE fibonacci_series AS (
SELECT
1 AS n,
0 AS fib1,
1 AS fib2
UNION ALL
SELECT
n + 1 AS n,
fib2 AS fib1,
fib1 + fib2 AS fib2
FROM fibonacci_series
WHERE n < 20 -- Limit the series to 20 numbers
)
SELECT
n,
fib1 AS fib
FROM fibonacci_series
ORDER BY n;
`"
Yashasvi V. - "WITH RECURSIVE fibonacci_series AS (
SELECT
1 AS n,
0 AS fib1,
1 AS fib2
UNION ALL
SELECT
n + 1 AS n,
fib2 AS fib1,
fib1 + fib2 AS fib2
FROM fibonacci_series
WHERE n < 20 -- Limit the series to 20 numbers
)
SELECT
n,
fib1 AS fib
FROM fibonacci_series
ORDER BY n;
`"See full answer
"First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently.
Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"
Stanley Y. - "First of all, stack and heap memory are abstraction on top of the hardware by the compiler. The hardware is not aware of stack and heap memory. There is only a single piece of memory that a program has access to. The compiler creates the concepts of stack and heap memory to run the programs efficiently.
Programs use stack memory to store local variables and a few important register values such as frame pointer and return address for program counter. This makes it easier for the compiler to gene"See full answer
"Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis.
Answer: You can do this with a counter.
Psuedo-Python
Start with counter = 0
output = []
Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output.
If you encounter a ')', decrement the coun"
Michael B. - "Problem: Given an input string txt consisting of alphanumeric characters and the parentheses characters '(' & ')', write a function which removes the minimum number of characters to return a version of the string with properly balanced parenthesis.
Answer: You can do this with a counter.
Psuedo-Python
Start with counter = 0
output = []
Iterate through the string, every time you encounter a '(', increment the counter. Add the character to the output.
If you encounter a ')', decrement the coun"See full answer
"Write a function which Caesar ciphers all the strings so that the first character is "a". Use ascii code points and the modulo operator to do this.
Use this function to create a hashmap between each string and the CC-a string. Then go through each key:value pair in the hashmap, and use the CC-a ciphered value as the key in a new defaultdict(list), adding the original string to the value field in the output."
Michael B. - "Write a function which Caesar ciphers all the strings so that the first character is "a". Use ascii code points and the modulo operator to do this.
Use this function to create a hashmap between each string and the CC-a string. Then go through each key:value pair in the hashmap, and use the CC-a ciphered value as the key in a new defaultdict(list), adding the original string to the value field in the output."See full answer
"naive solution:
def countprefixpairs(words):
n = len(words)
count = 0
for i in range(n):
for j in range(i + 1, n):
if words[i].startswith(words[j]) or words[j].startswith(words[i]):
count += 1
return count
using tries for when the list of words is very long:
from collections import Counter
class TrieNode:
def init(self):
self.children = {}
self.count = 0 # To count the number of words ending at this node"
Anonymous Unicorn - "naive solution:
def countprefixpairs(words):
n = len(words)
count = 0
for i in range(n):
for j in range(i + 1, n):
if words[i].startswith(words[j]) or words[j].startswith(words[i]):
count += 1
return count
using tries for when the list of words is very long:
from collections import Counter
class TrieNode:
def init(self):
self.children = {}
self.count = 0 # To count the number of words ending at this node"See full answer
"Initialize left pointer: Set a left pointer left to 0.
Iterate through the array: Iterate through the array from left to right.
If the current element is not 0, swap it with the element at the left pointer and increment left.
Time complexity: O(n). The loop iterates through the entire array once, making it linear time.
Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures.
"
Avon T. - "Initialize left pointer: Set a left pointer left to 0.
Iterate through the array: Iterate through the array from left to right.
If the current element is not 0, swap it with the element at the left pointer and increment left.
Time complexity: O(n). The loop iterates through the entire array once, making it linear time.
Space complexity: O(1). The algorithm operates in-place, modifying the input array directly without using additional data structures.
"See full answer
"Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited:
def diameterOfTree(root):
if root is None:
return 0
diameter = 0
stack = deque([[root, False]]) # (node, visited)
node_heights = {}
while stack:
curr_node, visited = stack[-1]
if visited:
heightleft = nodeheights.get(curr_node.left, 0)
heightright = nodehe"
Gabriele G. - "Without using a recursive approach, one can perform a post-order traversal by removing the parent nodes from the stack only if children were visited:
def diameterOfTree(root):
if root is None:
return 0
diameter = 0
stack = deque([[root, False]]) # (node, visited)
node_heights = {}
while stack:
curr_node, visited = stack[-1]
if visited:
heightleft = nodeheights.get(curr_node.left, 0)
heightright = nodehe"See full answer