How To Abide By Duplicate Words Inward Coffee String? [Solution]
Problem : Write a Java programme to impress the duplicate words from a given disceptation e.g. if given String is "Java together with JavaScript are totally different, JavaScript follows Java" so your programme should impress "Java" together with "JavaScript" because those ii are 2 duplicate words from given String. You demand to consider all cases e.g. given String tin dismiss live on null, empty, may or may non comprise whatever duplicate words, but for simplicity, yous tin dismiss assume that judgement volition ever inwards English linguistic communication together with exclusively utilization ASCII characters, alphabets, together with numerals, no especial character. It's ameliorate to larn the requirement correct of the work inwards the showtime fifty-fifty if the interviewer doesn't say yous everything. Directly jumping into solution without quest a distich of questions may non become good amongst many interviewers who looks for item oriented candidates.
If yous are practicing these coding problems for an interview, I besides advise yous accept a seem at Cracking the Coding Interview book. It contains 150 Programming Questions together with their Solutions, which is expert plenty to clear most of the beginner together with intermediate programming undertaking interviews.
Solution : In companionship to uncovering duplicate words, nosotros firstly demand to split upwards the judgement into words. For that, yous tin dismiss split the String on infinite using a greedy regular expression, so that it tin dismiss guide hold multiple white spaces betwixt words. You tin dismiss utilization the split() method of java.lang.String cast to produce that, this method returns an array of words.
Once nosotros listing of words, nosotros tin dismiss insert them into HashSet. Since HashSet doesn't permit duplicate together with its add() method render imitation if an object already exists inwards HashSet, nosotros tin dismiss uncovering all duplicate words. Just loop over array, insert them into HashSet using add() method, banking concern agree output of add() method. If add() returns imitation so it's a duplicate, impress that give-and-take to the console.
This is besides i of the top twenty String based problems from interviews. You tin dismiss run across that article to to a greater extent than coding problems based upon String.
One of the follow-up questions of this is how produce yous uncovering a divulge of times each duplicate give-and-take has appeared inwards a sentence? For example, inwards our coding problem, your solution should besides impress count of both Java together with JavaScript e.g. Java : 2 together with JavaScript : 2 because they guide hold appeared twice inwards a sentence.
You tin dismiss solve this work yesteryear choosing around other hash-based information construction similar a hash table, which maintains telephone commutation value pair. Java provides several implementation of hash tabular array information construction e.g. HashMap, Hashtable, together with ConcurrentHashMap, but for full general purpose, HashMap is expert enough.
In short, but utilization HashMap instead of HashSet to snuff it along count of duplicate words inwards the sentence. This is besides similar to the work of finding duplicate characters inwards String. Instead of character, yous demand to uncovering duplicate words, equally shown here.
Another follow-up inquiry related to this work is how produce yous take away duplicate words from String inwards Java? Which is genuinely the same work of removing duplicate elements from an array? If yous know how to solve that, yous tin dismiss easily solve this i equally well. If yous human face upwards whatever problem, see this solution.
From the output it's clear that our programme is working equally expected, It correct prints that "two" is the exclusively duplicate give-and-take inwards given String. Nonetheless, nosotros are going to write around unit of measurement essay to farther essay our solution for unlike input values.
That's all close how to uncovering duplicate words inwards a given String inwards Java. We guide hold used HashSet information construction to solve this work together with our solution has fourth dimension together with infinite complexity of O(n). For a curious developer, tin dismiss yous come upwards up amongst a solution amongst ameliorate fourth dimension together with infinite complexity? How close a solution amongst fourth dimension complexity inwards companionship of O(k) where k is duplicate words? or O(logN)?
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2
If yous are practicing these coding problems for an interview, I besides advise yous accept a seem at Cracking the Coding Interview book. It contains 150 Programming Questions together with their Solutions, which is expert plenty to clear most of the beginner together with intermediate programming undertaking interviews.
Solution : In companionship to uncovering duplicate words, nosotros firstly demand to split upwards the judgement into words. For that, yous tin dismiss split the String on infinite using a greedy regular expression, so that it tin dismiss guide hold multiple white spaces betwixt words. You tin dismiss utilization the split() method of java.lang.String cast to produce that, this method returns an array of words.
Once nosotros listing of words, nosotros tin dismiss insert them into HashSet. Since HashSet doesn't permit duplicate together with its add() method render imitation if an object already exists inwards HashSet, nosotros tin dismiss uncovering all duplicate words. Just loop over array, insert them into HashSet using add() method, banking concern agree output of add() method. If add() returns imitation so it's a duplicate, impress that give-and-take to the console.
This is besides i of the top twenty String based problems from interviews. You tin dismiss run across that article to to a greater extent than coding problems based upon String.
One of the follow-up questions of this is how produce yous uncovering a divulge of times each duplicate give-and-take has appeared inwards a sentence? For example, inwards our coding problem, your solution should besides impress count of both Java together with JavaScript e.g. Java : 2 together with JavaScript : 2 because they guide hold appeared twice inwards a sentence.
You tin dismiss solve this work yesteryear choosing around other hash-based information construction similar a hash table, which maintains telephone commutation value pair. Java provides several implementation of hash tabular array information construction e.g. HashMap, Hashtable, together with ConcurrentHashMap, but for full general purpose, HashMap is expert enough.
In short, but utilization HashMap instead of HashSet to snuff it along count of duplicate words inwards the sentence. This is besides similar to the work of finding duplicate characters inwards String. Instead of character, yous demand to uncovering duplicate words, equally shown here.
Another follow-up inquiry related to this work is how produce yous take away duplicate words from String inwards Java? Which is genuinely the same work of removing duplicate elements from an array? If yous know how to solve that, yous tin dismiss easily solve this i equally well. If yous human face upwards whatever problem, see this solution.
Java Program to uncovering duplicate words inwards String
Here is our solution to the work of finding duplicate words inwards a judgement inwards Java. I guide hold used HashSet to uncovering duplicates. The fourth dimension complexity of this solution is O(n) because nosotros demand to iterate over all chemical factor inwards the array. You besides demand a buffer of the same size equally master array, hence, the infinite complexity is besides O(n), so it may non live on suitable for a genuinely long String. You demand to a greater extent than retention to uncovering fifty-fifty a unmarried duplicate give-and-take if your String is huge.import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * Java Program to demonstrate how to uncovering duplicate words inwards String. */ public class DuplicateWordsInString{ public static void main(String[] args) { String test = "This judgement contains ii words, i together with two"; Set<String> duplicates = duplicateWords(test); System.out.println("input : " + test); System.out.println("output : " + duplicates); } /** * Method to uncovering duplicate words inwards a Sentence or String * @param input String * @return laid of duplicate words */ public static Set<String> duplicateWords(String input){ if(input == null || input.isEmpty()){ return Collections.emptySet(); } Set<String> duplicates = new HashSet<>(); String[] words = input.split("\\s+"); Set<String> set = new HashSet<>(); for(String give-and-take : words){ if(!set.add(word)){ duplicates.add(word); } } return duplicates; } } Output : input : This judgement contains ii words, i and ii output : [two]
JUnit tests
Here is my listing of JUnit essay cast for our solution. We are going to essay our solution for empty String, nothing String, String amongst exclusively duplicates, String without whatever duplicates together with String which contains multiple spaces betwixt words. Each JUnit tests i input. If your input laid is large so yous tin dismiss besides consider using parameterized JUnit test.import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.Set; import org.junit.Test; public class DuplicateWordsInStringTest { @Test public void testWithEmptyString(){ Set<String> output = DuplicateWordsInString.duplicateWords(""); assertEquals(Collections.emptySet(), output); } @Test public void testWithNullString(){ Set<String> output = DuplicateWordsInString.duplicateWords(null); assertEquals(Collections.emptySet(), output); } @Test public void testWithDuplicateString(){ Set<String> output = DuplicateWordsInString.duplicateWords("one i one ii two"); assertTrue(output.contains("one")); assertTrue(output.contains("two")); assertTrue(output.size() == 2); } @Test public void testWithOutDuplicates(){ Set<String> output = DuplicateWordsInString.duplicateWords("one ii three"); assertEquals(Collections.emptySet(), output); } @Test public void testWithMultipleSpaceBetweenWord(){ Set<String> output = DuplicateWordsInString.duplicateWords(" i ii iii "); assertEquals(Collections.emptySet(), output); } }
That's all close how to uncovering duplicate words inwards a given String inwards Java. We guide hold used HashSet information construction to solve this work together with our solution has fourth dimension together with infinite complexity of O(n). For a curious developer, tin dismiss yous come upwards up amongst a solution amongst ameliorate fourth dimension together with infinite complexity? How close a solution amongst fourth dimension complexity inwards companionship of O(k) where k is duplicate words? or O(logN)?
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2
![How to uncovering duplicate words inwards Java String? [Solution] Write a Java programme to impress the duplicate words from a given disceptation e How to uncovering duplicate words inwards Java String? [Solution]](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_SZC05xKiqtMACTRwbo-GSIyL3h9_qWBcSYKQqlStdEUuvNG21xhHKGk6Pj4Jxlf46neUzMf_XsvxLQyWhyb6Khk6VoG15xKVcVjwiJabJZreAgGhGjj6Ko_7PoPWtgrxLLF70SqpDQac/s320/Cracking+the+coding+interview+6th+Edition.png)
![How to uncovering duplicate words inwards Java String? [Solution] Write a Java programme to impress the duplicate words from a given disceptation e How to uncovering duplicate words inwards Java String? [Solution]](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzhOPaAo0A4CiCMf-yDsxalk8ZHWq78hkd0yindp7bXX88p-Uvcr3i7cE14bw_FNb2dUfWEM_TBMsjnGXtfRRR7yMRBVAWnLSXKyJsP3RtMvfcn-RYF1XmJzaGE-Am557IGMok4tTAMfW6/s320/Coding+Puzzles+Book+for+Interview.jpg)
Komentar
Posting Komentar