349. Intersection of Two Arrays(Solution || Leetcode easy || Java)

Palakkgoyal
2 min readNov 13, 2022

--

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

SOLUTION:

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//First sort both the arrays
Arrays.sort(nums1);
Arrays.sort(nums2);

//Create a list for storing elements
List<Integer> temp = new ArrayList<>();

//start a for loop for searching elements of intersection
for(int i = 0; i < nums1.length; i++){
//if our list do not contains that element then search for that element
if(!temp.contains(nums1[i])){

for(int j = 0; j < nums2.length; j++){
//if the element is also in array 2 then add that in our list
if(nums1[i] == nums2[j]){
temp.add(nums1[i]);
break;
}
}
}
}

//create array to return
int[] ans = new int[temp.size()];

//copy elements of list into array
for(int k = 0; k < temp.size(); k++){
ans[k] = temp.get(k);
}
return ans;
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet