Find Common Strings from Two Arrays

Comparing two arrays to find common elements is a common programming challenge, often used in search algorithms, database queries, and data processing. Using different techniques, this article will demonstrate efficient ways to find common strings from two arrays.

Understanding the Problem

Given two arrays of strings, we need to identify strings that appear in both arrays.

Example:

Approach to Solve the Problem

We can solve this problem using different approaches:

  1. Brute Force (Nested Loops) – Simple but inefficient for large arrays.
  2. Using a HashSet (Efficient Approach) – Uses set operations for quick lookups.
  3. Using Java Streams (Modern Functional Approach) – Uses functional programming to filter common elements.

1. Brute Force (Using Nested Loops)

Here is the Brute Force (Nested Loops) approach to finding common strings from two arrays in Java.

package com.javacodepoint.stringarray;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

public class CommonStringsBruteForce {

	// Method to find common strings using nested loops
	public static String[] findCommonStrings(String[] array1, String[] array2) {
		List<String> commonStrings = new ArrayList<>();

		for (String word1 : array1) {
			for (String word2 : array2) {
				if (word1.equals(word2)) { // Check if both words are the same
					if (!commonStrings.contains(word1)) { // Avoid duplicates
						commonStrings.add(word1);
					}
				}
			}
		}

		return commonStrings.toArray(new String[0]); // Convert List to Array
	}

	public static void main(String[] args) {
		String[] array1 = { "apple", "banana", "grape", "orange" };
		String[] array2 = { "mango", "banana", "apple", "peach" };

		// Find and print common strings
		String[] commonWords = findCommonStrings(array1, array2);
		System.out.println("Common Strings: " + Arrays.toString(commonWords));
	}
}

2. Using HashSet (efficient approach)

package com.javacodepoint.stringarray;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class CommonStringsFinder {

	// Method to find common strings using HashSet
	public static String[] findCommonStrings(String[] array1, String[] array2) {
		Set<String> set1 = new HashSet<>(Arrays.asList(array1));
		Set<String> commonStrings = new HashSet<>();

		for (String word : array2) {
			if (set1.contains(word)) {
				commonStrings.add(word);
			}
		}

		return commonStrings.toArray(new String[0]); // Convert Set to Array
	}

	public static void main(String[] args) {
		String[] array1 = { "apple", "banana", "grape", "orange" };
		String[] array2 = { "mango", "banana", "apple", "peach" };

		// Find and print common strings
		String[] commonWords = findCommonStrings(array1, array2);
		System.out.println("Common Strings: " + Arrays.toString(commonWords));
	}
}

3. Using Java Streams (Modern Functional Approach)

package com.javacodepoint.stringarray;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class CommonStringsUsingStreams {
	public static void main(String[] args) {
		String[] array1 = { "apple", "banana", "grape", "orange" };
		String[] array2 = { "mango", "banana", "apple", "peach" };

		Set<String> set1 = new HashSet<>(Arrays.asList(array1));

		// Find common elements using Streams
		Set<String> commonWords = Arrays.stream(array2).filter(set1::contains).collect(Collectors.toSet());

		System.out.println("Common Strings: " + commonWords);
	}
}

Time Complexity Analysis

ApproachTime ComplexitySpace Complexity
Brute Force (Nested Loops)O(N * M)O(1)
Using HashSetO(N + M)O(N)
Using Streams & HashSetO(N + M)O(N)

Conclusion

Finding common strings between two arrays is a fundamental problem that can be solved efficiently using:

  • Brute Force (Simple, but slow for large arrays).
  • HashSet Approach (Best performance, O(N) time complexity).
  • Streams API (Concise & Modern Functional Approach).

The HashSet-based approach is the best choice for performance, while Streams API provides a cleaner, functional way to solve the problem.

You can learn the Top 20 string array programs for interview preparation (Click here).

Java logical programs list


Java Basic Programs

Java String Programs

Java String Array Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *