Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Counting adjacent pairs of words in JavaScript
We are required to write a JavaScript function that takes in a string str that represents a sentence as the only argument.
Our function should count and return the adjacent pair of identical words present in the string str. Our function should check the words ignoring their case, which means 'it' and 'It' should be counted as identical.
Problem Statement
For example, if the input to the function is:
const str = 'This this is a a sample string';
The expected output should be:
2
Output Explanation: Because the repeating words are 'this' and 'a'.
Solution
Following is the code implementation:
const str = 'This this is a a sample string';
const countIdentical = (str = '') => {
const arr = str.split(' ');
let count = 0;
for(let i = 0; i
2
How It Works
The algorithm follows these steps:
- Split the input string into an array of words using space as delimiter
- Initialize a counter to track adjacent identical pairs
- Loop through the array, comparing each word with its next neighbor
- Use toLowerCase() to perform case-insensitive comparison
- Increment counter when adjacent words match
- Return the final count
Alternative Approach Using reduce()
const str = 'This this is a a sample string';
const countIdenticalReduce = (str = '') => {
const words = str.split(' ');
return words.reduce((count, word, index) => {
if (index
2
Edge Cases
Let's test the function with various edge cases:
// Empty string
console.log(countIdentical(''));
// Single word
console.log(countIdentical('hello'));
// No adjacent pairs
console.log(countIdentical('hello world test'));
// Multiple adjacent pairs
console.log(countIdentical('hello hello world world test test'));
// Mixed case
console.log(countIdentical('Hello HELLO world WORLD'));
0
0
0
3
2
Conclusion
This solution efficiently counts adjacent identical word pairs using case-insensitive comparison. The time complexity is O(n) where n is the number of words, making it optimal for most use cases.
