Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# O(n) in time complexity.
# O(n) in space complexity
n = len(nums)
left_cum_prod = [1]
for i in range(n-1):
left_cum_prod.append(left_cum_prod[i] * nums[i])
right_cum_prod = [1]
for i in range(n-1):
right_cum_prod.append(right_cum_prod[i] * nums[n-1-i])
return [left_cum_prod[i] * right_cum_prod[n-1-i] for i in range(n)]
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# O(n) in time complexity.
# O(1) in space complexity
n = len(nums)
left_cum_prod = [1]
for i in range(n-1):
left_cum_prod.append(left_cum_prod[i] * nums[i])
# Do it in-place instead of using right_cum_prod
right_cum_prod = 1
for i in range(1, n):
left_cum_prod[n-1-i] *= right_cum_prod * nums[n-i]
right_cum_prod *= nums[n-i]
"""
nums = [1, 2, 3, 4]
L = [1, 1, 2, 6]
L[3] = 6
L[2] = 2 * (1 * 4) = 8
L[1] = 1 * (4 * 3) = 12
L[0] = 1 * (12* 2) = 24
"""
return left_cum_prod
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
res = [1]
for i, elt in enumerate(nums[:-1]):
res.append(res[i] * elt)
R, n = 1, len(res)
for i, elt in enumerate(nums[::-1]):
res[n-1-i] *= R
R *= elt
return res
https://leetcode.com/problems/find-k-closest-elements/ Naive def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: L = sorted([(abs(elt - x), elt) for elt in arr], key=lambda tup: tup[0]) return sorted([tup[1] for tup in L[:k]]) Opti
Sep 23, 2022Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example: MinStack minStack = new MinStack();
Jun 27, 2022Given a string containing just the characters $($, $)$, ${$, $}$, $[$ and $]$, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Jun 27, 2022Solution 1 Time complexity: O(n³) Space complexity: O(n) class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: n = len(nums) if n < 3: return []
Apr 23, 2022or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up