Approach: Use two pointers from start and end
void ExtremePrint(int arr[], int size) {
for(int i=0;i<size/2;i++) {
cout <<arr[i]<<" "<<arr[size - 1 - i]<<" ";
}
if (size%2!= 0) {
cout<<arr[size / 2]; // Print the middle element if the array size is odd
}
cout << endl;
}
Method : Count number of zeros and ones, then fill the array
void countZerosOnes(vector<int>& arr) {
int oneCount = 0;
int zeroCount = 0;
int twoCount = 0; // Just for the logic there is no need to create twoCount Variable
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
zeroCount++;
}
else if (arr[i] == 1) {
oneCount++;
}
else {
twoCount++; // Just for the logic there is no need to create twoCount Variable
}
}
fill(arr, arr + zeroCount, 0);
fill(arr + zeroCount, arr + zeroCount + oneCount, 1);
fill(arr + zeroCount + oneCount, arr + n, 2);
}
Approach: Use INT_MIN and INT_MAX, traverse the array
void minandmax(int arr[],int size){
int min =INT_MAX;
int max= INT_MIN;
for(int i=0;i<size;i++){
if(arr[i]<min) min=arr[i];
if(arr[i]>max) max=arr[i];
}
cout<<"Min elem :"<<min<<" Max Elem :"<<max ;
cout<<endl;
}
Approach: Traverse array to find target element
int findElement(int arr[], int size, int elemt) {
for(int i = 0; i < size; i++) {
if(elemt == arr[i]) {
cout << "Element found" << endl;
return i; // Return index if element is found
}
}
cout << "Element not in the array" << endl;
return -1; // Return -1 if element is not found
}
Approach: XOR approach - all duplicates cancel out
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = 0;
for(int i = 0; i < nums.size(); i++){
ans = ans ^ nums[i];
}
return ans;
}
};
Method 1: Count and fill
Method 2: Sort function
Method 3: Two pointer approach