Print all words occurring in a sentence exactly K times
Last Updated :
18 Apr, 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++
#include<bits/stdc++.h>
using namespace std;
void kFreqWords(string S, int K)
{
string temp = "" ;
vector<string> l;
for ( auto x: S)
{
if (x == ' ' )
{
l.push_back(temp);
temp = "" ;
}
else
temp += x;
}
for ( auto x: l)
{
if (count(l.begin(), l.end(), x) == K)
{
cout << x << endl;
remove (l.begin(),l.end(), x);
}
}
}
int main()
{
string S = "banana is in yellow and sun flower is also in yellow " ;
int K = 2;
kFreqWords(S, K);
}
|
Java
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
class GFG {
static void kFreqWords(String S, int K) {
String temp = "" ;
Queue<String> l = new ConcurrentLinkedQueue<String>();
for ( char x : S.toCharArray()) {
if (x == ' ' ) {
l.add(temp);
temp = "" ;
} else
temp += x;
}
for (String x : l) {
if (count(l, x) == K) {
System.out.print(x + "\n" );
l.remove((Object)x);
}
}
}
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) {
String S = "banana is in yellow and sun flower is also in yellow " ;
int K = 2 ;
kFreqWords(S, K);
}
}
|
Python3
def kFreqWords(S, K):
l = list (S.split( " " ))
for i in l:
if l.count(i) = = K:
print (i)
l.remove(i)
if __name__ = = "__main__" :
S = "banana is in yellow and sun flower is also in yellow"
K = 2
kFreqWords(S, K)
|
C#
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
public class GFG {
static void kFreqWords(String S, int K) {
String temp = "" ;
List<String> l = new List<String>();
foreach ( char x in S.ToCharArray()) {
if (x == ' ' ) {
l.Add(temp);
temp = "" ;
} else
temp += x;
}
foreach (String x in new List<String>(l)) {
if (count(l, x) == K) {
Console.Write(x + "\n" );
l.Remove(x);
}
}
}
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) {
String S = "banana is in yellow and sun flower is also in yellow " ;
int K = 2;
kFreqWords(S, K);
}
}
|
Javascript
function kFreqWords(S, K) {
let l = S.split( " " );
for (let i = 0; i < l.length; i++) {
if (l.filter(word => word === l[i]).length === K) {
console.log(l[i]);
l = l.filter(word => word !== l[i]);
}
}
}
( function () {
let S = "banana is in yellow and sun flower is also in yellow" ;
let K = 2;
kFreqWords(S, K);
})();
|
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++
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <vector>
using namespace std;
void printWords(string sentence, int k) {
istringstream iss(sentence);
vector<string> words;
unordered_map<string, int > frequency;
do {
string word;
iss >> word;
words.push_back(word);
frequency[word]++;
} while (iss);
for ( auto & p : frequency) {
if (p.second == k) {
cout << p.first << " " ;
}
}
}
int main() {
string sentence = "sky is blue and my favourite color is blue" ;
int k = 2;
printWords(sentence, k);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void printWords(String sentence, int k) {
String[] words = sentence.split( " " );
Map<String, Integer> frequency = new HashMap<>();
for (String word : words) {
int count = frequency.getOrDefault(word, 0 );
frequency.put(word, count + 1 );
}
for (Map.Entry<String, Integer> entry : frequency.entrySet()) {
if (entry.getValue() == k) {
System.out.print(entry.getKey() + " " );
}
}
}
public static void main(String[] args) {
String sentence = "sky is blue and my favourite color is blue" ;
int k = 2 ;
printWords(sentence, k);
}
}
|
Python3
from collections import Counter
def printWords(sentence, k):
lis = list (sentence.split( " " ))
frequency = Counter(lis)
for i in frequency:
if (frequency[i] = = k):
print (i, end = " " )
sentence = "sky is blue and my favourite color is blue"
K = 2
printWords(sentence, K)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program {
static void Main( string [] args) {
string sentence = "sky is blue and my favourite color is blue" ;
int K = 2;
printWords(sentence, K);
}
public static void printWords( string sentence, int k) {
string [] words = sentence.Split( " " );
Dictionary< string , int > frequency = words.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());
foreach ( var word in frequency) {
if (word.Value == k) {
Console.Write(word.Key + " " );
}
}
}
}
}
|
Javascript
<script>
function printWords(sentence, k)
{
let lis = sentence.split( " " );
frequency = {};
for (const word of lis)
{
frequency[word] = frequency[word] ? frequency[word] + 1 : 1;
}
for (const key of Object.keys(frequency)){
if (frequency[key] == k){
document.write(key + " " );
}
}
}
let sentence = "sky is blue and my favourite color is blue"
let K = 2
printWords(sentence, K)
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #3: Using filter, lambda function and itertools.groupby:
- Initialize a variable max to be the first element of the array.
- Loop through the remaining elements of the array.
- For each element, compare it to the current value of max.
- If the element is greater than max, update max to be the element.
- After looping through all elements, the variable max will contain the maximum value in the array.
- 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) {
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());
unordered_map<string, int > frequencyGroups;
for (string word : words) {
frequencyGroups[word]++;
}
vector<string> filteredGroups;
for ( auto & entry : frequencyGroups) {
if (entry.second == k) {
filteredGroups.push_back(entry.first);
}
}
unordered_set<string> printedWords;
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) {
String[] words = sentence.split( "\\s+" );
Arrays.sort(words);
Map<String, Long> frequencyGroups = Arrays.stream(words)
.collect(Collectors.groupingBy(w -> w, Collectors.counting()));
List<String> filteredGroups = frequencyGroups.entrySet().stream()
.filter(e -> e.getValue() == k)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
Set<String> printedWords = new HashSet<>();
for (String word : filteredGroups) {
if (!printedWords.contains(word)) {
System.out.print(word + " " );
printedWords.add(word);
}
}
}
}
|
Python3
from itertools import groupby
def printWords(sentence, k):
words = sorted (sentence.split())
frequency_groups = groupby(words, key = lambda word: words.count(word))
filtered_groups = filter ( lambda group: group[ 0 ] = = k, frequency_groups)
printed_words = set ()
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)
sentence = "sky is blue and my favourite color is blue"
print ( "The original list : " + str (sentence))
K = 2
printWords(sentence, K)
|
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)
{
var words = sentence.Split().OrderBy(w = > w);
var frequencyGroups = words.GroupBy(
w = > words.Count(x = > x == w));
var filteredGroups
= frequencyGroups.Where(g = > g.Key == k);
var printedWords = new HashSet< string >();
foreach ( var group in filteredGroups)
{
foreach ( var word in group )
{
if ( group .Key == k
&& !printedWords.Contains(word)) {
Console.Write(word + " " );
printedWords.Add(word);
}
}
}
}
}
|
Javascript
function printWords(sentence, k) {
let words = sentence.split( ' ' );
words.sort();
let frequencyGroups = {};
for (let word of words) {
if (frequencyGroups[word] === undefined) {
frequencyGroups[word] = 1;
} else {
frequencyGroups[word]++;
}
}
let filteredGroups = [];
for (let entry in frequencyGroups) {
if (frequencyGroups[entry] === k) {
filteredGroups.push(entry);
}
}
let printedWords = new Set();
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).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...