Skip to content
Related Articles

Related Articles

Print all words occurring in a sentence exactly K times
  • Last Updated : 26 Mar, 2021

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 occuring K times
  kFreqWords(S, K);
 
}
 
// This code is contributed by SURENDRA_GANGWAR.

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 occuring 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 thee 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 occures k times
def printWords(sentence, k):
 
    # spliting 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

Output:

is blue 

Time Complexity: O(N)

Space Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :