709347. Rearrange the array
Rearrange the Array
Slug: rearrange-the-array-1639032648 Difficulty: Hard Id: 709347 Topic Tags: DFS, Prime Number, LCS, Algorithms Company Tags: Flipkart
Summary
Given an array arr of size n, where each element is either a prime number or not, the task is to rearrange the elements in the array such that all prime numbers come first and are followed by non-prime numbers. This problem can be approached using Depth-First Search (DFS) and Prime Number detection.
Detailed Explanation
The approach to solve this problem involves two steps:
- Detecting prime numbers in the array.
- Rearranging the elements based on their primality.
To detect prime numbers, we use a simple function that checks if a number is prime or not. This function takes an integer num as input and returns true if it's prime and false otherwise.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers,
prime_startandnon_prime_end, to 0. - Traverse the array using DFS. For each element:
- If the element is prime, update
prime_startto the current index. - If the element is not prime, update
non_prime_endto the current index + 1.
- If the element is prime, update
- Once the traversal is complete, rearrange the elements by copying all prime numbers from the original array to a new array and then copying non-prime numbers to fill up the rest of the new array.
Here's an ASCII art diagram illustrating this process:
Original Array: [2, 3, 4, 5, 6, 7, 8, 9]
Prime Start: 1
Non-Prime End: 0
Rearranged Array: [3, 5, 7], [2, 4, 6, 8, 9]
The time complexity of this solution is O(n log n), where n is the size of the array. This is because we are using a prime number detection function that involves a simple loop and checks up to the square root of the number. The space complexity is O(1) as we only need to keep track of two pointers.
Optimized Solutions
Java
public static void rearrangeArray(int[] arr) {
int n = arr.length;
boolean[] primes = new boolean[n];
for (int i = 0; i < n; i++) {
primes[i] = isPrime(arr[i]);
}
int primeStart = 0, nonPrimeEnd = 0;
for (int i = 0; i < n; i++) {
if (primes[i]) {
primeStart = i;
} else {
nonPrimeEnd = i + 1;
}
}
int[] rearrangedArr = new int[n];
for (int i = 0, j = primeStart; i < n; i++, j++) {
if (j < primeStart) {
rearrangedArr[i] = arr[nonPrimeEnd++];
} else {
rearrangedArr[i] = arr[j];
}
}
}
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2, sqrt = (int)Math.sqrt(num); i <= sqrt; i++) {
if (num % i == 0) return false;
}
return true;
}