Find Common Characters in Array of Strings | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given an array of strings (lowercase characters only), write a program to return a list of all characters (including duplicates) which is present in all strings of an array.

For example, if a character occurs 3 times in all strings, then include that character three times in the result.

Example 

Find Common Characters in Array of Strings

Input :- ["cat", "bat", "rat"]
Output :- [a, t]
Input :- ["code", "road"]
Output :- [d, o]

Solution

This problem can be solved in following steps :-

  1. Create two integer array of size 26 (Total number of characters in the English language), One array (count array) will be used to store the frequency of each character in the S string of input array and another array (main array) will be used to store the minimum frequency of each character among all strings of input array. Initialize this array with Integer.MAX_VALUE.
  2. Iterate through the given input array from start (index 0) to end (n-1, where n is the length of an array) and for each iteration convert the string into a character array and assign a frequency of each character to count array.
  3. Iterate through the count array (prepared in the last step) and for each iteration and assign a minimum value between count array and main array to the main array.

Program

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

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		List<String> result = main.commonChars(new String[] {"code","road"});		
		System.out.println(result);					
	}
	
	/* Solution */    
	public List<String> commonChars(String[] A) {        
        int[] array = new int[26];
        int[] main = new int[26];
        Arrays.fill(main,Integer.MAX_VALUE);
        
        char[] temp;        
        for(String string : A){
            temp = string.toCharArray();
            for(int i=0; i<temp.length; i++){
                array[temp[i] - 'a']++;
            }
            for(int i = 0; i<26; i++){
                main[i] = Math.min(main[i], array[i]);
                array[i] = 0;
            }
        }
        
        List<String> result = new ArrayList<>();
        for(int i=0; i<26; i++) {
            while((main[i]--) > 0) {
                result.add((((char)('a' + i))+""));
            }
        }
        return result;        
    }
}

Result

[d, o] 

Similar Post

  1. Duplicate Zeros in Array
  2. Find Peak Element in Array
  3. Peak Index in a Mountain Array

That’s all for Find Common Characters in Array of Strings in Java, If you liked it, please share your thoughts in a comments section and share it with others too.