Finding elements whose successors and predecessors are in array in JavaScript

We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function should construct and return a new array that contains all such elements from the original array whose successor and predecessor are both present in the array. This means, if any element num is in the original array, it should be included in the result array if and only if num - 1 and num + 1 are also present in the array.

For example, if the input array is:

const arr = [4, 6, 8, 1, 9, 7, 5, 12];

Then the output should be:

[6, 8, 7, 5]

Here's why these elements qualify:

  • 6: Both 5 (6-1) and 7 (6+1) are present
  • 8: Both 7 (8-1) and 9 (8+1) are present
  • 7: Both 6 (7-1) and 8 (7+1) are present
  • 5: Both 4 (5-1) and 6 (5+1) are present

Example

The code for this will be:

const arr = [4, 6, 8, 1, 9, 7, 5, 12];

const pickMiddleElements = (arr = []) => {
    const res = [];
    for(let i = 0; i < arr.length; i++){
        const num = arr[i];
        const hasBefore = arr.includes(num - 1);
        const hasAfter = arr.includes(num + 1);
        if(hasBefore && hasAfter){
            res.push(num);
        }
    }
    return res;
};

console.log(pickMiddleElements(arr));

Output

The output in the console will be:

[ 6, 8, 7, 5 ]

Optimized Approach Using Set

For better performance with large arrays, we can use a Set for O(1) lookups:

const arr = [4, 6, 8, 1, 9, 7, 5, 12];

const pickMiddleElementsOptimized = (arr = []) => {
    const numSet = new Set(arr);
    const res = [];
    
    for(const num of arr){
        if(numSet.has(num - 1) && numSet.has(num + 1)){
            res.push(num);
        }
    }
    return res;
};

console.log(pickMiddleElementsOptimized(arr));
[ 6, 8, 7, 5 ]

Comparison

Method Time Complexity Space Complexity Best For
Array.includes() O(n²) O(1) Small arrays
Set lookup O(n) O(n) Large arrays

Conclusion

Both approaches find elements with adjacent predecessors and successors. Use the Set approach for better performance with larger datasets, as it reduces time complexity from O(n²) to O(n).

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

518 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements