Open In App

Print all words occurring in a sentence exactly K times

Improve
Improve
Like Article
Like
Save
Share
Report

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)


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<String> l = new List<String>();
    foreach (char x in S.ToCharArray()) {
      if (x == ' ') {
        l.Add(temp);
        temp = "";
      } else
        temp += x;
    }
 
    // Traverse the list
    foreach (String x in new List<String>(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<String> 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:

C++




// C++ code for the above approach
 
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
 
using namespace std;
 
// function to print words that appear k times
void printWords(string sentence, int k) {
    istringstream iss(sentence);
    vector<string> words;
    unordered_map<string, int> frequency;
 
    // Splitting the string into words and counting their frequency
    do {
        string word;
        iss >> word;
        words.push_back(word);
        frequency[word]++;
    } while (iss);
 
    // Printing the words that appear k times
    for (auto& p : frequency) {
        if (p.second == k) {
            cout << p.first << " ";
        }
    }
}
 
// Driver code
int main() {
    string sentence = "sky is blue and my favourite color is blue";
    int k = 2;
 
    printWords(sentence, k);
    return 0;
}
 
// This code is contributed by sdeadityasharma


Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
 
  public static void printWords(String sentence, int k) {
    // splitting the string
    String[] words = sentence.split(" ");
    // Calculating frequency of every word
    Map<String, Integer> frequency = new HashMap<>();
    for (String word : words) {
      int count = frequency.getOrDefault(word, 0);
      frequency.put(word, count + 1);
    }
 
    // Traversing the frequency
    for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
      // checking if frequency is k
      if (entry.getValue() == k) {
        // print the word
        System.out.print(entry.getKey() + " ");
      }
    }
  }
 
  public static void main(String[] args) {
  // Given string
  String sentence = "sky is blue and my favourite color is blue";
  // Given value of K
  int k = 2;
 
  printWords(sentence, k);
  }
}


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


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
namespace ConsoleApp1
{
    class Program {
        static void Main(string[] args) {
            // Given string
            string sentence = "sky is blue and my favourite color is blue";
            // Given value of K
            int K = 2;
            // Call to printWords function
            printWords(sentence, K);
        }
 
        // Function to print words which occurs k times
        public static void printWords(string sentence, int k) {
            // Splitting the sentence into words
            string[] words = sentence.Split(" ");
            // Calculating frequency of every word
            Dictionary<string, int> frequency = words.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
 
            // Traversing the frequency dictionary
            foreach (var word in frequency) {
                // Checking if frequency is k
                if (word.Value == k) {
                    // Print the word
                    Console.Write(word.Key + " ");
                }
            }
        }
    }
}


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)
Auxiliary Space: O(N)

Method #3: Using filter, lambda function and itertools.groupby:

  1. Initialize a variable max to be the first element of the array.
  2. Loop through the remaining elements of the array.
  3. For each element, compare it to the current value of max.
  4. If the element is greater than max, update max to be the element.
  5. After looping through all elements, the variable max will contain the maximum value in the array.
  6. Return max as the result.

C++




#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
 
using namespace std;
 
void printWords(string sentence, int k) {
    // splitting the sentence into words and sorting them
    vector<string> words;
    string word;
    for (char c : sentence) {
        if (c == ' ') {
            words.push_back(word);
            word = "";
        }
        else {
            word += c;
        }
    }
    words.push_back(word);
    sort(words.begin(), words.end());
 
    // using unordered_map to group words by their frequency
    unordered_map<string, int> frequencyGroups;
    for (string word : words) {
        frequencyGroups[word]++;
    }
 
    // using vector to store words that occur k times
    vector<string> filteredGroups;
    for (auto& entry : frequencyGroups) {
        if (entry.second == k) {
            filteredGroups.push_back(entry.first);
        }
    }
 
    // using unordered_set to keep track of printed words
    unordered_set<string> printedWords;
 
    // printing words that occur k times and haven't been printed before
    for (string word : filteredGroups) {
        if (printedWords.find(word) == printedWords.end()) {
            cout << word << " ";
            printedWords.insert(word);
        }
    }
}
 
int main() {
    string sentence = "sky is blue and my favourite color is blue";
    cout << "The original list: " << sentence << endl;
    int k = 2;
    printWords(sentence, k);
    return 0;
}


Java




import java.util.*;
import java.util.stream.*;
 
class Main {
    public static void main(String[] args) {
        String sentence = "sky is blue and my favourite color is blue";
        System.out.println("The original list : " + sentence);
        int k = 2;
        printWords(sentence, k);
    }
 
    static void printWords(String sentence, int k) {
        // splitting the sentence into words and sorting them
        String[] words = sentence.split("\\s+");
        Arrays.sort(words);
 
        // using Map to group words by their frequency
        Map<String, Long> frequencyGroups = Arrays.stream(words)
            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));
 
        // using filter to get words that occur k times
        List<String> filteredGroups = frequencyGroups.entrySet().stream()
            .filter(e -> e.getValue() == k)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
 
        // using HashSet to keep track of printed words
        Set<String> printedWords = new HashSet<>();
 
        // printing words that occur k times and haven't been printed before
        for (String word : filteredGroups) {
            if (!printedWords.contains(word)) {
                System.out.print(word + " ");
                printedWords.add(word);
            }
        }
    }
}


Python3




from itertools import groupby
def printWords(sentence, k):
    # splitting the sentence into words and sorting them
    words = sorted(sentence.split())
    # using groupby to group words by their frequency
    frequency_groups = groupby(words, key=lambda word: words.count(word))
    # using filter to get words that occur k times
    filtered_groups = filter(lambda group: group[0] == k, frequency_groups)
    # using set to keep track of printed words
    printed_words = set()
    # printing words that occur k times and haven't been printed before
    for freq, group in filtered_groups:
        for word in group:
            if freq == k and word not in printed_words:
                print(word, end=" ")
                printed_words.add(word)
# driver code
sentence = "sky is blue and my favourite color is blue"
# printing string
print("The original list : " + str(sentence))
K = 2
printWords(sentence, K)
#This code is contributed by Rayudu


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program {
  static void Main(string[] args)
  {
    string sentence
      = "sky is blue and my favourite color is blue";
    Console.WriteLine("The original list : "
                      + sentence);
    int k = 2;
    PrintWords(sentence, k);
  }
 
  static void PrintWords(string sentence, int k)
  {
 
    // splitting the sentence into words and sorting
    // them
    var words = sentence.Split().OrderBy(w = > w);
 
    // using groupby to group words by their frequency
    var frequencyGroups = words.GroupBy(
      w = > words.Count(x = > x == w));
 
    // using filter to get words that occur k times
    var filteredGroups
      = frequencyGroups.Where(g = > g.Key == k);
 
    // using HashSet to keep track of printed words
    var printedWords = new HashSet<string>();
 
    // printing words that occur k times and haven't
    // been printed before
    foreach(var group in filteredGroups)
    {
      foreach(var word in group)
      {
        if (group.Key == k
            && !printedWords.Contains(word)) {
          Console.Write(word + " ");
          printedWords.Add(word);
        }
      }
    }
  }
}
 
// This code is contributed by user_dtewbxkn77n


Javascript




function printWords(sentence, k) {
    // splitting the sentence into words and sorting them
    let words = sentence.split(' ');
    words.sort();
 
    // using object to group words by their frequency
    let frequencyGroups = {};
    for (let word of words) {
        if (frequencyGroups[word] === undefined) {
            frequencyGroups[word] = 1;
        } else {
            frequencyGroups[word]++;
        }
    }
 
    // using array to store words that occur k times
    let filteredGroups = [];
    for (let entry in frequencyGroups) {
        if (frequencyGroups[entry] === k) {
            filteredGroups.push(entry);
        }
    }
 
    // using Set to keep track of printed words
    let printedWords = new Set();
 
    // printing words that occur k times and haven't been printed before
    for (let word of filteredGroups) {
        if (!printedWords.has(word)) {
            process.stdout.write(word + " ");
            printedWords.add(word);
        }
    }
}
 
let sentence = "sky is blue and my favourite color is blue";
console.log("The original list: " + sentence);
let k = 2;
printWords(sentence, k);


Output

The original list : sky is blue and my favourite color is blue
blue is 

Time Complexity: O(n), where n is the number of words in the sentence.
This needs to split the sentence into individual words, count the frequency of each word, and then iterate through the dictionary to print the words that occur k times. Each of these steps takes O(n) time, resulting in a total time complexity of O(n).

Space Complexity: O(n), where n is the number of words in the sentence.
This needs to store the words in a list and the frequency counts in a dictionary. The size of the list and dictionary are both proportional to the number of words in the sentence, resulting in a space complexity of O(n).



Last Updated : 18 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads