"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
"public static boolean isPalindrome(String str){
boolean flag = true;
int len = str.length()-1;
int j = len;
for(int i=0;i<=len/2;i++){
if(str.charAt(i)!=str.charAt(j--)){
flag = false;
break;
}
}
return flag;
}"
Sravanthi M. - "public static boolean isPalindrome(String str){
boolean flag = true;
int len = str.length()-1;
int j = len;
for(int i=0;i<=len/2;i++){
if(str.charAt(i)!=str.charAt(j--)){
flag = false;
break;
}
}
return flag;
}"See full answer
"We can use dictionary to store cache items so that our read / write operations will be O(1).
Each time we read or update an existing record, we have to ensure the item is moved to the back of the cache. This will allow us to evict the first item in the cache whenever the cache is full and we need to add new records also making our eviction O(1)
Instead of normal dictionary, we will use ordered dictionary to store cache items. This will allow us to efficiently move items to back of the cache a"
Alfred O. - "We can use dictionary to store cache items so that our read / write operations will be O(1).
Each time we read or update an existing record, we have to ensure the item is moved to the back of the cache. This will allow us to evict the first item in the cache whenever the cache is full and we need to add new records also making our eviction O(1)
Instead of normal dictionary, we will use ordered dictionary to store cache items. This will allow us to efficiently move items to back of the cache a"See full answer
Software Engineer
Data Structures & Algorithms
+6 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"#include
#include
#include
using namespace std;
vector diff(const vector& A, const vector& B) {
unordered_set elements;
vector result;
for (const auto& element : A) {
elements.insert(element);
}
for (const auto& element : B) {
if (elements.find(element) == elements.end()) {
result.push_back(element);
} else {
elements.erase(element);
}
}
for"
Warrenbuff - "#include
#include
#include
using namespace std;
vector diff(const vector& A, const vector& B) {
unordered_set elements;
vector result;
for (const auto& element : A) {
elements.insert(element);
}
for (const auto& element : B) {
if (elements.find(element) == elements.end()) {
result.push_back(element);
} else {
elements.erase(element);
}
}
for"See full answer
"we can use two pointer + set like maintain i,j and also insert jth character to set like while set size is equal to our window j-i+1 then maximize our answer and increase jth pointer till last index"
Kishor J. - "we can use two pointer + set like maintain i,j and also insert jth character to set like while set size is equal to our window j-i+1 then maximize our answer and increase jth pointer till last index"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
"this assumes that the dependency among courses is in a growing order:
0 -> 1 -> 2 -> ...
if not, then the code will not work"
Gabriele G. - "this assumes that the dependency among courses is in a growing order:
0 -> 1 -> 2 -> ...
if not, then the code will not work"See full answer
"this solution here is much faster than the exponent reference soln. It is also far more concise and easy to understand
def moveZerosToEnd(arr: List[int]) -> List[int]:
left = 0
for right in range(len(arr)):
if arr[right] == 0:
pass
else:
if left != right:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left += 1
return arr
`"
Devesh K. - "this solution here is much faster than the exponent reference soln. It is also far more concise and easy to understand
def moveZerosToEnd(arr: List[int]) -> List[int]:
left = 0
for right in range(len(arr)):
if arr[right] == 0:
pass
else:
if left != right:
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left += 1
return arr
`"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
"One thing is not clear to me, We encoded the length of the word to a character, but the max number which can be converted to char ascii is 255. How will it work for length till 65535?"
Curly T. - "One thing is not clear to me, We encoded the length of the word to a character, but the max number which can be converted to char ascii is 255. How will it work for length till 65535?"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