Posts Common Elements (geeksforgeeks - SDE Sheet)
Post
Cancel

Common Elements (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given two lists V1 and V2 of sizes n and m respectively. Return the list of elements common to both the lists and return the list in sorted order. Duplicates may be there in the output list.

geeksforgeeks

SOLUTION

To solve this, we sort both arrays and use two pointers to compare elements. If they’re equal, we add the element to the result and move both pointers. If not, we move the pointer with the smaller element.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {

    public static ArrayList<Integer> common_element(int v1[], int v2[]) {

        int n = v1.length;
        int m = v2.length;

        Arrays.sort(v1);
        Arrays.sort(v2);

        ArrayList<Integer> list = new ArrayList<>();

        int i = 0;
        int j = 0;

        // Traverse both arrays using the two-pointer technique
        while (i < n && j < m) {

            // If both elements are equal, add to the list and move both pointers
            if (v1[i] == v2[j]) {
                list.add(v1[i]);
                i++;
                j++;

            // If the element in v1 is smaller, increment pointer i to move forward
            } else if (v1[i] < v2[j]) {
                i++;

            // If the element in v2 is smaller, increment pointer j to move forward
            } else {
                j++;
            }

        }

        return list;
    }
}
This post is licensed under CC BY 4.0 by the author.