Find the second most repeated word in a given string

Given an string text which contains many words. Our goal is to find the second most repeated word which is exist in given text. For example.

Example 1
Input : "AA XXY IP WW JR JR VIP JR JT IP"

// Word   Occurrence
// ------------------
// AA       1
// XXY      1
// IP       2  ⥢ [Second most repeated]
// WW       1
// JR       3  
// VIP      1
// JT       1
// -------------
OutPut   : "IP"


Example 2

Input : "data set abc xyz app like abc app abc code data abc app"

// ------------------
// Word   Occurrence
// ------------------
// data     2
// set      1
// abc      4
// xyz      1
// app      3  ⥢ [Second most repeated]
// like     1
// code     1

Output : "app"

In case there is no repeated word simply print a None value. In case more than one second most repeated word present in given text then print first word.

Here given code implementation process.

import java.util.HashMap;
/*
    Java Program for
    Find the second most repeated word in a given string
*/
public class FindWords
{
    public void secondMostRepeated(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(" ");
        String result = "";
        int max = 0;
        int count = 0;
        // 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);
            }
            if (record.get(word[i]) > max)
            {
                // Largest repeated frequency
                max = record.get(word[i]);
            }
        }
        System.out.println("Given Text : " + text);
        // Find second max repeated word
        for (int i = 0; i < word.length; ++i)
        {
            if (record.get(word[i]) < max)
            {
                if (count < record.get(word[i]))
                {
                    result = word[i];
                    count = record.get(word[i]);
                }
            }
        }
        if (count == 0)
        {
            System.out.println("None");
        }
        else
        {
            System.out.println(result);
        }
    }
    public static void main(String[] args)
    {
        FindWords task = new FindWords();
        String text = "data set abc xyz app like abc app abc code data abc app";
        // Test A
        // ------------------
        // Word   Occurrence
        // ------------------
        // data     2
        // set      1
        // abc      4
        // xyz      1
        // app      3  ⥢ [Second most repeated]
        // like     1
        // code     1
        // ---------------------
        // Output : app
        task.secondMostRepeated(text);
        text = "App Data File Data Error File Data Fill";
        // Test B
        // ------------------
        // Word   Occurrence
        // ------------------
        // App     1
        // Data    3
        // File    2  ⥢ [Second most repeated]
        // Error   1
        // Fill    1  
        // ---------------------
        // Output : File
        task.secondMostRepeated(text);
    }
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File

Java solution example 1

Java find second repeated word example 1

Java solution example 2

Java find second repeated word example 2
// Include header file
#include <iostream>
#include <string.h>
#include <unordered_map>

using namespace std;
/*
    C++ Program for
    Find the second most repeated word in a given string
*/
class FindWords
{
    public: void secondMostRepeated(char text[])
    {
        // Get the length
        int n = strlen(text);
        if (n == 0)
        {
            return;
        }
        unordered_map < string, int > record;
        // Collecting words
        char *word = strtok(text, " ");
        string result = "";
        string input = "";
        int max = 0;
        int count = 0;
        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;
            }
            if (record[word] > max)
            {
                // Largest repeated frequency
                max = record[word];
            }
            word = strtok (NULL, " ");
            first = false;
        }
        cout << "Given Text : " << input << endl;

        // Find second max repeated word
        for (auto &info: record)
        {
           
            if (info.second < max)
            {
                if (count < info.second)
                {
                    result = info.first;
                    count = info.second;
                }
            }
        }
        if (count == 0)
        {
            cout << "None" << endl;
        }
        else
        {
            cout << result << endl;
        }
    }
};
int main()
{
    FindWords *task = new FindWords();
    char text1[] = "data set abc xyz app like abc app abc code data abc app";
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    task->secondMostRepeated(text1);
    char text2[] = "App Data File Data Error File Data Fill";
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    task->secondMostRepeated(text2);
    return 0;
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
package main
import ("fmt" 
        "strings")
/*
    Go Program for
    Find the second most repeated word in a given string
*/
type FindWords struct {}
func getFindWords() * FindWords {
    var me *FindWords = &FindWords {}
    return me
}
func(this FindWords) secondMostRepeated(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, " ")
    var result string = ""
    var max int = 0
    var count int = 0
    // 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
        }
        if record[word[i]] > max {
            // Largest repeated frequency
            max = record[word[i]]
        }
    }
    fmt.Println("Given Text : ", text)
    // Find second max repeated word
    for i := 0 ; i < len(word) ; i++ {
        if record[word[i]] < max {
            if count < record[word[i]] {
                result = word[i]
                count = record[word[i]]
            }
        }
    }
    if count == 0 {
        fmt.Println("None")
    } else {
        fmt.Println(result)
    }
}
func main() {
    var task * FindWords = getFindWords()
    var text string = "data set abc xyz app like abc app abc code data abc app"
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    task.secondMostRepeated(text)
    text = "App Data File Data Error File Data Fill"
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    task.secondMostRepeated(text)
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
// Include namespace system
using System;
using System.Collections.Generic;
/*
    Csharp Program for
    Find the second most repeated word in a given string
*/
public class FindWords
{
    public void secondMostRepeated(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(" ");
        String result = "";
        int max = 0;
        int count = 0;
        // 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);
            }
            if (record[word[i]] > max)
            {
                // Largest repeated frequency
                max = record[word[i]];
            }
        }
        Console.WriteLine("Given Text : " + text);
        // Find second max repeated word
        for (int i = 0; i < word.Length; ++i)
        {
            if (record[word[i]] < max)
            {
                if (count < record[word[i]])
                {
                    result = word[i];
                    count = record[word[i]];
                }
            }
        }
        if (count == 0)
        {
            Console.WriteLine("None");
        }
        else
        {
            Console.WriteLine(result);
        }
    }
    public static void Main(String[] args)
    {
        FindWords task = new FindWords();
        String text = "data set abc xyz app like abc app abc code data abc app";
        // Test A
        // ------------------
        // Word   Occurrence
        // ------------------
        // data     2
        // set      1
        // abc      4
        // xyz      1
        // app      3  ⥢ [Second most repeated]
        // like     1
        // code     1
        // ---------------------
        // Output : app
        task.secondMostRepeated(text);
        text = "App Data File Data Error File Data Fill";
        // Test B
        // ------------------
        // Word   Occurrence
        // ------------------
        // App     1
        // Data    3
        // File    2  ⥢ [Second most repeated]
        // Error   1
        // Fill    1  
        // ---------------------
        // Output : File
        task.secondMostRepeated(text);
    }
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
<?php
/*
    Php Program for
    Find the second most repeated word in a given string
*/
class FindWords
{
    public  function secondMostRepeated($text)
    {
        // Get the length
        $n = strlen($text);
        if ($n == 0)
        {
            return;
        }
        $record = array();
        // Collecting words
        $word = explode(" ", $text);
        $result = "";
        $max = 0;
        $count = 0;
        // 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;
            }
            if ($record[$word[$i]] > $max)
            {
                // Largest repeated frequency
                $max = $record[$word[$i]];
            }
        }
        echo("Given Text : ".$text.
            "\n");
        // Find second max repeated word
        for ($i = 0; $i < count($word); ++$i)
        {
            if ($record[$word[$i]] < $max)
            {
                if ($count < $record[$word[$i]])
                {
                    $result = $word[$i];
                    $count = $record[$word[$i]];
                }
            }
        }
        if ($count == 0)
        {
            echo("None".
                "\n");
        }
        else
        {
            echo($result.
                "\n");
        }
    }
}

function main()
{
    $task = new FindWords();
    $text = "data set abc xyz app like abc app abc code data abc app";
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    $task->secondMostRepeated($text);
    $text = "App Data File Data Error File Data Fill";
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    $task->secondMostRepeated($text);
}
main();

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
/*
    Node JS Program for
    Find the second most repeated word in a given string
*/
class FindWords
{
    secondMostRepeated(text)
    {
        // Get the length
        var n = text.length;
        if (n == 0)
        {
            return;
        }
        var record = new Map();
        // Collecting words
        var word = text.split(" ");
        var result = "";
        var max = 0;
        var count = 0;
        // 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);
            }
            if (record.get(word[i]) > max)
            {
                // Largest repeated frequency
                max = record.get(word[i]);
            }
        }
        console.log("Given Text : " + text);
        // Find second max repeated word
        for (var i = 0; i < word.length; ++i)
        {
            if (record.get(word[i]) < max)
            {
                if (count < record.get(word[i]))
                {
                    result = word[i];
                    count = record.get(word[i]);
                }
            }
        }
        if (count == 0)
        {
            console.log("None");
        }
        else
        {
            console.log(result);
        }
    }
}

function main()
{
    var task = new FindWords();
    var text = "data set abc xyz app like abc app abc code data abc app";
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    task.secondMostRepeated(text);
    text = "App Data File Data Error File Data Fill";
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    task.secondMostRepeated(text);
}
main();

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
#    Python 3 Program for
#    Find the second most repeated word in a given string
class FindWords :
    def secondMostRepeated(self, text) :
        #  Get the length
        n = len(text)
        if (n == 0) :
            return
        
        record = dict()
        #  Collecting words
        word = text.split(" ")
        result = ""
        max = 0
        count = 0
        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
            
            if (record.get(word[i]) > max) :
                #  Largest repeated frequency
                max = record.get(word[i])
            
            i += 1
        
        print("Given Text : ", text)
        i = 0
        #  Find second max repeated word
        while (i < len(word)) :
            if (record.get(word[i]) < max) :
                if (count < record.get(word[i])) :
                    result = word[i]
                    count = record.get(word[i])
                
            
            i += 1
        
        if (count == 0) :
            print("None")
        else :
            print(result)
        
    

def main() :
    task = FindWords()
    text = "data set abc xyz app like abc app abc code data abc app"
    #  Test A
    #  ------------------
    #  Word   Occurrence
    #  ------------------
    #  data     2
    #  set      1
    #  abc      4
    #  xyz      1
    #  app      3  ⥢ [Second most repeated]
    #  like     1
    #  code     1
    #  ---------------------
    #  Output : app
    task.secondMostRepeated(text)
    text = "App Data File Data Error File Data Fill"
    #  Test B
    #  ------------------
    #  Word   Occurrence
    #  ------------------
    #  App     1
    #  Data    3
    #  File    2  ⥢ [Second most repeated]
    #  Error   1
    #  Fill    1  
    #  ---------------------
    #  Output : File
    task.secondMostRepeated(text)

if __name__ == "__main__": main()

Output

Given Text :  data set abc xyz app like abc app abc code data abc app
app
Given Text :  App Data File Data Error File Data Fill
File
#    Ruby Program for
#    Find the second most repeated word in a given string
class FindWords 
    def secondMostRepeated(text) 
        #  Get the length
        n = text.length
        if (n == 0) 
            return
        end

        record = Hash.new()
        #  Collecting words
        word = text.split(" ")
        result = ""
        max = 0
        count = 0
        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

            if (record[word[i]] > max) 
                #  Largest repeated frequency
                max = record[word[i]]
            end

            i += 1
        end

        print("Given Text : ", text, "\n")
        i = 0
        #  Find second max repeated word
        while (i < word.length) 
            if (record[word[i]] < max) 
                if (count < record[word[i]]) 
                    result = word[i]
                    count = record[word[i]]
                end

            end

            i += 1
        end

        if (count == 0) 
            print("None", "\n")
        else
 
            print(result, "\n")
        end

    end

end

def main() 
    task = FindWords.new()
    text = "data set abc xyz app like abc app abc code data abc app"
    #  Test A
    #  ------------------
    #  Word   Occurrence
    #  ------------------
    #  data     2
    #  set      1
    #  abc      4
    #  xyz      1
    #  app      3  ⥢ [Second most repeated]
    #  like     1
    #  code     1
    #  ---------------------
    #  Output : app
    task.secondMostRepeated(text)
    text = "App Data File Data Error File Data Fill"
    #  Test B
    #  ------------------
    #  Word   Occurrence
    #  ------------------
    #  App     1
    #  Data    3
    #  File    2  ⥢ [Second most repeated]
    #  Error   1
    #  Fill    1  
    #  ---------------------
    #  Output : File
    task.secondMostRepeated(text)
end

main()

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
import scala.collection.mutable._;
/*
    Scala Program for
    Find the second most repeated word in a given string
*/
class FindWords()
{
    def secondMostRepeated(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 result: String = "";
        var max: Int = 0;
        var count: Int = 0;
        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);
            }
            if (record.get(word(i)).get > max)
            {
                // Largest repeated frequency
                max = record.get(word(i)).get;
            }
            i += 1;
        }
        println("Given Text : " + text);
        i = 0;
        // Find second max repeated word
        while (i < word.length)
        {
            if (record.get(word(i)).get < max)
            {
                if (count < record.get(word(i)).get)
                {
                    result = word(i);
                    count = record.get(word(i)).get;
                }
            }
            i += 1;
        }
        if (count == 0)
        {
            println("None");
        }
        else
        {
            println(result);
        }
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var task: FindWords = new FindWords();
        var text: String = "data set abc xyz app like abc app abc code data abc app";
        // Test A
        // ------------------
        // Word   Occurrence
        // ------------------
        // data     2
        // set      1
        // abc      4
        // xyz      1
        // app      3  ⥢ [Second most repeated]
        // like     1
        // code     1
        // ---------------------
        // Output : app
        task.secondMostRepeated(text);
        text = "App Data File Data Error File Data Fill";
        // Test B
        // ------------------
        // Word   Occurrence
        // ------------------
        // App     1
        // Data    3
        // File    2  ⥢ [Second most repeated]
        // Error   1
        // Fill    1  
        // ---------------------
        // Output : File
        task.secondMostRepeated(text);
    }
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File
import Foundation;
/*
    Swift 4 Program for
    Find the second most repeated word in a given string
*/
class FindWords
{
    func secondMostRepeated(_ 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 result: String = "";
        var max: Int = 0;
        var count: Int = 0;
        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;
            }
            if (record[word[i]]! > max)
            {
                // Largest repeated frequency
                max = record[word[i]]!;
            }
            i += 1;
        }
        print("Given Text : ", text);
        i = 0;
        // Find second max repeated word
        while (i < word.count)
        {
            if (record[word[i]]! < max)
            {
                if (count < record[word[i]]!)
                {
                    result = word[i];
                    count = record[word[i]]!;
                }
            }
            i += 1;
        }
        if (count == 0)
        {
            print("None");
        }
        else
        {
            print(result);
        }
    }
}
func main()
{
    let task: FindWords = FindWords();
    var text: String = "data set abc xyz app like abc app abc code data abc app";
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    task.secondMostRepeated(text);
    text = "App Data File Data Error File Data Fill";
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    task.secondMostRepeated(text);
}
main();

Output

Given Text :  data set abc xyz app like abc app abc code data abc app
app
Given Text :  App Data File Data Error File Data Fill
File
/*
    Kotlin Program for
    Find the second most repeated word in a given string
*/
class FindWords
{
    fun secondMostRepeated(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
        val word = text.split(" ");
        var result: String = "";
        var max: Int = 0;
        var count: Int = 0;
        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);
            }
            if (record.getValue(word[i]) > max)
            {
                // Largest repeated frequency
                max = record.getValue(word[i]);
            }
            i += 1;
        }
        println("Given Text : " + text);
        i = 0;
        // Find second max repeated word
        while (i < word.count())
        {
            if (record.getValue(word[i]) < max)
            {
                if (count < record.getValue(word[i]))
                {
                    result = word[i];
                    count = record.getValue(word[i]);
                }
            }
            i += 1;
        }
        if (count == 0)
        {
            println("None");
        }
        else
        {
            println(result);
        }
    }
}
fun main(args: Array < String > ): Unit
{
    val task: FindWords = FindWords();
    var text: String = "data set abc xyz app like abc app abc code data abc app";
    // Test A
    // ------------------
    // Word   Occurrence
    // ------------------
    // data     2
    // set      1
    // abc      4
    // xyz      1
    // app      3  ⥢ [Second most repeated]
    // like     1
    // code     1
    // ---------------------
    // Output : app
    task.secondMostRepeated(text);
    text = "App Data File Data Error File Data Fill";
    // Test B
    // ------------------
    // Word   Occurrence
    // ------------------
    // App     1
    // Data    3
    // File    2  ⥢ [Second most repeated]
    // Error   1
    // Fill    1  
    // ---------------------
    // Output : File
    task.secondMostRepeated(text);
}

Output

Given Text : data set abc xyz app like abc app abc code data abc app
app
Given Text : App Data File Data Error File Data Fill
File


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