Last active
October 17, 2017 08:42
-
-
Save zeagord/346ef31ce3081143344b79f512e0bddb to your computer and use it in GitHub Desktop.
Find First Unique String in an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
/** | |
* Created by rg3 on 10/17/17. | |
*/ | |
public class UniqueStringTask { | |
private static String findFirstUnique(String ...names){ | |
if (names.length ==0) { // Check for empty array | |
return "No names found"; | |
} else if (names.length ==1) { // Only one names present | |
return names[0]; | |
} else if (names.length==2) { //When there are two names | |
if (names[0].equals(names[1])){ | |
return "No unique names"; | |
} else { | |
return names[0]; | |
} | |
} else { // When there are more than two names | |
// LinkedHashMap maintains insertion order | |
Map<String, Integer> namesMapCount = new LinkedHashMap<String, Integer>(); | |
for (String name: names) { | |
if (!namesMapCount.containsKey(name)) { | |
namesMapCount.put(name, 1); | |
} else { | |
namesMapCount.put(name, namesMapCount.get(name) + 1); | |
} | |
} | |
System.out.println(namesMapCount); | |
for (String name: names) { | |
if (namesMapCount.get(name) == 1) { | |
return name; | |
} | |
} | |
} | |
return "No unique names"; | |
} | |
public static void main(String ...args){ | |
System.out.println(findFirstUnique(new String[] {"Alan", "Dan", "Raj", "Umar", "Alan", "Raj"})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment