why is my for loop within a for loop causing issues?

I have the following code, where we have two lists of unique integers, nums1 and nums2; where nums1 is a subset of nums2. We want compare each element of nums1 with nums2, and append the ‘output_stack’ with the next biggest integer in nums2.

For example: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

def nextGreaterElement(nums1, nums2):
    nums1 = sorted(nums1)
    nums2 = sorted(nums2)


    output_stack = []
    for i in range(len(nums1)):
        for j in range(len(nums2)):
            if nums1[i] ==nums2[-1]:
                output_stack.append(-1)

            elif nums1[i] == max(nums2):
                output_stack.append(-1)

            elif nums1[i] == nums2[j]:
                output_stack.append(nums2[j+1])

            else:
                output_stack.append(-1)

        return(print(output_stack))

nextGreaterElement([2,4],[1,2,3,4])

The code above returns the wrong output [-1,3,-1,-1] and I know why- it is because I am iterating over all of nums2 with j, but this is the only way I know how to do it. Is there a way to amend the existing code.

My trouble is that if I took away the second ‘for’ loop, I struggled to find a way to reference the ‘next’ index in nums2; is there a way to do this without using a ‘for’ loop?

Answer

try to exit from the second for loop inside the else-if structure:

    for i in range(len(nums1)):
      for j in range(len(nums2)):
        if nums1[i] ==nums2[-1]:
            output_stack.append(-1)
            break
        elif nums1[i] == max(nums2):
            output_stack.append(-1)
            break
        elif nums1[i] == nums2[j]:
            output_stack.append(nums2[j+1])
            break
        else:
            output_stack.append(-1)
            break
    return(print(output_stack))