Skip to content

Instantly share code, notes, and snippets.

@Fredpwol
Last active May 4, 2021 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fredpwol/41a7117f004c9982140f9a8c76c97282 to your computer and use it in GitHub Desktop.
Save Fredpwol/41a7117f004c9982140f9a8c76c97282 to your computer and use it in GitHub Desktop.
Find array value products
def arrayProducts(arr):
if arr == None: return []
if len(arr) == 1: return [0]
left_mul = 1 #this holds product so far from the left side
for i in range(len(arr)):
right_mul = 1
for j in range(i+1, len(arr)): # this loops from the index of the current value + 1 to the end
right_mul *= arr[j]
temp_v = arr[i]
arr[i] = left_mul *right_mul
left_mul *= temp_v
return arr
@meekg33k
Copy link

meekg33k commented May 2, 2021

Hello @Fredpwol, thank you for participating in Week 4 of Algorithm Fridays.

Your solution works for most test cases, however it fails for the test case for when one of the elements of the array is 0.

arrayProducts([4, 3, 0]); ❌ // should return [0, 0, 12] but yours returns [0, 0, 0]

Also, do you think we can better optimize this in terms of memory usage? Do we have to create a new res array?

Kudos all the same for a good attempt!

@Fredpwol
Copy link
Author

Fredpwol commented May 2, 2021

Hello @meekg33k, Thank you for the response,

I have taken note of all my issues and missing edge cases so here's my new solution please check it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment