Write a java program to find intersection of elements in two arrays in java

Поделиться
HTML-код
  • Опубликовано: 10 фев 2025
  • This video explains how to find intersection of elements in 2 arrays in java.

Комментарии • 11

  • @srinivasgangaraju2998
    @srinivasgangaraju2998 Год назад +3

    all your solutions are containing the collections/ using some apis. generally interviewer asks for solutions without using any datastructures.

  • @svr9546
    @svr9546 Год назад +2

    public class InterSection {
    public static void main(String[] args) {
    int arr1[]= {4,1,2,3};
    int arr2[]= {5,4,2,8};
    System.out.println("Intersection of the Two Arrays:: ");

    for(int i=0; i

  • @manimaran3926
    @manimaran3926 Год назад +2

    Most of the time they'll say don't use any built in method to solve the problem.
    for (int i = 0; i < arr1.length; i++) {
    for (int j = 0; j < arr2.length; j++) {
    if(arr1[i] == arr2[j]) {
    return arr2[j];
    }
    }
    }

  • @sushant3530
    @sushant3530 2 года назад +1

    Can we use hashmap also ?

  • @vengateshm2122
    @vengateshm2122 3 года назад +7

    Another approach
    1. Add array1 to hashset1
    2. Add array2 to hashset2
    3. Hashset1.retainAll(hashset2)
    We can use the below also but it will add the second array element into hashset
    if(!hashset.add(arrElement))

  • @sarathvarada8618
    @sarathvarada8618 3 года назад +1

    Hi,
    What is the purpose of using hashset here. Please let me know

    • @bhumikabansal6022
      @bhumikabansal6022 Год назад +1

      hashset allows only non duplicate elements. so there will be no repeatation of same common element

  • @karthikreddypakala3060
    @karthikreddypakala3060 3 года назад

    if there are dublicate elements while we are adding elements to the hashset what should we do?

    • @omprakashak7176
      @omprakashak7176 3 года назад +1

      This code will fail.

    • @kishorenagarajan344
      @kishorenagarajan344 3 года назад +5

      That's the reason why we use a HashSet here as it stores only unique elements so when you add elements to the hash from the array you get only a set with unique elements and avoids the duplicates

  • @AshmitaChoudhury
    @AshmitaChoudhury 9 месяцев назад

    code please