Even/Odd, Positive/Negative & Separation
Practice the following array programs.
Count Even & Odd Elements
Use the condition:
if (arr[i] % 2 == 0)
evenCount++;
else
oddCount++;
Count Positive & Negative Elements
Determine whether each element is positive or negative.
Example condition:
arr[i] >= 0
Separate Even & Odd Elements
Traverse the array once and store:
- Even elements
- Odd elements
in separate collections or arrays.
Sum of Even & Odd Elements
Maintain separate accumulators while traversing the array.
- Sum of Even Elements
- Sum of Odd Elements
These programs complete in a single traversal.
Time Complexity: O(n)
Comparison & Combination
Practice comparison and combination-based array programs.
Compare Two Arrays
Verify:
- Both arrays have the same length.
- Every corresponding element is equal.
Alternatively, use:
Arrays.equals(array1, array2);
Merge Two Arrays
Create a new array whose size is the combined length of both arrays.
Copy elements from each array into the new array.
Copy an Array
Copy elements:
- Using a loop
- Using
Arrays.copyOf()
Arrays.copyOf(arr, arr.length);
Find Common Elements
Compare two arrays and identify the elements present in both.
A HashSet can be used to improve performance.
Left & Right Rotation
Left Rotation
public class LeftRotateArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int n = arr.length;
int temp = arr[0];
for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = temp;
System.out.print("Array after left rotation: ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
Logic
- Store the first element.
- Shift every element one position to the left.
- Place the stored element at the last position.
Time Complexity: O(n)
Right Rotation
Right rotation follows the opposite approach.
- Store the last element.
- Shift all elements one position to the right.
- Place the stored value at the beginning.
Time Complexity: O(n)
Find the Missing Number
public class FindMissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 5};
int n = 5;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int i = 0; i < arr.length; i++) {
actualSum = actualSum + arr[i];
}
int missingNumber = expectedSum - actualSum;
System.out.println("Missing number is: " + missingNumber);
}
}
Logic
Expected Sum = n × (n + 1) / 2
Subtract the actual array sum from the expected sum.
The difference is the missing number.
Time Complexity: O(n)
Space Complexity: O(1)
Pair With a Given Sum
public class PairWithGivenSum {
public static void main(String[] args) {
int[] arr = {2, 4, 3, 5, 7, 8, 9};
int targetSum = 7;
HashSet<Integer> set = new HashSet<>();
System.out.println("Pairs with given sum:");
for (int i = 0; i < arr.length; i++) {
int requiredNumber = targetSum - arr[i];
if (set.contains(requiredNumber)) {
System.out.println("(" + requiredNumber + ", " + arr[i] + ")");
}
set.add(arr[i]);
}
}
}
Logic
For every element:
- Calculate the required complement.
- Check whether the complement already exists inside the
HashSet. - If found, print the pair.
Time Complexity: O(n)
Majority Element (Moore's Voting)
public class MajorityElement {
public static void main(String[] args) {
int[] arr = {2, 2, 1, 2, 3, 2, 2};
int candidate = 0;
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (count == 0) {
candidate = arr[i];
count = 1;
} else if (arr[i] == candidate) {
count++;
} else {
count--;
}
}
System.out.println("Majority Element: " + candidate);
}
}
Logic
Maintain:
- Candidate
- Count
When:
- The current element matches the candidate, increment the count.
- Otherwise, decrement the count.
- If the count reaches zero, select a new candidate.
Time Complexity: O(n)
Space Complexity: O(1)
Move Zeros & Array↔ArrayList
Move Zeros to the End
Maintain a write index.
- Copy all non-zero elements first.
- Fill the remaining positions with zeros.
Variants include:
- Move Zeros to Beginning
- Move Negative Numbers to Beginning
Time Complexity: O(n)
Convert Array to ArrayList
public class ArrayToArrayList {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
System.out.println("ArrayList: " + list);
}
}
Convert ArrayList to Array
list.toArray(new Integer[0]);
Frequently Asked Questions
How do you find a missing number in an array?
Calculate the expected sum using:
n × (n + 1) / 2
Subtract the actual array sum to obtain the missing number.
How do you find a pair with a given sum?
Use a HashSet.
For every element, calculate:
Target Sum − Current Element
If the required value already exists in the set, a valid pair has been found.
What is Moore's Voting Algorithm?
Moore's Voting Algorithm identifies the majority element by maintaining a candidate and a counter while traversing the array only once.
Time Complexity: O(n)
Space Complexity: O(1)
How do you rotate an array by one position?
Left Rotation
- Save the first element.
- Shift remaining elements left.
- Place the saved element at the end.
Right Rotation
- Save the last element.
- Shift remaining elements right.
- Place the saved element at the beginning.
How do you convert between an array and an ArrayList?
Array → ArrayList
Loop through the array and use:
list.add(value);
ArrayList → Array
list.toArray(new Integer[0]);