 Open in App
Not now

# Print all words occurring in a sentence exactly K times

• Last Updated : 27 Jan, 2023

Given a string S consisting of lowercase alphabets and an integer K, the task is to print all the words that occur K times in the string S.

Examples:

Input: S = “banana is in yellow and sun flower is also in yellow”, K = 2
Output: “is” “yellow” “in”
Explanation: The words “is”, “yellow” and “in” occurs in the string twice.

Input: S = “geeks for geeks”, K = 2
Output: “geeks”

Approach: Follow the steps below to solve the problem:

• Initialize a list l to store the words present in the string.
• Split the words and store it in the list.
• Traverse the list and for each word:
• If the frequency of the word is found to be K:
• Print that word.
• Remove current occurrence of that word from the list.

Below is the implementation of the above approach:

## C++

 `// CPP program for the above approach``#include``using` `namespace` `std;` `// Function to print all the words``// occurring k times in a string``void` `kFreqWords(string S, ``int` `K)``{` `  ``// Stores the words``  ``string temp = ``""``;``  ``vector l;``  ``for` `(``auto` `x: S)``  ``{``    ``if``(x == ``' '``)``    ``{``      ``l.push_back(temp);``      ``temp = ``""``;``    ``}``    ``else``      ``temp += x;``  ``}` `  ``// Traverse the list``  ``for` `(``auto` `x: l)``  ``{` `    ``// Check for count``    ``if` `(count(l.begin(), l.end(), x) == K)``    ``{` `      ``// Print the word``      ``cout << x << endl;` `      ``// Remove from list``      ``remove``(l.begin(),l.end(), x);``    ``}``  ``}``}` `// Driver Code``int` `main()``{` `  ``// Given string``  ``string S = ``"banana is in yellow and sun flower is also in yellow "``;` `  ``// Given value of K``  ``int` `K = 2;` `  ``// Function call to find``  ``// all words occurring K times``  ``kFreqWords(S, K);` `}` `// This code is contributed by SURENDRA_GANGWAR.`

## Java

 `// JAVA program for the above approach``import` `java.util.Queue;``import` `java.util.concurrent.ConcurrentLinkedQueue;` `class` `GFG {` `  ``// Function to print all the words``  ``// occurring k times in a String``  ``static` `void` `kFreqWords(String S, ``int` `K) {` `    ``// Stores the words``    ``String temp = ``""``;``    ``Queue l = ``new` `ConcurrentLinkedQueue();``    ``for` `(``char` `x : S.toCharArray()) {``      ``if` `(x == ``' '``) {``        ``l.add(temp);``        ``temp = ``""``;``      ``} ``else``        ``temp += x;``    ``}` `    ``// Traverse the list``    ``for` `(String x : l) {` `      ``// Check for count``      ``if` `(count(l, x) == K) {` `        ``// Print the word``        ``System.out.print(x + ``"\n"``);` `        ``// Remove from list``        ``l.remove((Object)x);``      ``}``    ``}``  ``}` `  ``// Driver Code``  ``private` `static` `int` `count(Queue l, String x) {``    ``int` `count = ``0``;``    ``for` `(String s : l) {``      ``if` `(s.equals(x))``        ``count++;``    ``}``    ``return` `count;``  ``}` `  ``public` `static` `void` `main(String[] args) {` `    ``// Given String``    ``String S = ``"banana is in yellow and sun flower is also in yellow "``;` `    ``// Given value of K``    ``int` `K = ``2``;` `    ``// Function call to find``    ``// all words occurring K times``    ``kFreqWords(S, K);` `  ``}``}` `// This code is contributed by shikhasingrajput`

## Python3

 `# Python3 program for the above approach` `# Function to print all the words``# occurring k times in a string`  `def` `kFreqWords(S, K):` `    ``# Stores the words``    ``l ``=` `list``(S.split(``" "``))` `    ``# Traverse the list``    ``for` `i ``in` `l:` `        ``# Check for count``        ``if` `l.count(i) ``=``=` `K:` `            ``# Print the word``            ``print``(i)` `            ``# Remove from list``            ``l.remove(i)`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``# Given string``    ``S ``=` `"banana is in yellow and sun flower is also in yellow"` `    ``# Given value of K``    ``K ``=` `2` `    ``# Function call to find``    ``# all words occurring K times``    ``kFreqWords(S, K)`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `using` `System.Collections.Concurrent;``public` `class` `GFG {` `  ``// Function to print all the words``  ``// occurring k times in a String``  ``static` `void` `kFreqWords(String S, ``int` `K) {` `    ``// Stores the words``    ``String temp = ``""``;``    ``List l = ``new` `List();``    ``foreach` `(``char` `x ``in` `S.ToCharArray()) {``      ``if` `(x == ``' '``) {``        ``l.Add(temp);``        ``temp = ``""``;``      ``} ``else``        ``temp += x;``    ``}` `    ``// Traverse the list``    ``foreach` `(String x ``in` `new` `List(l)) {` `      ``// Check for count``      ``if` `(count(l, x) == K) {` `        ``// Print the word``        ``Console.Write(x + ``"\n"``);` `        ``// Remove from list``        ``l.Remove(x);``      ``}``    ``}``  ``}` `  ``// Driver Code``  ``private` `static` `int` `count(List l, String x) {``    ``int` `count = 0;``    ``foreach` `(String s ``in` `l) {``      ``if` `(s.Equals(x))``        ``count++;``    ``}``    ``return` `count;``  ``}` `  ``public` `static` `void` `Main(String[] args) {` `    ``// Given String``    ``String S = ``"banana is in yellow and sun flower is also in yellow "``;` `    ``// Given value of K``    ``int` `K = 2;` `    ``// Function call to find``    ``// all words occurring K times``    ``kFreqWords(S, K);` `  ``}``}` ` `  `// This code contributed by shikhasingrajput`

## Javascript

 `// Function to print all the words``// occurring k times in a string``function` `kFreqWords(S, K) {``    ``// Stores the words``    ``let l = S.split(``" "``);` `    ``// Traverse the list``    ``for` `(let i = 0; i < l.length; i++) {``        ``// Check for count``        ``if` `(l.filter(word => word === l[i]).length === K) {``            ``// Print the word``            ``console.log(l[i]);` `            ``// Remove from list``            ``l = l.filter(word => word !== l[i]);``        ``}``    ``}``}` `// Driver Code``(``function``() {``    ``// Given string``    ``let S = ``"banana is in yellow and sun flower is also in yellow"``;` `    ``// Given value of K``    ``let K = 2;` `    ``// Function call to find``    ``// all words occurring K times``    ``kFreqWords(S, K);``})();`

Output

```is
yellow
in```

Time Complexity: O(N2)
Auxiliary Space: O(N) because using auxiliary space for list to store frequency of word

#### Method #2: Using built in python functions:

• As all the words in a sentence are separated by spaces.
• We have to split the sentence by spaces using split().
• We split all the words by spaces and store them in a list.
• Use Counter function to count frequency of words
• Traverse the frequency dictionary and print the word having frequency k

Below is the implementation of above approach:

## Python3

 `# Python program for the above approach``from` `collections ``import` `Counter` `# Python program to print words``# which occurs k times``def` `printWords(sentence, k):` `    ``# splitting the string``    ``lis ``=` `list``(sentence.split(``" "``))` `    ``# Calculating frequency of every word``    ``frequency ``=` `Counter(lis)` `    ``# Traversing the frequency``    ``for` `i ``in` `frequency:` `        ``# checking if frequency is k` `        ``if``(frequency[i] ``=``=` `k):``          ` `            ``# print the word``            ``print``(i, end``=``" "``)`  `# Driver code``# Given string``sentence ``=` `"sky is blue and my favourite color is blue"` `# Given value of K``K ``=` `2` `printWords(sentence, K)``# this code is contributed by vikkycirus`

## Javascript

 ``

Output:

`is blue `

Time Complexity: O(N)

Space Complexity: O(N)

My Personal Notes arrow_drop_up