"from collections import deque
def updateword(words, startword, end_word):
if end_word not in words:
return None # Early exit if end_word is not in the dictionary
queue = deque([(start_word, 0)]) # (word, steps)
visited = set([start_word]) # Keep track of visited words
while queue:
word, steps = queue.popleft()
if word == end_word:
return steps # Found the target word, return steps
for i in range(len(word)):
"
叶 路. - "from collections import deque
def updateword(words, startword, end_word):
if end_word not in words:
return None # Early exit if end_word is not in the dictionary
queue = deque([(start_word, 0)]) # (word, steps)
visited = set([start_word]) # Keep track of visited words
while queue:
word, steps = queue.popleft()
if word == end_word:
return steps # Found the target word, return steps
for i in range(len(word)):
"See full answer
"Reversing a linked list is a very popular question. We have two approaches to reverse the linked list: Iterative approach and recursion approach.
Iterative approach (JavaScript)
function reverseLL(head){
if(head === null) return head;
let prv = null;
let next = null;
let cur = head;
while(cur){
next = cur.next; //backup
cur.next = prv;
prv = cur;
cur = next;
}
head = prv;
return head;
}
Recursion Approach (JS)
function reverseLLByRecursion("
Satyam S. - "Reversing a linked list is a very popular question. We have two approaches to reverse the linked list: Iterative approach and recursion approach.
Iterative approach (JavaScript)
function reverseLL(head){
if(head === null) return head;
let prv = null;
let next = null;
let cur = head;
while(cur){
next = cur.next; //backup
cur.next = prv;
prv = cur;
cur = next;
}
head = prv;
return head;
}
Recursion Approach (JS)
function reverseLLByRecursion("See full answer
"2 Approaches:
1) The more intuitive approach is doing a multi-source BFS from all cats and storing the distance of closest cats. Then do a dfs/bfs from rat to bread.
Time Complexity: O(mn + 4^L) where L is path length, worst case L could be mn
Space Complexity: O(m*n)
2) The first approach should be fine for interviews. But if they ask to optimize it further, you can use Binary Search. Problems like "Finding max of min distance" or "Finding min of max" could be usually solved by BS.
"
Karan K. - "2 Approaches:
1) The more intuitive approach is doing a multi-source BFS from all cats and storing the distance of closest cats. Then do a dfs/bfs from rat to bread.
Time Complexity: O(mn + 4^L) where L is path length, worst case L could be mn
Space Complexity: O(m*n)
2) The first approach should be fine for interviews. But if they ask to optimize it further, you can use Binary Search. Problems like "Finding max of min distance" or "Finding min of max" could be usually solved by BS.
"See full answer
"// C++ program to print the count of
// subsets with sum equal to the given value X
#include
using namespace std;
// Recursive function to return the count
// of subsets with sum equal to the given value
int subsetSum(int arr[], int n, int i,
int sum, int count)
{
// The recursion is stopped at N-th level
// where all the subsets of the given array
// have been checked
if (i == n) {
// Incrementing the count if sum is
// equal to 0 and returning the count
if (sum == 0)"
Ajay U. - "// C++ program to print the count of
// subsets with sum equal to the given value X
#include
using namespace std;
// Recursive function to return the count
// of subsets with sum equal to the given value
int subsetSum(int arr[], int n, int i,
int sum, int count)
{
// The recursion is stopped at N-th level
// where all the subsets of the given array
// have been checked
if (i == n) {
// Incrementing the count if sum is
// equal to 0 and returning the count
if (sum == 0)"See full answer
"Idea for solution:
Reverse the complete char array
Reverse the words separated by space. i.e. Find the space characters and the reverse the subarray between two space characters.
vector reverseSubarray(vector& arr, int s, int e)
{
while (s reverseWords(vector& arr )
{
int n = arr.size();
reverse(arr, 0, n - 1"
Rahul M. - "Idea for solution:
Reverse the complete char array
Reverse the words separated by space. i.e. Find the space characters and the reverse the subarray between two space characters.
vector reverseSubarray(vector& arr, int s, int e)
{
while (s reverseWords(vector& arr )
{
int n = arr.size();
reverse(arr, 0, n - 1"See full answer
"You can ask some clarifying questions like
1) Ask if the list is already sorted or not
2) is zero included in the list ?
3) Natural numbers are usually positive numbers ( clarify they are non negatives)
Solution :
1) If sorted use two pointers and sort them in O(N)
2) if not sorted , -ve / only +ve numbers in the list doesn't matter - the easiest solution is
Use a priority queue and push the number and its square in each iteration
Finally return the list returned by the priority Queue. N"
Bless M. - "You can ask some clarifying questions like
1) Ask if the list is already sorted or not
2) is zero included in the list ?
3) Natural numbers are usually positive numbers ( clarify they are non negatives)
Solution :
1) If sorted use two pointers and sort them in O(N)
2) if not sorted , -ve / only +ve numbers in the list doesn't matter - the easiest solution is
Use a priority queue and push the number and its square in each iteration
Finally return the list returned by the priority Queue. N"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
"function serialize(list) {
for (let i=0; i 0xFFFF) {
throw new Exception(String ${list[i]} is too long!);
}
const prefix = String.fromCharCode(length);
list[i] = ${prefix}${list[i]};
console.log(list[i])
}
return list.join('');
}
function deserialize(s) {
let i=0;
const length = s.length;
const output = [];
while (i < length) {
"
Tiago R. - "function serialize(list) {
for (let i=0; i 0xFFFF) {
throw new Exception(String ${list[i]} is too long!);
}
const prefix = String.fromCharCode(length);
list[i] = ${prefix}${list[i]};
console.log(list[i])
}
return list.join('');
}
function deserialize(s) {
let i=0;
const length = s.length;
const output = [];
while (i < length) {
"See full answer
"def friend_distance(friends, userA, userB):
step = 0
total_neighs = set()
llen = len(total_neighs)
total_neighs.add(userB)
while len(total_neighs)!=llen:
s = set()
step += 1
llen = len(total_neighs)
for el in total_neighs:
nes = neighbours(friends, userA, el)
if userA in nes:
return step
for p in nes:
s.add(p)
for el in s:
total_neighs.add(el)
return -1
def neighbours(A,n1, n2):
out = set()
for i in range(len(A[n2])):
if An2:
out.add(i)
return out"
Batman X. - "def friend_distance(friends, userA, userB):
step = 0
total_neighs = set()
llen = len(total_neighs)
total_neighs.add(userB)
while len(total_neighs)!=llen:
s = set()
step += 1
llen = len(total_neighs)
for el in total_neighs:
nes = neighbours(friends, userA, el)
if userA in nes:
return step
for p in nes:
s.add(p)
for el in s:
total_neighs.add(el)
return -1
def neighbours(A,n1, n2):
out = set()
for i in range(len(A[n2])):
if An2:
out.add(i)
return out"See full answer
"Yes, I need to compare the first half of the first string with the reverse order of the second half of the second string. Repeat this process to the first half of the second string and the second half of the first string."
Noor M. - "Yes, I need to compare the first half of the first string with the reverse order of the second half of the second string. Repeat this process to the first half of the second string and the second half of the first string."See full answer
"
from typing import List
def least_interval(tasks: List[str], n: int) -> int:
pass # your code goes here
if n == 0:
return len(tasks)
dictionary = {}
total_sum = len(tasks)
output = 0
for t in tasks:
if t in dictionary:
dictionary[t] += 1
else:
dictionary[t] = 1
dictLen = len(dictionary)
while total_sum > 0:
for key in dictionary.keys():
if dictionary[key] > 0:
"
Anonymous Quail - "
from typing import List
def least_interval(tasks: List[str], n: int) -> int:
pass # your code goes here
if n == 0:
return len(tasks)
dictionary = {}
total_sum = len(tasks)
output = 0
for t in tasks:
if t in dictionary:
dictionary[t] += 1
else:
dictionary[t] = 1
dictLen = len(dictionary)
while total_sum > 0:
for key in dictionary.keys():
if dictionary[key] > 0:
"See full answer
"public static void sortBinaryArray(int[] array) {
int len = array.length;
int[] res = new int[len];
int r=len-1;
for (int value : array) {
if(value==1){
res[r]= 1;
r--;
}
}
System.out.println(Arrays.toString(res));
}
`"
Nitin P. - "public static void sortBinaryArray(int[] array) {
int len = array.length;
int[] res = new int[len];
int r=len-1;
for (int value : array) {
if(value==1){
res[r]= 1;
r--;
}
}
System.out.println(Arrays.toString(res));
}
`"See full answer