"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
"
Compare alternate houses i.e for each house starting from the third, calculate the maximum money that can be stolen up to that house by choosing between:
Skipping the current house and taking the maximum money stolen up to the previous house.
Robbing the current house and adding its value to the maximum money stolen up to the house two steps back.
package main
import (
"fmt"
)
// rob function calculates the maximum money a robber can steal
func maxRob(nums []int) int {
ln"
VContaineers - "
Compare alternate houses i.e for each house starting from the third, calculate the maximum money that can be stolen up to that house by choosing between:
Skipping the current house and taking the maximum money stolen up to the previous house.
Robbing the current house and adding its value to the maximum money stolen up to the house two steps back.
package main
import (
"fmt"
)
// rob function calculates the maximum money a robber can steal
func maxRob(nums []int) int {
ln"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
"Use a representative of each, e.g. sort the string and add it to the value of a hashmap> where we put all the words that belong to the same anagram together."
Gaston B. - "Use a representative of each, e.g. sort the string and add it to the value of a hashmap> where we put all the words that belong to the same anagram together."See full answer
Machine Learning Engineer
Data Structures & Algorithms
+4 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"#inplace reversal without inbuilt functions
def reverseString(s):
chars = list(s)
l, r = 0, len(s)-1
while l < r:
chars[l],chars[r] = chars[r],chars[l]
l += 1
r -= 1
reversed = "".join(chars)
return reversed
"
Anonymous Possum - "#inplace reversal without inbuilt functions
def reverseString(s):
chars = list(s)
l, r = 0, len(s)-1
while l < r:
chars[l],chars[r] = chars[r],chars[l]
l += 1
r -= 1
reversed = "".join(chars)
return reversed
"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
"In python
def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]:
result = list(set(arr1) & set(arr2))
return result
"
Sammy R. - "In python
def find_duplicates(arr1: List[int], arr2: List[int]) -> List[int]:
result = list(set(arr1) & set(arr2))
return result
"See full answer
"\# Definition for a binary tree node.
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.max_sum = float('-inf')"
Jerry O. - "\# Definition for a binary tree node.
class TreeNode:
def init(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.max_sum = float('-inf')"See full answer
"If 0's aren't a concern, couldn't we just
multiply all numbers.
and then divide product by each number in the list ?
if there's more than one zero, then we just return an array of 0s
if there's one zero, then we just replace 0 with product and rest 0s.
what am i missing?"
Sachin R. - "If 0's aren't a concern, couldn't we just
multiply all numbers.
and then divide product by each number in the list ?
if there's more than one zero, then we just return an array of 0s
if there's one zero, then we just replace 0 with product and rest 0s.
what am i missing?"See full answer
"
from typing import List
def getnumberof_islands(binaryMatrix: List[List[int]]) -> int:
if not binaryMatrix: return 0
rows = len(binaryMatrix)
cols = len(binaryMatrix[0])
islands = 0
for r in range(rows):
for c in range(cols):
if binaryMatrixr == 1:
islands += 1
dfs(binaryMatrix, r, c)
return islands
def dfs(grid, r, c):
if (
r = len(grid)
"
Rick E. - "
from typing import List
def getnumberof_islands(binaryMatrix: List[List[int]]) -> int:
if not binaryMatrix: return 0
rows = len(binaryMatrix)
cols = len(binaryMatrix[0])
islands = 0
for r in range(rows):
for c in range(cols):
if binaryMatrixr == 1:
islands += 1
dfs(binaryMatrix, r, c)
return islands
def dfs(grid, r, c):
if (
r = len(grid)
"See full answer
"function findPrimes(n) {
if (n < 2) return [];
const primes = [];
for (let i=2; i <= n; i++) {
const half = Math.floor(i/2);
let isPrime = true;
for (let prime of primes) {
if (i % prime === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
return primes;
}
`"
Tiago R. - "function findPrimes(n) {
if (n < 2) return [];
const primes = [];
for (let i=2; i <= n; i++) {
const half = Math.floor(i/2);
let isPrime = true;
for (let prime of primes) {
if (i % prime === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
primes.push(i);
}
}
return primes;
}
`"See full answer
"
import java.util.*;
class Solution {
// Time Complexity: O(n^2)
// Space Complexity: O(n)
public static List> threeSum(int[] nums) {
// Ensure that the array is sorted first
Arrays.sort(nums);
// Create the results list to return
List> results = new ArrayList();
// Iterate over the length of nums
for (int i = 0; i < nums.length-2; i++) {
// We will have the first number in"
Victor O. - "
import java.util.*;
class Solution {
// Time Complexity: O(n^2)
// Space Complexity: O(n)
public static List> threeSum(int[] nums) {
// Ensure that the array is sorted first
Arrays.sort(nums);
// Create the results list to return
List> results = new ArrayList();
// Iterate over the length of nums
for (int i = 0; i < nums.length-2; i++) {
// We will have the first number in"See full answer
"const ops = {
'+': (a, b) => a+b,
'-': (a, b) => a-b,
'/': (a, b) => a/b,
'': (a, b) => ab,
};
function calc(expr) {
// Search for + or -
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if (['+', '-'].includes(char)) {
return opschar), calc(expr.slice(i+1)));
}
}
// Search for / or *
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if"
Tiago R. - "const ops = {
'+': (a, b) => a+b,
'-': (a, b) => a-b,
'/': (a, b) => a/b,
'': (a, b) => ab,
};
function calc(expr) {
// Search for + or -
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if (['+', '-'].includes(char)) {
return opschar), calc(expr.slice(i+1)));
}
}
// Search for / or *
for (let i=expr.length-1; i >= 0; i--) {
const char = expr.charAt(i);
if"See full answer
"
Brute Force Two Pointer Solution:
from typing import List
def two_sum(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return []
debug your code below
print(two_sum([2, 7, 11, 15], 9))
`"
Ritaban M. - "
Brute Force Two Pointer Solution:
from typing import List
def two_sum(nums, target):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return []
debug your code below
print(two_sum([2, 7, 11, 15], 9))
`"See full answer