Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
(Spoilers) Why do we iterate from right to left?

Daven L

Sep 12, 2023

In the solution snippet, the answer is:

# Iterate from 'right' to 'left' and add all these subarrays to the result. for i in range(right, left - 1, -1): # Add the current element at the beginning of the list. temp_list.insert(0, arr[i]) # Add the current subarray to the result. result.append(list(temp_list))

But what I don't understand is why we should do it this way.

What I had was:

left, right = 0, 0 product = 1 ans = [] while right < len(arr): product *= arr[right] # move left until product < target while product >= target and left < len(arr): product /= arr[left] left += 1 # guaranteed to have product < target, get all windows tmp = [] for i in range(left, right + 1): tmp.append(arr[i]) ans.append(list(tmp)) right += 1 return ans

And with inputs [8, 2, 6, 5], 50, the answer should be:

[[8], [2], [2, 8], [6], [6, 2], [5], [5, 6]]

But I am getting

[[8], [8], [8, 2], [2], [2, 6], [6], [6, 5]]

Is it a small mistake in my logic or is my approach fundamentally wrong?

2

0

Comments
Comments