How to replace zeros in the array, with elements of another array in java

import java.util.Arrays;
public class Main
{
public static void main(String[] args) {

    int[] a = {1,2,3,0,0,0};
    int[] b = {7,9,13};
    
    //resultant array: a={1,2,3,7,9,13}

}

>Solution :

Iterate through array A and replace elements with value zero with elements from B.

int n = a.length();
int m = b.length();
int j = 0;
for(int i=0; i<n; i++){
  if(a[i] == 0 && j<m){a[i]=b[j];j++;}
}

Leave a Reply