Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Print all words occurring in a sentence exactly K times

  • Last Updated : 18 Jan, 2022

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<bits/stdc++.h>
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<string> 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<String> l = new ConcurrentLinkedQueue<String>();
    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<String> 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)
Output
is
yellow
in

Time Complexity: O(N)
Auxiliary Space: O(1)

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




<script>
// JavaScript program for the above approach
  
/*
Function to print words
which occur k times
*/
function printWords(sentence, k)
{
     
    // splitting the string
    let lis = sentence.split(" ");
     
    // Calculating frequency of each word
    frequency = {};
    for(const word of lis)
    {
 
        // if word exists, increase the value by 1, otherwise mark it as 1
        frequency[word] = frequency[word] ? frequency[word] + 1 : 1;
    }
     
    // Iterating through frequency
    for(const key of Object.keys(frequency)){
         
        // if frequency is k
        if(frequency[key] == k){
 
            // print the word
            document.write(key + " ");
        }
    }
}
 
// Driver code
// Given string
let sentence = "sky is blue and my favourite color is blue"
  
// Given value of K
let K = 2
printWords(sentence, K)
 
// This code is contributed by mostaptname
</script>

Output:

is blue 

Time Complexity: O(N)

Space Complexity: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!