Find the first repeated word in a string

Given text which contains many words, Our goal is to find first word which is repeated in given text. For example, find the first repeated word from left to right direction.

Input : "We have 4 gold coins and 5 silver coins make new gold coins"
                     ↑                                      ↑
                     └--------------------------------------┘
Output : "gold"
[Note that here "gold" is first repeated word]

Input : "Launch an app that runs faster and faster than other app okay"
                   ↑                                           ↑
                   └-------------------------------------------┘
Output : "app"

In case there is no repeated word simply print a None value. How to solve this problem question is arising your mind. Hint first split the text into words and find first repeated word.

Here given code implementation process.

import java.util.HashMap;
/*
    Java Program for
    Find the first repeated word in a string
*/
public class FindWords
{
    public void firstRepeatedWord(String text)
    {
        // Get the length
        int n = text.length();
        if (n == 0)
        {
            return;
        }
        HashMap < String, Integer > record = 
          new HashMap < String, Integer > ();
        
        // Collecting words
        String[] word = text.split(" ");

        // Count frequency of given word
        for (int i = 0; i < word.length; ++i)
        {
            if (record.containsKey(word[i]))
            {
                // Increase frequency
                record.put(word[i], record.get(word[i]) + 1);
            }
            else
            {
                // Add new word
                record.put(word[i], 1);
            }
        }
        System.out.println("Given Text : " + text);

        // Find first repeated word
        for (int i = 0; i < word.length; ++i)
        {
            if (record.get(word[i]) > 1)
            {
                // Display first repeated word
                System.out.println(word[i]);
                return;
            }
        }
        System.out.println("None");
    }
    public static void main(String[] args)
    {
        FindWords task = new FindWords();
        String text = "Launch an app that runs faster and faster than other app";
        // Test A
        // "Launch an app that runs faster and faster than other app okay"
        //             ↑                                          ↑
        //             └------------------------------------------┘    
        task.firstRepeatedWord(text);
        text = "App Data Code Error Cdoe Data Fill";
        // Test B
        // "App Data Code Error Cdoe Data Fill"
        //        ↑                    ↑
        //        └--------------------┘  
        task.firstRepeatedWord(text);
    }
}

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data

Implementing Example 1 in java

Java find first repeated word example 1

Implementing Example 2 in java

Java find first repeated word example 2
// Include header file
#include <iostream>
#include <string.h>
#include <unordered_map>
#include <vector>
using namespace std;
/*
    C++ Program for
    Find the first repeated word in a string
*/
class FindWords
{
    public: void firstRepeatedWord(char text[])
    {
        // Get the length
        int n = strlen(text);

        if (n == 0)
        {
            return;
        }
        unordered_map < string, int > record;
        // Collecting words
        char *word  = strtok(text, " ");
        vector <string> data;
        char *check = word;
        string result = "";
        string input = "";
        bool first = true;
        // Count frequency of given word
        while (word != NULL)
        {
            if(first == false)
            {
                input += " ";
            }
            input += word;

            if (record.find(word) != record.end())
            {
                // Increase frequency
                record[word] = record[word] + 1;
            }
            else
            {
                // Add new word
                record[word] = 1;
            }
            data.push_back(word);
            word = strtok (NULL, " ");
            first = false;
        }
  
        cout << " Input : "<< input << endl;


        // Find first repeated word
        for (int i = 0; i < data.size(); ++i)
        {
            if (record[data[i]] > 1)
            {
                // Display first repeated word
                cout << "  " << data[i] << endl;
                return;
            }
        }
 
        cout << " None" << endl;
    }
};
int main()
{
    FindWords *task = new FindWords();
    char text1[] = "Launch an app that runs faster and faster than other app";
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    task->firstRepeatedWord(text1);
    char text2[]  = "App Data Code Error Cdoe Data Fill";
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    task->firstRepeatedWord(text2);
    return 0;
}

Output

 Input : Launch an app that runs faster and faster than other app
  app
 Input : App Data Code Error Cdoe Data Fill
  Data
package main
import "fmt"
import "strings"
/*
    Go Program for
    Find the first repeated word in a string
*/
type FindWords struct {}
func getFindWords() * FindWords {
    var me *FindWords = &FindWords {}
    return me
}
func(this FindWords) firstRepeatedWord(text string) {
    // Get the length
    var n int = len(text)
    if n == 0 {
        return
    }
    var record = make(map[string] int)
    // Collecting words
    var word = strings.Split(text, " ")
    // Count frequency of given word
    for i := 0 ; i < len(word) ; i++ {
        if _, found := record[word[i]] ; found {
            // Increase frequency
            record[word[i]] = record[word[i]] + 1
        } else {
            // Add new word
            record[word[i]] = 1
        }
    }
    fmt.Println("Given Text : ", text)
    // Find first repeated word
    for i := 0 ; i < len(word) ; i++ {
        if record[word[i]] > 1 {
            // Display first repeated word
            fmt.Println(word[i])
            return
        }
    }
    fmt.Println("None")
}
func main() {
    var task * FindWords = getFindWords()
    var text string = "Launch an app that runs faster and faster than other app"
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    task.firstRepeatedWord(text)
    text = "App Data Code Error Cdoe Data Fill"
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    task.firstRepeatedWord(text)
}

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp Program for
    Find the first repeated word in a string
*/
public class FindWords
{
    public void firstRepeatedWord(String text)
    {
        // Get the length
        int n = text.Length;
        if (n == 0)
        {
            return;
        }
        Dictionary < string, int > record = 
          new Dictionary < string, int > ();
        // Collecting words
        String[] word = text.Split(" ");
        // Count frequency of given word
        for (int i = 0; i < word.Length; ++i)
        {
            if (record.ContainsKey(word[i]))
            {
                // Increase frequency
                record[word[i]] = record[word[i]] + 1;
            }
            else
            {
                // Add new word
                record.Add(word[i], 1);
            }
        }
        Console.WriteLine("Given Text : " + text);
        // Find first repeated word
        for (int i = 0; i < word.Length; ++i)
        {
            if (record[word[i]] > 1)
            {
                // Display first repeated word
                Console.WriteLine(word[i]);
                return;
            }
        }
        Console.WriteLine("None");
    }
    public static void Main(String[] args)
    {
        FindWords task = new FindWords();
        String text = "Launch an app that runs faster and faster than other app";
        // Test A
        // "Launch an app that runs faster and faster than other app okay"
        //             ↑                                          ↑
        //             └------------------------------------------┘    
        task.firstRepeatedWord(text);
        text = "App Data Code Error Cdoe Data Fill";
        // Test B
        // "App Data Code Error Cdoe Data Fill"
        //        ↑                    ↑
        //        └--------------------┘  
        task.firstRepeatedWord(text);
    }
}

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
<?php
/*
    Php Program for
    Find the first repeated word in a string
*/
class FindWords
{
    public  function firstRepeatedWord($text)
    {
        // Get the length
        $n = strlen($text);
        if ($n == 0)
        {
            return;
        }
        $record = array();
        // Collecting words
        $word = explode(" ", $text);
        // Count frequency of given word
        for ($i = 0; $i < count($word); ++$i)
        {
            if (array_key_exists($word[$i], $record))
            {
                // Increase frequency
                $record[$word[$i]] = $record[$word[$i]] + 1;
            }
            else
            {
                // Add new word
                $record[$word[$i]] = 1;
            }
        }
        echo("Given Text : ".$text.
            "\n");
        // Find first repeated word
        for ($i = 0; $i < count($word); ++$i)
        {
            if ($record[$word[$i]] > 1)
            {
                // Display first repeated word
                echo($word[$i].
                    "\n");
                return;
            }
        }
        echo("None\n");
    }
}

function main()
{
    $task = new FindWords();
    $text = "Launch an app that runs faster and faster than other app";
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    $task->firstRepeatedWord($text);
    $text = "App Data Code Error Cdoe Data Fill";
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    $task->firstRepeatedWord($text);
}
main();

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
/*
    Node JS Program for
    Find the first repeated word in a string
*/
class FindWords
{
    firstRepeatedWord(text)
    {
        // Get the length
        var n = text.length;
        if (n == 0)
        {
            return;
        }
        var record = new Map();
        // Collecting words
        var word = text.split(" ");
        // Count frequency of given word
        for (var i = 0; i < word.length; ++i)
        {
            if (record.has(word[i]))
            {
                // Increase frequency
                record.set(word[i], record.get(word[i]) + 1);
            }
            else
            {
                // Add new word
                record.set(word[i], 1);
            }
        }
        console.log("Given Text : " + text);
        // Find first repeated word
        for (var i = 0; i < word.length; ++i)
        {
            if (record.get(word[i]) > 1)
            {
                // Display first repeated word
                console.log(word[i]);
                return;
            }
        }
        console.log("None");
    }
}

function main()
{
    var task = new FindWords();
    var text = "Launch an app that runs faster and faster than other app";
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    task.firstRepeatedWord(text);
    text = "App Data Code Error Cdoe Data Fill";
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    task.firstRepeatedWord(text);
}
main();

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
#    Python 3 Program for
#    Find the first repeated word in a string
class FindWords :
    def firstRepeatedWord(self, text) :
        #  Get the length
        n = len(text)
        if (n == 0) :
            return
        
        record = dict()
        #  Collecting words
        word = text.split(" ")
        i = 0
        #  Count frequency of given word
        while (i < len(word)) :
            if ((word[i] in record.keys())) :
                #  Increase frequency
                record[word[i]] = record.get(word[i]) + 1
            else :
                #  Add new word
                record[word[i]] = 1
            
            i += 1
        
        print("Given Text : ", text)
        i = 0
        #  Find first repeated word
        while (i < len(word)) :
            if (record.get(word[i]) > 1) :
                #  Display first repeated word
                print(word[i])
                return
            
            i += 1
        
        print("None")
    

def main() :
    task = FindWords()
    text = "Launch an app that runs faster and faster than other app"
    #  Test A
    #  "Launch an app that runs faster and faster than other app okay"
    #              ↑                                          ↑
    #              └------------------------------------------┘    
    task.firstRepeatedWord(text)
    text = "App Data Code Error Cdoe Data Fill"
    #  Test B
    #  "App Data Code Error Cdoe Data Fill"
    #         ↑                    ↑
    #         └--------------------┘  
    task.firstRepeatedWord(text)

if __name__ == "__main__": main()

Output

Given Text :  Launch an app that runs faster and faster than other app
app
Given Text :  App Data Code Error Cdoe Data Fill
Data
#    Ruby Program for
#    Find the first repeated word in a string
class FindWords 
    def firstRepeatedWord(text) 
        #  Get the length
        n = text.length
        if (n == 0) 
            return
        end

        record = Hash.new()
        #  Collecting words
        word = text.split(" ")
        i = 0
        #  Count frequency of given word
        while (i < word.length) 
            if (record.key?(word[i])) 
                #  Increase frequency
                record[word[i]] = record[word[i]] + 1
            else
 
                #  Add new word
                record[word[i]] = 1
            end

            i += 1
        end

        print("Given Text : ", text, "\n")
        i = 0
        #  Find first repeated word
        while (i < word.length) 
            if (record[word[i]] > 1) 
                #  Display first repeated word
                print(word[i], "\n")
                return
            end

            i += 1
        end

        print("None", "\n")
    end

end

def main() 
    task = FindWords.new()
    text = "Launch an app that runs faster and faster than other app"
    #  Test A
    #  "Launch an app that runs faster and faster than other app okay"
    #              ↑                                          ↑
    #              └------------------------------------------┘    
    task.firstRepeatedWord(text)
    text = "App Data Code Error Cdoe Data Fill"
    #  Test B
    #  "App Data Code Error Cdoe Data Fill"
    #         ↑                    ↑
    #         └--------------------┘  
    task.firstRepeatedWord(text)
end

main()

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
import scala.collection.mutable._;
/*
    Scala Program for
    Find the first repeated word in a string
*/
class FindWords()
{
    def firstRepeatedWord(text: String): Unit = {
        // Get the length
        var n: Int = text.length();
        if (n == 0)
        {
            return;
        }
        var record: HashMap[String, Int] = new HashMap[String, Int]();
        // Collecting words
        var word: Array[String] = text.split(" ");
        var i: Int = 0;
        // Count frequency of given word
        while (i < word.length)
        {
            if (record.contains(word(i)))
            {
                // Increase frequency
                record.addOne(word(i), record.get(word(i)).get + 1);
            }
            else
            {
                // Add new word
                record.addOne(word(i), 1);
            }
            i += 1;
        }
        println("Given Text : " + text);
        i = 0;
        // Find first repeated word
        while (i < word.length)
        {
            if (record.get(word(i)).get > 1)
            {
                // Display first repeated word
                println(word(i));
                return;
            }
            i += 1;
        }
        println("None");
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var task: FindWords = new FindWords();
        var text: String = "Launch an app that runs faster and faster than other app";
        // Test A
        // "Launch an app that runs faster and faster than other app okay"
        //             ↑                                          ↑
        //             └------------------------------------------┘    
        task.firstRepeatedWord(text);
        text = "App Data Code Error Cdoe Data Fill";
        // Test B
        // "App Data Code Error Cdoe Data Fill"
        //        ↑                    ↑
        //        └--------------------┘  
        task.firstRepeatedWord(text);
    }
}

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data
import Foundation;
/*
    Swift 4 Program for
    Find the first repeated word in a string
*/
class FindWords
{
    func firstRepeatedWord(_ text: String)
    {
        // Get the length
        let n: Int = text.count;
        if (n == 0)
        {
            return;
        }
        var record: [String : Int] = [String : Int]();
        // Collecting words
        let word: [String] = text.split
        {
            $0 == " "
        }.map(String.init);
        var i: Int = 0;
        // Count frequency of given word
        while (i < word.count)
        {
            if (record.keys.contains(word[i]))
            {
                // Increase frequency
                record[word[i]] = record[word[i]]! + 1;
            }
            else
            {
                // Add new word
                record[word[i]] = 1;
            }
            i += 1;
        }
        print("Given Text : ", text);
        i = 0;
        // Find first repeated word
        while (i < word.count)
        {
            if (record[word[i]]! > 1)
            {
                // Display first repeated word
                print(word[i]);
                return;
            }
            i += 1;
        }
        print("None");
    }
}
func main()
{
    let task: FindWords = FindWords();
    var text: String = "Launch an app that runs faster and faster than other app";
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    task.firstRepeatedWord(text);
    text = "App Data Code Error Cdoe Data Fill";
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    task.firstRepeatedWord(text);
}
main();

Output

Given Text :  Launch an app that runs faster and faster than other app
app
Given Text :  App Data Code Error Cdoe Data Fill
Data
/*
    Kotlin Program for
    Find the first repeated word in a string
*/
class FindWords
{
    fun firstRepeatedWord(text: String): Unit
    {
        // Get the length
        val n: Int = text.length;
        if (n == 0)
        {
            return;
        }
        var record: HashMap < String, Int > = HashMap < String, Int > ();
        // Collecting words
        var word = text.split(" ");
        var i: Int = 0;
        // Count frequency of given word
        while (i < word.count())
        {
            if (record.containsKey(word[i]))
            {
                // Increase frequency
                record.put(word[i], record.getValue(word[i]) + 1);
            }
            else
            {
                // Add new word
                record.put(word[i], 1);
            }
            i += 1;
        }
        println("Given Text : " + text);
        i = 0;
        // Find first repeated word
        while (i < word.count())
        {
            if (record.getValue(word[i]) > 1)
            {
                // Display first repeated word
                println(word[i]);
                return;
            }
            i += 1;
        }
        println("None");
    }
}
fun main(args: Array < String > ): Unit
{
    val task: FindWords = FindWords();
    var text: String = "Launch an app that runs faster and faster than other app";
    // Test A
    // "Launch an app that runs faster and faster than other app okay"
    //             ↑                                          ↑
    //             └------------------------------------------┘    
    task.firstRepeatedWord(text);
    text = "App Data Code Error Cdoe Data Fill";
    // Test B
    // "App Data Code Error Cdoe Data Fill"
    //        ↑                    ↑
    //        └--------------------┘  
    task.firstRepeatedWord(text);
}

Output

Given Text : Launch an app that runs faster and faster than other app
app
Given Text : App Data Code Error Cdoe Data Fill
Data


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved