CC-8 : Find unique and repeating elements in an array.
Description:
Given an input array of String, find the return the list of unique words and the list of repeating words.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| strArray1 = {"listen", "near", "swim", "morning", "listen"}; | Unique Elements : near,swim,morning Repeating Elements : listen |
| strArray = {"peace", "road", "ate", "ate", "tree", "fly", "tree"}; | Unique Elements : fly,road,peace Repeating Array : ate,tree |
Pseudocode:
| The java method should accept following input parameters: arr (String array). |
| Initialize a variable uniqueWords of type HashSet |
| Initialize a variable repeatWords of type HashSet |
| Using a for loop iterate through arr, using idx as a loop variable with initial value 0 and increment idx till it reaches arr1.length-1:
if uniqueWords does not contain arr[idx]:
Add arr[idx] to uniqueWords.
if uniqueWords does contains arr[idx]:
Add arr[idx] to repeatWords.
|
| At completion of above loop, remove all elements of repeatWords from uniqueWords using HashSet.removeAll() method. Now, uniqueWords contains all the unique words and repeatWords contains all the repeated words. |
| Initialize a 2 dimensional String array retVal with 2 rows. |
| Use an iterator to access elements from uniqueWords and add the same to String array retVal[0]. Use another iterator to access elements from repeatWords and add the same to String array retVal[1]. Return retVal. |
Code:
public String[][] setFindUniqueAndRepeating(String[] arr) {
HashSet<String> uniqueWords=new HashSet<String>();
HashSet<String> repeatWords=new HashSet<String>();
for (int idx=0; idx< arr.length; idx++) {
if ( ! uniqueWords.contains(arr[idx])) {
uniqueWords.add(arr[idx]);
}else {
repeatWords.add(arr[idx]);
}
}
uniqueWords.removeAll(repeatWords);
String[][] retVal=new String[2][];
retVal[0]=new String[uniqueWords.size()];
retVal[1]=new String[repeatWords.size()];
int idx=0;
Iterator itr=uniqueWords.iterator();
while (itr.hasNext()) {
retVal[0][idx]=(String)itr.next();
idx++;
}
idx=0;
itr=repeatWords.iterator();
while (itr.hasNext()) {
retVal[1][idx]=(String)itr.next();
idx++;
}
return retVal;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |