Posted on by Kalkicode
Code Hash

Top k frequent words solution

Here given code implementation process.

/*
    Java program for
    Top k frequent words solution
*/
import java.util.HashMap;
import java.util.ArrayList;
public class Occurrence
{
	public void topKfrequent(String[] words, int n, int k)
	{
		HashMap < String, Integer > frequency = new HashMap < String, Integer > ();
		HashMap < Integer, ArrayList < String >> result = new HashMap < > ();
		int count = 0;
		for (int i = 0; i < n; i++)
		{
			if (frequency.containsKey(words[i]))
			{
				//when key exist then put new key
				frequency.put(words[i], frequency.get(words[i]) + 1);
			}
			else
			{
				frequency.put(words[i], 1);
			}
		}
		// Combine elements by frequency
		for (String data: frequency.keySet())
		{
			if (result.containsKey(frequency.get(data)))
			{
				result.get(frequency.get(data)).add(data);
			}
			else
			{
				result.put(frequency.get(data), new ArrayList < String > ());
				result.get(frequency.get(data)).add(data);
			}
		}
		System.out.print("  Top " + k + " element is \n");
		for (int i = n - 1; i >= 0; --i)
		{
			if (result.containsKey(i))
			{
				for (String data: result.get(i))
				{
					System.out.print("  " + data);
					count++;
					if (count == k)
					{
						return;
					}
				}
			}
		}
		if (count != k)
		{
			System.out.print(" All top " + k + " element are not exist");
		}
	}
	public static void main(String[] args)
	{
		Occurrence task = new Occurrence();
		String[] words = {
			"good" , "move" , "this" , "free" , 
          "bad" , "good" , "is" , "game" ,
          "is" , "logic" , "move" , "logic" , 
          "code" , "is" , "move" , "game","good"
		};
		int n = words.length;
		int k = 4;
		task.topKfrequent(words, n, k);
	}
}

Output

  Top 4 element is
  move  is  good  game
// Include header file
#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;
class Occurrence
{
	public: void topKfrequent(string words[], int n, int k)
	{
		unordered_map < string, int > frequency;
		unordered_map < int, vector < string > > result;
		int count = 0;
		for (int i = 0; i < n; i++)
		{
			if (frequency.find(words[i]) != frequency.end())
			{
				//when key exist then put new key
				frequency[words[i]] = frequency[words[i]] + 1;
			}
			else
			{
				frequency[words[i]] = 1;
			}
		}
		// Combine elements by frequency
		for (auto &data: frequency)
		{
			if (result.find(data.second) != result.end())
			{
				result[data.second].push_back(data.first);
			}
			else
			{
				result[data.second].push_back(data.first);
			}
		}
		cout << "  Top " << k << " element is \n";
		for (int i = n - 1; i >= 0; --i)
		{
			if (result.find(i) != result.end())
			{
				for (auto &data: result[i])
				{
					cout << "  " << data;
					count++;
					if (count == k)
					{
						return;
					}
				}
			}
		}
		if (count != k)
		{
			cout << " All top " << k << " element are not exist";
		}
	}
};
int main()
{
	Occurrence *task = new Occurrence();
	string words[] = {
		"good" , "move" , "this" , "free" , 
        "bad" , "good" , "is" , "game" , "is" , 
       "logic" , "move" , "logic" , "code" , 
       "is" , "move" , "game", "good"
	};
	int n = sizeof(words) / sizeof(words[0]);
	int k = 4;
	task->topKfrequent(words, n, k);
	return 0;
}

Output

  Top 4 element is
  is  good  move  logic
// Include namespace system
using System;
using System.Collections.Generic;
public class Occurrence
{
	public void topKfrequent(String[] words, int n, int k)
	{
		Dictionary < string, int > frequency = 
          new Dictionary < string, int > ();
		Dictionary < int, List < string >> result = 
          new Dictionary <int, List < string >> ();
		int count = 0;
		for (int i = 0; i < n; i++)
		{
			if (frequency.ContainsKey(words[i]))
			{
				//when key exist then put new key
				frequency[words[i]] = frequency[words[i]] + 1;
			}
			else
			{
				frequency.Add(words[i], 1);
			}
		}
		// Combine elements by frequency
		foreach(KeyValuePair < String, int > data in frequency)
		{
			if (result.ContainsKey(data.Value))
			{
				result[data.Value].Add(data.Key);
			}
			else
			{
				result.Add(data.Value, new List < string > ());
				result[data.Value].Add(data.Key);
			}
		}
		Console.Write("  Top " + k + " element is \n");
		for (int i = n - 1; i >= 0; --i)
		{
			if (result.ContainsKey(i))
			{
				foreach(String data in result[i])
				{
					Console.Write("  " + data);
					count++;
					if (count == k)
					{
						return;
					}
				}
			}
		}
		if (count != k)
		{
			Console.Write(" All top " + k + " element are not exist");
		}
	}
	public static void Main(String[] args)
	{
		Occurrence task = new Occurrence();
		String[] words = {
		  "good" , "move" , "this" , "free" , 
          "bad" , "good" , "is" , "game" , 
          "is" , "logic" , "move" , "logic" , 
          "code" , "is" , "move" , "game", "good"
		};
		int n = words.Length;
		int k = 4;
		task.topKfrequent(words, n, k);
	}
}

Output

  Top 4 element is
  good  move  is  game
package main
import "fmt"
/*
    Go program for
    Top k frequent words solution
*/

func topKfrequent(words[] string, n int, k int) {
	var frequency = make(map[string] int)
	var result = make(map[int] []string)
	var count int = 0
	for i := 0 ; i < n ; i++ {
		if _, found := frequency[words[i]] ; found {
			//when key exist then put new key
			frequency[words[i]] = frequency[words[i]] + 1
		} else {
			frequency[words[i]] = 1
		}
	}
	// Combine elements by frequency
	for k, v := range frequency {
		if _, found := result[v] ; found {
			result[v] = append(result[v], k)
		} else {
			result[v] = make([]string,0)
			result[v] = append(result[v], k)
		}
	}
	fmt.Print("  Top ", k, " element is \n")
	for i := n - 1 ; i >= 0 ; i-- {
		if _, found := result[i] ; found {
			for _, v := range result[i] {
				fmt.Print("  ", v)
				count++
				if count == k {
					return
				}
			}
		}
	}
	if count != k {
		fmt.Print(" All top ", k, " element are not exist")
	}
}
func main() {
	
	var words = [] string {"good",
		"move",
		"this",
		"free",
		"bad",
		"good",
		"is",
		"game",
		"is",
		"logic",
		"move",
		"logic",
		"code",
		"is",
		"move",
		"game",
		"good"}
	var n int = len(words)
	var k int = 4
	topKfrequent(words, n, k)
}

Output

Top 4 element is 
  move  is  good  logic
<?php
class Occurrence
{
	public	function topKfrequent($words, $n, $k)
	{
		$frequency = array();
		$result = array();
		$count = 0;
		for ($i = 0; $i < $n; $i++)
		{
			if (array_key_exists($words[$i], $frequency))
			{
				//when key exist then put new key
				$frequency[$words[$i]] = $frequency[$words[$i]] + 1;
			}
			else
			{
				$frequency[$words[$i]] = 1;
			}
		}
		// Combine elements by frequency
		foreach($frequency as $key => $value)
		{
			if (array_key_exists($value, $result))
			{
				$result[$value][] = $key;
			}
			else
			{
				$result[$value] = array();
				$result[$value][] = $key;
			}
		}
		echo("  Top ".$k." element is \n");
		for ($i = $n - 1; $i >= 0; --$i)
		{
			if (array_key_exists($i, $result))
			{
				foreach($result[$i] as $key => $value)
				{
					echo("  ".$value);
					$count++;
					if ($count == $k)
					{
						return;
					}
				}
			}
		}
		if ($count != $k)
		{
			echo(" All top ".$k.
				" element are not exist");
		}
	}
}

function main()
{
	$task = new Occurrence();
	$words = array("good", "move", "this", "free", 
                   "bad", "good", "is", "game", "is", 
                   "logic", "move", "logic", "code", 
                   "is", "move", "game", "good");
	$n = count($words);
	$k = 4;
	$task->topKfrequent($words, $n, $k);
}
main();

Output

  Top 4 element is
  good  move  is  game
class Occurrence
{
	topKfrequent(words, n, k)
	{
		var frequency = new Map();
		var result = new Map();
		var count = 0;
		for (var i = 0; i < n; i++)
		{
			if (frequency.has(words[i]))
			{
				//when key exist then put new key
				frequency.set(words[i], frequency.get(words[i]) + 1);
			}
			else
			{
				frequency.set(words[i], 1);
			}
		}
		// Combine elements by frequency
		for (let [key, value] of frequency)
		{
			if (result.has(value))
			{
				result.get(value).push(key);
			}
			else
			{
				result.set(value, []);
				result.get(value).push(key);
			}
		}
		process.stdout.write("  Top " + k + " element is \n");
		for (var i = n - 1; i >= 0; --i)
		{
			if (result.has(i))
			{
				for (let data of result.get(i) )
				{
					process.stdout.write("  " + data);
					count++;
					if (count == k)
					{
						return;
					}
				}
			}
		}
		if (count != k)
		{
			process.stdout.write(" All top " + k + " element are not exist");
		}
	}
}

function main()
{
	var task = new Occurrence();
	var words = ["good", "move", "this", "free", 
                 "bad", "good", "is", "game", "is", 
                 "logic", "move", "logic", "code", 
                 "is", "move", "game", "good"];
	var n = words.length;
	var k = 4;
	task.topKfrequent(words, n, k);
}
main();

Output

  Top 4 element is
  good  move  is  game
#    Python 3 program for
#    Top k frequent words solution
class Occurrence :
	def topKfrequent(self, words, n, k) :
		frequency = dict()
		result = dict()
		count = 0
		i = 0
		while (i < n) :
			if ((words[i] in frequency.keys())) :
				# when key exist then put new key
				frequency[words[i]] = frequency.get(words[i]) + 1
			else :
				frequency[words[i]] = 1
			
			i += 1
		
		for key, value in frequency.items() :
			if ((value in result.keys())) :
				result.get(value).append(key)
			else :
				result[value] = []
				result.get(value).append(key)
			
		
		print("  Top ", k ," element is ")
		i = n - 1
		while (i >= 0) :
			if ((i in result.keys())) :
				for data in result.get(i) :
					print(" ", data, end = "")
					count += 1
					if (count == k) :
						return
					
				
			
			i -= 1
		
		if (count != k) :
			print(" All top ", k ," element are not exist", end = "")
		
	

def main() :
	task = Occurrence()
	words = ["good", "move", "this", "free", 
             "bad", "good", "is", "game", "is", 
             "logic", "move", "logic", "code", 
             "is", "move", "game", "good"]
	n = len(words)
	k = 4
	task.topKfrequent(words, n, k)

if __name__ == "__main__": main()

Output

  Top  4  element is
  is  good  move  game
#    Ruby program for
#    Top k frequent words solution
class Occurrence 
	def topKfrequent(words, n, k) 
		frequency = Hash.new()
		result = Hash.new()
		count = 0
		i = 0
		while (i < n) 
			if (frequency.key?(words[i])) 
				# when key exist then put new key
				frequency[words[i]] = frequency[words[i]] + 1
			else
 
				frequency[words[i]] = 1
			end

			i += 1
		end

		#  Combine elements by frequency
		frequency.each { | key, value |
			if (result.key?(value)) 
				result[value].push(key)
			else
 
				result[value] = []
				result[value].push(key)
			end

		}
		print("  Top ", k ," element is \n")
		i = n - 1
		while (i >= 0) 
			if (result.key?(i)) 
				for data in result[i] do 
					print("  ", data)
					count += 1
					if (count == k) 
						return
					end

				end

			end

			i -= 1
		end

		if (count != k) 
			print(" All top ", k ," element are not exist")
		end

	end

end

def main() 
	task = Occurrence.new()
	words = ["good", "move", "this", "free", 
             "bad", "good", "is", "game", "is", 
             "logic", "move", "logic", "code", 
             "is", "move", "game", "good"]
	n = words.length
	k = 4
	task.topKfrequent(words, n, k)
end

main()

Output

  Top 4 element is 
  good  move  is  game
import scala.collection.mutable._;
/*
    Scala program for
    Top k frequent words solution
*/
class Occurrence()
{
	def topKfrequent(words: Array[String], n: Int, k: Int): Unit = {
		var frequency = Map[String, Int]();
		var result =  Map[Int, ArrayBuffer[String]]();
		var count: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			if (frequency.contains(words(i)))
			{
				//when key exist then put new key
				frequency.addOne(words(i), frequency.get(words(i)).get + 1);
			}
			else
			{
				frequency.addOne(words(i), 1);
			}
			i += 1;
		}
		// Combine elements by frequency
		for ((key, value) <- frequency)
		{
			if (result.contains(value))
			{
				result.get(value).get += key;
			}
			else
			{
				result.addOne(value, new ArrayBuffer[String]());
				result.get(value).get += key;
			}
		}
		print("  Top " + k + " element is \n");
		i = n - 1;
		while (i >= 0)
		{
			if (result.contains(i))
			{
              	for ((v) <- result.get(i).get)
				{
					print("  " + v);
					count += 1;
					if (count == k)
					{
						return;
					}
				}
			}
			i -= 1;
		}
		if (count != k)
		{
			print(" All top " + k + " element are not exist");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: Occurrence = new Occurrence();
		var words: Array[String] = Array(
          "good", "move", "this", "free", 
          "bad", "good", "is", "game", "is", 
          "logic", "move", "logic", "code", 
          "is", "move", "game","good");
		var n: Int = words.length;
		var k: Int = 4;
		task.topKfrequent(words, n, k);
	}
}

Output

  Top 4 element is
  move  is  good  game
import Foundation;
/*
    Swift 4 program for
    Top k frequent words solution
*/
class Occurrence
{
	func topKfrequent(_ words: [String], _ n: Int, _ k: Int)
	{
		var frequency =  [String : Int]();
		var result = [Int : [String]]();
		var count: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			if (frequency.keys.contains(words[i]))
			{
				//when key exist then put new key
				frequency[words[i]] = frequency[words[i]]! + 1;
			}
			else
			{
				frequency[words[i]] = 1;
			}
			i += 1;
		}
		// Combine elements by frequency
		for (key, value) in frequency
		{
          	if (result.keys.contains(value) == false)
            {
                result[value] = [String]();
            }
			
			result[value]!.append(key);
			
		}
		print("  Top ", k ," element is ");
		i = n - 1;
		while (i >= 0)
		{
			if (result.keys.contains(i))
			{
				for data in result[i]!
				{
					print("  ", data, terminator: "");
					count += 1;
					if (count == k)
					{
						return;
					}
				}
			}
			i -= 1;
		}
		if (count  != k)
		{
			print(" All top ", k ," element are not exist", terminator: "");
		}
	}
}
func main()
{
	let task: Occurrence = Occurrence();
	let words: [String] = ["good", "move", "this", "free", 
                           "bad", "good", "is", "game", 
                           "is", "logic", "move", "logic", 
                           "code", "is", "move", "game", "good"];
	let n: Int = words.count;
	let k: Int = 4;
	task.topKfrequent(words, n, k);
}
main();

Output

  Top  4  element is
   good   move   is   logic
/*
    Kotlin program for
    Top k frequent words solution
*/
class Occurrence
{
	fun topKfrequent(words: Array < String > , n: Int, k: Int): Unit
	{
		var frequency = mutableMapOf < String, Int > ();
		var result = mutableMapOf<Int, ArrayList <String> >();
		var count: Int = 0;
		var i: Int = 0;
		while (i < n)
		{
			if (frequency.containsKey(words[i]))
			{
				//when key exist then put new key
				frequency.put(words[i], frequency.getValue(words[i]) + 1);
			}
			else
			{
				frequency.put(words[i], 1);
			}
			i += 1;
		}
		// Combine elements by frequency
		for ((key, value) in frequency)
		{
			if (result.containsKey(value))
			{
				result.getValue(value).add(key);
			}
			else
			{
				result.put(value, ArrayList < String > ());
				result.getValue(value).add(key);
			}
		}
		print("  Top " + k + " element is \n");
		i = n - 1;
		while (i >= 0)
		{
			if (result.containsKey(i))
			{
				for (data in result.getValue(i))
				{
					print("  " + data);
					count += 1;
					if (count == k)
					{
						return;
					}
				}
			}
			i -= 1;
		}
		if (count != k)
		{
			print(" All top " + k + " element are not exist");
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: Occurrence = Occurrence();
	val words: Array < String > = arrayOf(
      "good", "move", "this", "free", "bad", 
      "good", "is", "game", "is", "logic", 
      "move", "logic", "code", "is", 
      "move", "game", "good");
	val n: Int = words.count();
	val k: Int = 4;
	task.topKfrequent(words, n, k);
}

Output

  Top 4 element is
  good  move  is  game

Comment

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







George Gomes     688 Day ago
I found that using https://youtube.com/playlist?list=PL1MJrDFRFiKYjsnJQZW7hUudwYqLyJZgv and follow through this playlist will really give me a good understanding about Top K Element.