Friday, October 3, 2025

How to Find Common Elements Between Two Arrays Java Program

This post is about writing a Java program to find common elements between two given arrays. It is a common interview question where it may be asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set or you may be asked to write using any inbuilt data structure.

1. Find Common Elements Between Two Arrays With Nested Loops - Java Program

In this approach to find common elements between two arrays in Java is to loop through one of the array in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array. If similar element is found print it and break from the inner loop.

Find common elements between two given arrays of integers

 
public class FindCommonElement {
 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }  
 }
}

Output

 
1
5

Find common elements between two arrays of strings

Logic to find common elements between two arrays remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.

 
public class FindCommonElement {
 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
 }
}

Output

 
Java
Scala
Python

Time and Space Complexity of This Approach

If first array has n elements and second array has m elements. Then outer loop runs n times and the inner loop may run upto m times. So, the time complexity is O(n X m).

No Extra space is needed in this approach so space complexity is O(1).

2. Find Common Elements Between Two Arrays Using HashSet - Java Program

If you are asked to write Java program to find common elements between two arrays where you can use inbuilt data structures then using HashSet provides a better performing solution than solution using nested loops.

Steps for solution are as given below

  1. Add all the elements of the first array in the HashSet.
  2. For each element of the second array, check if it is already in the set. If yes, that means a common element.
  3. Store such common elements in a separate List
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CommonElementArray {
  public static void main(String[] args) {
    
    String[] strArray1 = {"Java", "Scala", "Clojure"};
    String[] strArray2 = {".Net", "Scala", "Java", "Java Script", "Python"};
    CommonElementArray obj = new CommonElementArray();
    obj.findCommonElements(strArray1, strArray2);
  }
  
  public void findCommonElements(String[] strArray1, String[] strArray2) {
    Set<String> set = new HashSet<>();
    List<String> commonElements = new ArrayList<String>();
    // Add elements of first array in HashSet
    for(String s: strArray1) {
      set.add(s);
    }
    
    for(String s: strArray2) {
      // check element (of second array) is already in the set
      // if yes that means a common element, store it in a list
      if(set.contains(s))
        commonElements.add(s);
    }
    System.out.println("Common elements are- " + commonElements);
  }
}

Output

Common elements are- [Scala, Java]

Time and Space Complexity of This Approach

If first array has n elements and second array has m elements. Then adding all the elements of the first array to the Set takes O(n) time because adding element to the HashSet is O(1) thus for n elements it is O(n).

Verifying that element is already there or not using contains is O(1) operation. So, for m elements it is O(m).

So, the total time complexity is O(n + m).

Extra space requirement is there for adding n elements in the HashSet and common elements (let's say k) in the List. So, the space complexity is O(n + k)

That's all for this topic How to Find Common Elements Between Two Arrays Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Remove Duplicate Elements From an Array in Java
  2. How to Remove Elements From an Array Java Program
  3. Array in Java
  4. Matrix Addition Java Program
  5. If Given String Sub-Sequence of Another String in Java

You may also like-

  1. Convert String to Byte Array Java Program
  2. Count Number of Times Each Character Appears in a String Java Program
  3. Java Lambda Expression Comparator Example
  4. Java Program to Create Your Own BlockingQueue
  5. AtomicInteger in Java With Examples
  6. New Date And Time API in Java With Examples
  7. How HashMap Works Internally in Java
  8. Spring MessageSource Internationalization (i18n) Support

KMP Algorithm For Pattern Search - Java Program

In this post we'll see how to write program in Java for KMP algorithm.

The KMP (Knuth-Morris-Pratt) algorithm is an efficient algorithm for finding occurrences of a pattern string with in a given string. This algorithm does pattern searching in linear time by creating a longest proper prefix which is also a suffix (LPS) array as a preprocessing step. This LPS array helps in reducing redundant comparisons.

Refer this post to learn more about "longest proper prefix which is also a suffix of a given string" algorithm and its Java implementation- Longest Prefix Suffix Java Program

To understand KMP algorithm better you should also have idea about pattern searching algorithm using brute force approach. So, first we'll see how to write a Java program for pattern searching algorithm using brute force approach

Pattern searching in a String - Java program (Brute force approach)

In this approach you start from index 0 of the string in an outer loop and then try to match character by character with the pattern string in an inner loop. If there is a mismatch at any point, you start from the next value of i in the outer loop.

public class PatternSearch {

  public static void main(String[] args) {

    String sentence = "abcdeabcdf";
    String word = "abcdf";

    stringPatternSearch(sentence, word);        
  }
  static void stringPatternSearch(String str, String pattern) {
    boolean patternFound = false;
    for(int i = 0; i <= str.length() - pattern.length(); i++) {
      System.out.println("Starting from i " + i);
      int j = 0;
      for(; j < pattern.length(); j++) {
        System.out.println("j value " + j);
        if(str.charAt(i+j) == pattern.charAt(j)) {
          continue;
        }else {
          break;
        }
      }
      if(j == pattern.length()) {
        System.out.println("Found pattern at index " + i);
        patternFound = true;
      }
    }
    if(!patternFound) {
      System.out.println("Pattern not found ");
    }
  }
}
Output
Starting from i 0
j value 0
j value 1
j value 2
j value 3
j value 4
Starting from i 1
j value 0
Starting from i 2
j value 0
Starting from i 3
j value 0
Starting from i 4
j value 0
Starting from i 5
j value 0
j value 1
j value 2
j value 3
j value 4
Found pattern at index 5

As you can see from the output for String as "abcdeabcdf" and pattern as "abcdf", when i=0, there is a match from 0..3 before a mismatch. Then the comparison starts from i=1 and j=0 again.

For String of length n and pattern of length m, in worst case, for each character in String you may match up to m-1 characters before finding a mismatch making the time complexity for this approach as O(n X m).

KMP algorithm for pattern searching - Java Program

KMP algorithm tries to avoid these redundant comparisons as we saw in brute force approach by using the LPS array.

By using LPS array, it can deduce how many characters from the previous match can be reused, avoiding redundant checking, especially with repeated characters.

KMP algorithm steps are as-

  1. Start loop for the String length. 0<=i<=stringlength
  2. Match each character in the String with each character in the pattern string, if character matches, move to the next character in both string and pattern. If match continues for the whole length of the pattern that means pattern is found in the String.
  3. If there is a mismatch-
    • pattern pointer j is not 0 then consult the LPS array to find the previous longest prefix that is also the suffix and move j by that length rather than starting from 0 again.
    • If j= 0, then increment i by 1. So, you don't reset i as done in the brute force approach you keep incrementing it to the next value.

Will try to clarify these conditions with example strings after the code.

public class KMPPatternSearch {

  public static void main(String[] args) {
    String sentence = "abcdeabcdf";
    String word = "abcdf";
    KMPSearch(sentence, word);     
  }
  
static void KMPSearch(String str, String pattern) {
    int patternLength = pattern.length();
    int strLength = str.length();

    // LPS array    
    int lps[] = new int[patternLength];
    // track index for pattern
    int j = 0; 

    // calculate lps array
    computeLPSArray(pattern, patternLength, lps);
    System.out.println("LPS Array- " + Arrays.toString(lps));
    // track index for string
    int i = 0; 
    while (i < strLength) {
      System.out.println("Starting from i " + i + " and j "+ j);
      if (pattern.charAt(j) == str.charAt(i)) {
        j++;
        i++;
        if (j == patternLength) {
          System.out.println("Found pattern at index " + (i - j));
          j = lps[j - 1];
        }
      }           
      // mismatch after j matches
      else {
        // Skip the previously matching characters
        if (j != 0)
          j = lps[j - 1];
        else
          i = i + 1;
      }
    }
  }
  
  static void computeLPSArray(String pattern, int patternLength, int[] lps) {
    int length = 0;
    int i = 1;
    // lps[0] is always 0
    lps[0] = 0;
    while (i < patternLength) {
      if (pattern.charAt(i) == pattern.charAt(length)) {
        lps[i] = ++length;              
        i++;
      } else { 
        if (length != 0) {
          // Use LPS array to find a smaller prefix
          length = lps[length - 1]; 
        } else {
          lps[i] = 0;
          i++;
        }
      }
    }
  }
}
Output
LPS Array- [0, 0, 0, 0, 0]
Starting from i 0 and j 0
Starting from i 1 and j 1
Starting from i 2 and j 2
Starting from i 3 and j 3
Starting from i 4 and j 4
Starting from i 4 and j 0
Starting from i 5 and j 0
Starting from i 6 and j 1
Starting from i 7 and j 2
Starting from i 8 and j 3
Starting from i 9 and j 4
Found pattern at index 5

As you can see from the output for String as "abcdeabcdf" and pattern as "abcdf". The LPS array is [0, 0, 0, 0, 0] as there are no matching prefixes and suffixes.

In the matching logic, when i=0, there is a match from 0..3 before a mismatch. At that point both i and j have value as 4. Since previous index value in LPS is 0 so j becomes 0 but i remains at 4, it is not reset to 1.

If you run with the following parameters-

String sentence = "abababc";
String word = "ababc";

Then the output is-

LPS Array- [0, 0, 1, 2, 0]
Starting from i 0 and j 0
Starting from i 1 and j 1
Starting from i 2 and j 2
Starting from i 3 and j 3
Starting from i 4 and j 4
Starting from i 4 and j 2
Starting from i 5 and j 3
Starting from i 6 and j 4
Found pattern at index 2

The LPS array is [0, 0, 1, 2, 0] because of the matching prefixes and suffixes.

In the matching logic, when i=0, there is a match from 0..3 before a mismatch. At that point both i and j have value as 4.

So, j = lps[j-1] for j = 4 means j will have value lps[3] which is 2. After the mismatch the next comparison will start from j=2, not again from j=0.

This works, because we know the previous longest prefix suffix is "abab" or we can say that because of the previous value in LPS array we know that substring for j=0..1 in the pattern matches the substring for j = 2..3.

So, no need to start from j=0 as suffix "ab" of the matched portion is equal to the "ab" prefix of the pattern.

Time and space complexity of KMP algorithm

For String of length n and pattern of length m, you traverse the pattern to create LPS array. Which means time complexity of O(m).

While searching the pattern string n is traversed once, because of LPS array redundant comparisons are avoided.

Thus, the time complexity of KMP algorithm is O(n+m)

Auxiliary space for the LPS array of size m is required, thus the space complexity of KMP algorithm is O(m).

That's all for this topic KMP Algorithm For Pattern Search - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Find The Longest Palindrome in a Given String
  2. Find All Permutations of a Given String Java Program
  3. If Given String Sub-Sequence of Another String in Java
  4. Convert String to Byte Array Java Program
  5. Removing Spaces Between Words in a String Java Program

You may also like-

  1. How to Find Common Elements Between Two Arrays Java Program
  2. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  3. Difference Between Two Dates in Java
  4. Stack Implementation in Java Using Linked List
  5. Angular Event Binding With Examples
  6. Search Filter Using useSearchParams in React Router
  7. Volatile Keyword in Java With Examples
  8. Interface in Python

Longest Prefix Suffix Java Program

In this post we'll see a Java program to find the length of the longest proper prefix of a given string that is also a suffix of the same string. Proper prefix means a prefix that is not equal to the whole string. For example, proper prefixes of String "abc" are "a", "ab", along with the empty string "" but it doesn't include "abc".

Coming to our requirement of finding the length of the longest proper prefix of a given string that is also a suffix of the same string, here are some examples.

Input is String s = "ababab";
Then output is- 4 as "abab" is the LPS here. 

Input is String s = "aaaaa";
Then output is- 4 as "aaaa" is the LPS here. 

Input is String s = "abcde";
Then output is- 0 as there is no prefix which is a suffix too. 

Input is String s = "aabcdaabc"
Then output is- 4 as "aabc" is the LPS here.

Here 2 ways are given to write Java program for this problem-

  1. Using brute force approach
  2. Using LPS array part of the KMP pattern matching algorithm

1. Length of the longest proper prefix of a given string that is also a suffix- Java program with brute force approach

In this approach you will have to match each possible prefix (0 to n-1 for string of length n) with the same length suffix. If all characters are same then it’s a match and that length becomes the current LPS.

For the program, two pointers r and l are used with r always starting from 0 and l starts from l – i (for 1 <= i < n). if characters at r and l matches then you keep incrementing both r and l. If l becomes equal to n (length of string) that becomes the current LPS.

You can visualize it as this-

Longest Prefix Suffix Java Program

This will be the case when i = 3, at that time r = 0 and l = 7 - 3 = 4. Here len = 7

Here is the Java program

public class LongestPrefixSuffix {

  public static void main(String[] args) {
    //String str = "aabcdaabc";
    String str = "abcdabc";
    System.out.println(getLPSLengthTwoP(str));
    
  }
  
  static int getLPSLengthTwoP(String str) {
    int len = str.length();
    int length = 0;
    // You don't want suffix to reach till 0th char, 
    // thats why i starts from 1
    for(int i = 1; i < len; i++) {
      
      int r = 0;
      int l = len - i;
      
      while(r < i && l < len ){
        
        // if no match then come out of the inner loop
        if(str.charAt(r) != str.charAt(l)) {
          break;
        }
        r++;
        l++;
      }
      // If l goes till the end of the String
      if(l == len)
        length = r;
    }
    return length;
  }
 }
Output
3

The time complexity of this approach is O(n2) as the outer loop traverse the whole string length, whereas inner loop may run i times.

Space complexity of this approach is constant i.e. O(1) as fixed number of integer variables are used.

2. Using LPS array part of the KMP algorithm - Java Program

With in the KMP pattern matching algorithm there is a part to create a longest prefix suffix (LPS) array. What is done in this logic is to traverse the length of the String n (0 to (n-1)) and for each index i you look for the longest prefix that is also a suffix for the substring 0 to i.

For example, if string is "ababcab" then the created LPS array would be- [0, 0, 1, 2, 0, 1, 2]

When i is 2 then there is a LPS of length 1 with in the substring "aba".
When i is 3 then there is a LPS of length 2 with in the substring "abab".
When i is 5 then there is a LPS of length 1 with in the substring "ababca".
When i is 6 then there is a LPS of length 2 with in the substring "ababcab".

The last entry in the created LPS array gives the length of the longest proper prefix which is also a suffix with in the given string.

Here is the Java program

public class LongestPrefixSuffix {

  public static void main(String[] args) {
    String str = "ababccababa";
    //String str = "aaaa";
    System.out.println(computeLPSArray(str));
  }
  
  static int computeLPSArray(String str) {
    int n = str.length();
    int length = 0; // Length of the previous longest prefix suffix
    int[] lps = new int[n];
    int i = 1;
    lps[0] = 0; // lps[0] is always 0
     
    while (i < n) {            
      if (str.charAt(i) == str.charAt(length)) {                 
        lps[i] = ++length;
        i++;
      } else {
        if (length != 0) {
          // Use LPS array to find a smaller prefix
          length = lps[length - 1]; 
        } else {
          // if No common prefix/suffix found
          lps[i] = 0; 
          i++;
        }
      }
    }
    return lps[n-1];
  }
}
Output
3

With in the program this is the part which causes confusion-

if (length != 0) {
  // Use LPS array to find a smaller prefix
  length = lps[length - 1]; 
}

Let's try to visualize it to get proper understanding.

Longest Prefix Suffix Array KMP

When i = 10, for the string of length 11 as shown above, the LPS array at that stage would look like-

[0, 0, 1, 2, 0, 0, 1, 2, 3, 4, 0]

Which means length variable at this time has value 4 and comparison fails for-

str.charAt(i) == str.charAt(length)

which takes the control to else part, that's where there is an optimization to look for the previous longest prefix/suffix by assigning length this way- length = lps[length - 1]; and start matching from there. It works because based on the new value of length, it is guaranteed that the highlighted parts will be same and we can start comparison after that position. Thus the final LPS array with all the elements will look like this-

[0, 0, 1, 2, 0, 0, 1, 2, 3, 4, 3]

Making the longest proper prefix that is also the suffix as 3.

With LPS array, time complexity becomes linear O(n) as there is only one traversal of String and each character may get processed at most two times-

  • Once when i increments.
  • Once when length backtracks due to mismatch

Needs auxiliary space for the LPS array, so the space complexity is O(n).

That's all for this topic Longest Prefix Suffix Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Manacher's Algorithm to Find The Longest Palindrome - Java Program
  2. Find Duplicate Characters in a String With Repetition Count Java Program
  3. Convert String to int in Java
  4. Converting String to Enum Type in Java
  5. Greatest Common Divisor (GCD) of Two Numbers Java Program

You may also like-

  1. Java Program to Create Your Own BlockingQueue
  2. What is In-place Algorithm
  3. Binary Tree Traversal Using Depth First Search Java Program
  4. Binary Search Program in Java
  5. Spring Boot Data JPA Repository Unit Test
  6. Angular Project Structure With File Description
  7. Python Conditional Statement - if, elif, else Statements
  8. useFetcher() Hook in React Router With Example