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
Finding the final direction of movement in JavaScript
Problem
We need to write a JavaScript function that takes an array of directional characters and finds the final direction after canceling out opposite movements. The array contains only 4 possible characters:
- 'N' ? stands for North direction
- 'S' ? stands for South direction
- 'W' ? stands for West direction
- 'E' ? stands for East direction
Each character represents a unit move in that direction. When opposite directions ('S' and 'N') or ('E' and 'W') appear adjacently, they cancel each other out. Our function should find the resulting direction after all cancellations.
Example Input and Expected Output
For the input array:
const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];
console.log("Input:", arr);
Input: [ 'N', 'S', 'S', 'E', 'W', 'N', 'W' ]
The expected output should be 'W' because:
- First 'N' and 'S' cancel each other
- 'E' and 'W' cancel each other
- Remaining 'S' and 'N' cancel each other
- Only 'W' remains
Solution Using String Replacement
const arr = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];
const cancelDirections = (arr = []) => {
let str = arr.join('');
while(str.includes('NS') || str.includes('SN') || str.includes('EW') || str.includes('WE')) {
str = str.replace('NS', '');
str = str.replace('SN', '');
str = str.replace('EW', '');
str = str.replace('WE', '');
}
return str.split('');
};
console.log("Result:", cancelDirections(arr));
console.log("Final direction:", cancelDirections(arr)[0] || 'None');
Result: [ 'W' ] Final direction: W
Alternative Solution Using Stack Approach
A more efficient approach uses a stack to track movements:
const cancelDirectionsStack = (arr = []) => {
const stack = [];
const opposites = { 'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E' };
for (let direction of arr) {
if (stack.length > 0 && stack[stack.length - 1] === opposites[direction]) {
stack.pop(); // Cancel out opposite directions
} else {
stack.push(direction);
}
}
return stack;
};
const testArray = ['N', 'S', 'S', 'E', 'W', 'N', 'W'];
console.log("Stack result:", cancelDirectionsStack(testArray));
// Test with another example
const testArray2 = ['N', 'N', 'S', 'E', 'E', 'W'];
console.log("Test 2 result:", cancelDirectionsStack(testArray2));
Stack result: [ 'W' ] Test 2 result: [ 'N', 'E' ]
Comparison of Methods
| Method | Time Complexity | Approach |
|---|---|---|
| String Replacement | O(n²) | Multiple passes through string |
| Stack Method | O(n) | Single pass with immediate cancellation |
Conclusion
Both methods solve the direction cancellation problem effectively. The stack approach is more efficient for large arrays, while the string replacement method is more intuitive to understand.
