# Why is my for-loop not decrementing after i = 0? (need i to become negative to exit out of loop!)

## Why is my for-loop not decrementing after i = 0? (need i to become negative to exit out of loop!)

Contents

Problem Description:

Trying to solve this Easy LeetCode question using two ptrs. Values for m & n should be constant, and I’m not decrementing the value for i anywhere else. Why is my for-loop not decrementing after i = 0? Any ideas? TIA!

``````class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
//Start filling nums1[] from the end instead
//Will run in O(m+n) = nums1.length()
int ptr1 = m-1, ptr2 = n-1;
for(int i = m+n-1; i > -1; i--){
//System.out.println("i = " + i);
//System.out.println("ptr1 = " + ptr1 + "tptr2 = " + ptr2);
if(ptr2 < 0 || nums1[ptr1] > nums2[ptr2])
nums1[i] = nums1[ptr1--];
else
nums1[i] = nums2[ptr2--];
System.out.println("nums1[" + i + "] = " + nums1[i]);
}
}
``````

}

## Solution – 1

Try this:

``````public class Test {
public static void main(String[] args) {

for (int i=6; i>-1; i--)
{
System.out.println(i);
}
}
``````

}

## Solution – 2

Your problem is not where you think it is.

The `for` loop correctly exits.

The output you show is from test case 1 (lines 1 to 6):

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3

``````nums1[5] = 6
nums1[4] = 5
nums1[3] = 3
nums1[2] = 2
nums1[1] = 2
nums1[0] = 1
``````

and from test case 2 (line 7):

Input: nums1 = [1], m = 1, nums2 = [], n = 0

``````nums1[0] = 1
``````

and then your code fails for test case 3

Input: nums1 = [0], m = 0, nums2 = [1], n = 1

You can verify that the for loop correctly exits by adding a System.out.println("Done"); after the for loop.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.