0% found this document useful (0 votes)
7 views2 pages

Interview Problem

The document outlines a problem of moving negative elements to the front of an array while maintaining the order of both negative and positive elements. It describes an algorithm using two pointers, left and right, to rearrange the elements through a series of checks and swaps. The process continues until the left pointer is less than or equal to the right pointer.

Uploaded by

mp7225563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Interview Problem

The document outlines a problem of moving negative elements to the front of an array while maintaining the order of both negative and positive elements. It describes an algorithm using two pointers, left and right, to rearrange the elements through a series of checks and swaps. The process continues until the left pointer is less than or equal to the right pointer.

Uploaded by

mp7225563
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Move Negative

Elements To Front Of Array

Problem statement:
Move the negative elements of an array to the
front

Example:
Input will be:
2 -9 10 12 5 -2 10 -4

Output will be:


-9 -2 -4 2 10 12 5 10

Note:
The order of negative elements are same.
The order of positive elements are same.
All negative elements have been moved to
the front.
All positive elements have been moved to the
end or followed by all the negative elements.
Solving Strategy
Move Negative
Elements To Front Of Array

The idea of the algorithm is to have two pointers left


and right.

All the elements before left should be negative and all


elements after right should be positive. This way if any
elements are at their wrong positions swaps can occur
to correct it.

Steps:
1. Initialize left pointer to 0 and right pointer to
size(nums)-1
2. check if both left and right elements are negative,
increment left pointer if true
3. check if left element is positive and right element is
negative then swap the elements, increment left
and decrement right
4. check if both left and right elements are positive,
decrement right pointer if true
5. otherwise, increment left and decrement right
pointers
6. repeat 2-5 until left pointer <= right pointer

You might also like