Reversing array without changing the position of certain elements JavaScript

In this problem, we need to reverse an array while keeping certain elements in their original positions. This requires tracking preserved element positions and carefully swapping only the non-preserved elements.

Understanding the Problem

The goal is to reverse an array but preserve specific elements at their original positions. For example, if we have array [1, 2, 3, 4, 5, 6] and want to preserve elements [2, 4, 6], the result should be [5, 2, 3, 4, 1, 6] instead of a complete reversal.

Algorithm Approach

The solution involves:

  • Track indices of elements to preserve
  • Create a working copy of the array
  • Reverse only the non-preserved elements
  • Maintain preserved elements in their original positions

Implementation

function reverseArrayWithPreserved(arr, preserveElements) {
    // Create a copy to avoid modifying original array
    const result = [...arr];
    
    // Get indices of elements to preserve
    const preservedIndices = new Set();
    preserveElements.forEach(element => {
        const index = arr.indexOf(element);
        if (index !== -1) {
            preservedIndices.add(index);
        }
    });
    
    // Collect non-preserved elements
    const nonPreservedElements = [];
    for (let i = 0; i < arr.length; i++) {
        if (!preservedIndices.has(i)) {
            nonPreservedElements.push(arr[i]);
        }
    }
    
    // Reverse the non-preserved elements
    nonPreservedElements.reverse();
    
    // Place reversed non-preserved elements back
    let nonPreservedIndex = 0;
    for (let i = 0; i < result.length; i++) {
        if (!preservedIndices.has(i)) {
            result[i] = nonPreservedElements[nonPreservedIndex];
            nonPreservedIndex++;
        }
    }
    
    return result;
}

// Example usage
const originalArray = [1, 2, 3, 4, 5, 6];
const elementsToPreserve = [2, 4, 6];

console.log("Original array:", originalArray);
console.log("Elements to preserve:", elementsToPreserve);

const reversedArray = reverseArrayWithPreserved(originalArray, elementsToPreserve);
console.log("Result:", reversedArray);
Original array: [ 1, 2, 3, 4, 5, 6 ]
Elements to preserve: [ 2, 4, 6 ]
Result: [ 5, 2, 3, 4, 1, 6 ]

Alternative Implementation

Here's a more concise approach using two pointers:

function reverseWithPreservedElements(arr, preserve) {
    const result = [...arr];
    const preservedSet = new Set(preserve);
    let left = 0, right = arr.length - 1;
    
    while (left < right) {
        // Skip preserved elements from left
        while (left < right && preservedSet.has(result[left])) {
            left++;
        }
        
        // Skip preserved elements from right
        while (left < right && preservedSet.has(result[right])) {
            right--;
        }
        
        // Swap non-preserved elements
        if (left < right) {
            [result[left], result[right]] = [result[right], result[left]];
            left++;
            right--;
        }
    }
    
    return result;
}

// Test with different example
const testArray = [10, 20, 30, 40, 50];
const preserveElements = [20, 40];

console.log("Test array:", testArray);
console.log("Preserve:", preserveElements);
console.log("Result:", reverseWithPreservedElements(testArray, preserveElements));
Test array: [ 10, 20, 30, 40, 50 ]
Preserve: [ 20, 40 ]
Result: [ 50, 20, 30, 40, 10 ]

Complexity Analysis

Approach Time Complexity Space Complexity
First Method O(n) O(n)
Two Pointer Method O(n) O(n)

Conclusion

Both approaches efficiently reverse arrays while preserving specific elements in their original positions. The two-pointer method is more memory-efficient for the swapping process, while the first method is more intuitive to understand.

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

647 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements