Java Interview Program (1)

By | September 15, 2017

Problem Statement:

Given two integer arrays, merge the common elements into a new array and find the sum of the elements.

input 1: {1,2,3,4}
input 2: {3,4,5,6}
common elements: {3,4}
output:7

Logic:

Solution:

package mypack;

import java.util.*;
public class Example { 
 public static int mergeArray(int a[],int b[]){
  //Create two ArrayLists 
  List<Integer> l1=new ArrayList<Integer>(); 
  List<Integer> l2=new ArrayList<Integer>(); 
  // Declare and initialize an int variable to store the sum of common elements
  int i,output=0; 
  for(i=0;i<a.length;i++) 
    l1.add(a[i]); 
  for(i=0;i<b.length;i++) 
    l2.add(b[i]); 
  l1.retainAll(l2); 
  for(i=0;i<l1.size();i++) 
    output+=(Integer) l1.get(i); 
 return output; 
} 
 public static void main(String[] args) { 
  int[] array1={1,2,3,4}; 
  int[] array2={3,4,5,6}; 
 System.out.println(mergeArray(array1,array2)); 
 }
}

Result:

Leave a Reply