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:

  1. Split the input string into an array of words using space as delimiter
  2. Initialize a counter to track adjacent identical pairs
  3. Loop through the array, comparing each word with its next neighbor
  4. Use toLowerCase() to perform case-insensitive comparison
  5. Increment counter when adjacent words match
  6. 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.

Updated on: 2026-03-15T23:19:00+05:30

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements