702985. Segregate Even and Odd numbers
Segregate Even and Odd numbers
Summary
Segregate Even and Odd numbers is a basic algorithmic problem that requires you to separate even and odd numbers from an array. This problem is based on arrays and data structures, making it relevant for companies like Paytm, Accolite, Amazon, MakeMyTrip, and LinkedIn.
Detailed Explanation
The given array contains both even and odd numbers, and we need to segregate them such that all the even numbers come first followed by all the odd numbers. This problem can be solved using a simple one-pass algorithm.
Here's the step-by-step breakdown of the solution:
- Initialize two pointers,
evenandodd, to the start of the array. - Iterate through the array from left to right.
- For each element in the array:
- If the element is even, move it to the position pointed by
even. Move theevenpointer one step forward. - If the element is odd, move it to the position pointed by
odd. Move theoddpointer one step forward.
- If the element is even, move it to the position pointed by
- Continue this process until all elements in the array are processed.
The time complexity of this algorithm is O(n), where n is the number of elements in the array. The space complexity is O(1) as we only use a few extra variables to store the pointers and do not need any additional space that scales with the input size.
Here's an ASCII art diagram illustrating the process:
Initial Array: [3, 6, 2, 5, 4]
Even Pointer: 0
Odd Pointer: 0
Iteration 1: [3] (odd) at position 0 -> move to odd pointer position
Even Pointer: 1
Odd Pointer: 1
Iteration 2: [6] (even) at position 1 -> move to even pointer position
Even Pointer: 2
Odd Pointer: 1
Iteration 3: [2] (even) at position 2 -> move to even pointer position
Even Pointer: 3
Odd Pointer: 1
Iteration 4: [5] (odd) at position 1 -> move to odd pointer position
Even Pointer: 3
Odd Pointer: 2
Iteration 5: [4] (even) at position 2 -> move to even pointer position
Even Pointer: 4
Odd Pointer: 2
Final Array: [2, 6, 4, 3, 5]
Optimized Solutions
Java
public class SegregateEvenAndOdd {
public static void segregate(int[] arr) {
int even = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// Even number, move it to the position pointed by `even`.
int temp = arr[even];
arr[even] = arr[i];
arr[i] = temp;
even++;
} else {
// Odd number, move it to the position pointed by `odd`.
int temp = arr[even];
arr[even] = arr[i];
arr[i] = temp;
even++;
}
}
}
}