"from typing import List
def productExceptSelf(nums: List[int]) -> List[int]:
if len(nums) <= 1:
raise Exception("nums must contain at least 2 items.")
Initialize totalProduct to the first number in nums. Later, we will populate this
as the product of ALL numbers in nums.
totalProduct = nums[0] if nums[0] != 0 else 1
If there is more than 1 zero in nums, all products will end up zero.
But if there's only 1 zero, there will be 1 nonzer"
Gemma S. - "from typing import List
def productExceptSelf(nums: List[int]) -> List[int]:
if len(nums) <= 1:
raise Exception("nums must contain at least 2 items.")
Initialize totalProduct to the first number in nums. Later, we will populate this
as the product of ALL numbers in nums.
totalProduct = nums[0] if nums[0] != 0 else 1
If there is more than 1 zero in nums, all products will end up zero.
But if there's only 1 zero, there will be 1 nonzer"See full answer
"def find_first(array: List[int], num: int) -> int:
lo = 0
hi = len(array)-1
while lo = num:
hi = mid - 1
if lo == mid and array[mid] == num:
return mid
else:
array[mid] < num
lo = mid + 1
return -1
`"
Gabriele G. - "def find_first(array: List[int], num: int) -> int:
lo = 0
hi = len(array)-1
while lo = num:
hi = mid - 1
if lo == mid and array[mid] == num:
return mid
else:
array[mid] < num
lo = mid + 1
return -1
`"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
Data Engineer
Data Structures & Algorithms
+4 more
🧠 Want an expert answer to a question? Saving questions lets us know what content to make next.
"from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = set()
for i in range(len(nums) - 2):
firstNum = nums[i]
l = i + 1
r = len(nums) - 1
while l 0:
r -= 1
elif potentialSum < 0:
l += 1
"
Anonymous Roadrunner - "from typing import List
def three_sum(nums: List[int]) -> List[List[int]]:
nums.sort()
triplets = set()
for i in range(len(nums) - 2):
firstNum = nums[i]
l = i + 1
r = len(nums) - 1
while l 0:
r -= 1
elif potentialSum < 0:
l += 1
"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
"
from typing import Dict, List, Optional
def max_profit(prices: Dict[str, int]) -> Optional[List[str]]:
pass # your code goes here
max = [None, 0]
min = [None, float("inf")]
for city, price in prices.items():
if price > max[1]:
max[0], max[1] = city, price
if price 0:
return [min[0], max[0]]
return None
debug your code below
prices = {'"
Rick E. - "
from typing import Dict, List, Optional
def max_profit(prices: Dict[str, int]) -> Optional[List[str]]:
pass # your code goes here
max = [None, 0]
min = [None, float("inf")]
for city, price in prices.items():
if price > max[1]:
max[0], max[1] = city, price
if price 0:
return [min[0], max[0]]
return None
debug your code below
prices = {'"See full answer
"
import pandas as pd
def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame:
#0. IMPORTANT: get the unordered pairs
gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1)
gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1)
#1. get the mean distance by cities
avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2)
avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True)
"
Sean L. - "
import pandas as pd
def findaveragedistance(gps_data: pd.DataFrame) -> pd.DataFrame:
#0. IMPORTANT: get the unordered pairs
gpsdata['city1']=gpsdata[['origin','destination']].min(axis=1)
gpsdata['city2']=gpsdata[['origin','destination']].max(axis=1)
#1. get the mean distance by cities
avgdistance=gpsdata.groupby(['city1','city2'], as_index=False)['distance'].mean().round(2)
avgdistance.rename(columns={'distance':"averagedistance"}, inplace=True)
"See full answer
"Arrays.sort(inputarray)
sliding window with a size of 2.
Check for the sum in the sliding window.
subtract the start when window moves"
Sridhar R. - "Arrays.sort(inputarray)
sliding window with a size of 2.
Check for the sum in the sliding window.
subtract the start when window moves"See full answer
"Problem Statement: The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2) with F(0) = 1 and F(1) = 1.
The solution is given in the problem statement itself.
If the value of n = 0, return 1.
If the value of n = 1, return 1.
Otherwise, return the sum of data at (n - 1) and (n - 2).
Explanation: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1.
Java Solution:
public static int fib(int n"
Rishi G. - "Problem Statement: The Fibonacci sequence is defined as F(n) = F(n-1) + F(n-2) with F(0) = 1 and F(1) = 1.
The solution is given in the problem statement itself.
If the value of n = 0, return 1.
If the value of n = 1, return 1.
Otherwise, return the sum of data at (n - 1) and (n - 2).
Explanation: The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1.
Java Solution:
public static int fib(int n"See full answer
"def check_byte(octet):
_"""
Checks if the given string \octet\ represents a valid byte (0-255).
"""_
Check for empty string
if not octet:
return False
Check if the string has non-digit characters
if not octet.isdigit():
return False
Check for leading zeroes in multi-digit numbers
if len(octet) > 1 and octet[0] == '0':
return False
Check if the integer value is between 0 and 255
return 0 <= int(octet) <= 255
def va"
Robert W. - "def check_byte(octet):
_"""
Checks if the given string \octet\ represents a valid byte (0-255).
"""_
Check for empty string
if not octet:
return False
Check if the string has non-digit characters
if not octet.isdigit():
return False
Check for leading zeroes in multi-digit numbers
if len(octet) > 1 and octet[0] == '0':
return False
Check if the integer value is between 0 and 255
return 0 <= int(octet) <= 255
def va"See full answer
"A much better solution than the one in the article, below:
It looks like the ones writing articles here in Javascript do not understand the time/space complexity of javascript methods.
shift, splice, sort, etc... In the solution article you have a shift and a sort being done inside a while, that is, the multiplication of Ns.
My solution, below, iterates through the list once and then sorts it, separately. It´s O(N+Log(N))
class ListNode {
constructor(val = 0, next = null) {
th"
Guilherme F. - "A much better solution than the one in the article, below:
It looks like the ones writing articles here in Javascript do not understand the time/space complexity of javascript methods.
shift, splice, sort, etc... In the solution article you have a shift and a sort being done inside a while, that is, the multiplication of Ns.
My solution, below, iterates through the list once and then sorts it, separately. It´s O(N+Log(N))
class ListNode {
constructor(val = 0, next = null) {
th"See full answer
"function areSentencesSimilar(sentence1, sentence2, similarPairs) {
if (sentence1.length !== sentence2.length) return false;
for (let i=0; i (w1 === word1 && !visited.has(w2)) || (w2 === word1 && !visited.has(w1)));
if (!edge) {
"
Tiago R. - "function areSentencesSimilar(sentence1, sentence2, similarPairs) {
if (sentence1.length !== sentence2.length) return false;
for (let i=0; i (w1 === word1 && !visited.has(w2)) || (w2 === word1 && !visited.has(w1)));
if (!edge) {
"See full answer