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
Selected Reading
JavaScript Algorithm - Removing Negatives from the Array
Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), we need to write a function that removes any negative values from the array using only the pop() method without creating temporary arrays.
The challenge is to modify the original array in-place, maintaining only positive numbers while using just the pop() method for removal.
Algorithm Approach
The algorithm works in two phases:
- Remove all negative values from the end of the array
- For remaining negatives, replace them with the last positive element and pop
Complete Implementation
function removeNegatives(x) {
// Phase 1: Strip all negatives from the end
while (x.length && x[x.length - 1] = 0; i--) {
if (x[i]
Original array: [-3, 5, 1, -7, 3, 2, 10, -1, -2]
After removing negatives: [10, 5, 1, 3, 2]
Step-by-Step Breakdown
let arr = [-3, 5, 1, -7, 3, 2, 10, -1, -2];
console.log("Step 1 - Original:", arr);
// Phase 1: Remove negatives from end
while (arr.length && arr[arr.length - 1] = 0; i--) {
if (arr[i]
Step 1 - Original: [-3, 5, 1, -7, 3, 2, 10, -1, -2]
Removing from end: -2
Removing from end: -1
After phase 1: [-3, 5, 1, -7, 3, 2, 10]
Replacing -7 at index 3 with 10
Replacing -3 at index 0 with 2
Final result: [2, 5, 1, 3]
How It Works
The algorithm ensures efficiency by:
-
Phase 1: Eliminates trailing negatives directly with
pop() - Phase 2: Replaces internal negatives with the last positive element, then removes the duplicate
- The loop goes backwards to avoid index shifting issues when modifying the array
Edge Cases
// Test edge cases
console.log("All negatives:", removeNegatives([-1, -2, -3]));
console.log("All positives:", removeNegatives([1, 2, 3]));
console.log("Empty array:", removeNegatives([]));
console.log("Single negative:", removeNegatives([-5]));
console.log("Single positive:", removeNegatives([5]));
All negatives: [] All positives: [1, 2, 3] Empty array: [] Single negative: [] Single positive: [5]
Conclusion
This algorithm efficiently removes negative numbers using only the pop() method by strategically replacing negatives with positive values from the array's end. The two-phase approach ensures optimal performance while maintaining the constraint of not using temporary arrays.
Advertisements
