0% found this document useful (0 votes)
3 views

Array

The document contains various C++ programs demonstrating array manipulation techniques, including finding maximum and minimum values, linear search, reversing an array, swapping adjacent elements, finding unique and duplicate elements, and implementing binary search. It also covers advanced topics such as finding intersections of arrays, pair sums, and modifying array elements based on specific conditions. Additionally, it discusses time complexity and provides multiple approaches for certain problems, ensuring a comprehensive understanding of array operations.

Uploaded by

abhishek040599
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Array

The document contains various C++ programs demonstrating array manipulation techniques, including finding maximum and minimum values, linear search, reversing an array, swapping adjacent elements, finding unique and duplicate elements, and implementing binary search. It also covers advanced topics such as finding intersections of arrays, pair sums, and modifying array elements based on specific conditions. Additionally, it discusses time complexity and provides multiple approaches for certain problems, ensuring a comprehensive understanding of array operations.

Uploaded by

abhishek040599
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

#Maximun and Minimun in an Array

#include<iostream>
using namespace std;

int getmax(int A[], int n)


{
int max1 = INT_MAX;
for(int i=0;i<n;i++)
{
if(A[i]> = max1)
{
max1 = A[i];
}
}

/*or we can use max function #Inbuilt function


for(int i=0;i<n;i++)
{
max1 = max(max1,A[i]);
}*/
}
int getmin(int A[], int n)
{
for(int i=0;i<n;i++)
{
int min1 = INT_MIN;
if(A[i]<=min1)
{
min1 = A[i];
}
}
/*or we can use min function #Inbuilt function
for(int i=0;i<n;i++)
{
min1 = min(min1,A[i]);
}*/
}

#Linear Search

#include<iostream>
using namespace std;

bool search(int arr[], int size, int k)


{
for(int i=0;i<size;i++)
{
if(arr[i]==k)
{
return 1;
}
}
return 0;
}
int main()
{
int arr[10] = {10,2,3,5,6,0,1,9,8,6};
int k = 05;
//int size = sizeof(arr)/sizeof(int);
bool result = search(arr,10,k);
if(result)
{
cout<<"Present"<<endl;
}
else
{
cout<<"Absent"<<endl;
}
return 0;
}

#Reverse an Array

#include<iostream>
using namespace std;

void printArr(int arr[], int n)


{
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}

void reverse(int arr[], int n)


{
int start = 0;
int end = n-1;

while(start<=end)
{
swap(arr[start],arr[end]);
start++;
end--;
}
}

int main()
{
int A[6] = {1,2,3,4,5,6};
int B[5] = {4,5,6,7,1};

reverse(A,6);
reverse(B,5);

printArr(A,6);
printArr(B,5);
return 0;
}
#Swap adjacent elements of an array

#include<iostream>
using namespace std;

void printArr(int arr[], int n)


{
for(int i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}

void swapadj(int arr[], int n)


{
int start = 0;
while(start<n-1)
{
swap(arr[start],arr[start+1]);
start = start + 2;
}
}

int main()
{
int A[6] = {6,4,8,10,12,14};
int B[5] = {1,2,3,4,5};

swapadj(A,6);
swapadj(B,5);

printArr(A,6);
printArr(B,5);
return 0;
}

#Find Unique Element in an Array

Use XOR property


any number a
a^a = 0
a^0 = a

2^2 -> 1 0 2^0 1 0


1 0 0 0
0 0 ->0 1 0 -> 2

#include<iostream>
using namespace std;

int main()
{
int A[7] = {1,2,4,4,2,1,3};
int a = 0;
for(int i = 0; i < n; i++)
{
a = a^A[i+1];
}
}

#Duplicate In Array

You are given an array ‘ARR’ of size ‘N’ containing each number between 1 and ‘N’ -
1 at least once. There is a single integer value that is present in the array
twice. Your task is to find the duplicate integer value present in the array.

Consider ARR = [1, 2, 3, 4, 4], the duplicate integer value present in the array is
4. Hence, the answer is 4 in this case.

Approach 1 XOR to find the duplicate element


int findDuplicate(vector<int> &arr)
{
// Write your code here

int N = arr.size();
int ans = 0;
for(int i=0;i<N;i++)
{
ans = ans^arr[i]^i; // XOR to find the duplicate element
}
return ans;
}

Approach 2 Frquency

int findDuplicate(vector<int> &arr)


{
// Write your code here

int N = arr.size();
int f[N+1] = {0};
for(int i = 0; i<N; i++)
{
f[arr[i]]++;
}
for(int i = 0; i<N; i++)
{
if(f[arr[i]]==2)
{
return arr[i];
}
}

Approach 3 : Sum of all elements - sum of 1 to n-1

int findDuplicate(vector<int> &arr)


{
// Write your code here
int n = arr.size();
int sum = 0;
for(int i = 0; i<n; i++)
{
sum+=arr[i];
}
return (sum-(n*(n-1)/2));

Intersection Of Two Arrays - 2 Pointer Approach

vector<int> findArrayIntersection(vector<int> &arr1, int n, vector<int> &arr2, int


m)
{
// Write your code here.
vector<int> intersection;
int i=0,j=0;
while(i<n && j<m)
{
if(arr1[i]==arr2[j])
{
intersection.push_back(arr1[i]);
i++;
j++;
}
else if(arr1[i]<arr2[j])
{
i++;
}
else
{
j++;
}
}
return intersection;
}

Pair Sum Array

vector<vector<int>> pairSum(vector<int> &arr, int s){


// Write your code here.
vector<vector<int>> ans;
for(int i=0;i<arr.size();i++)
{
for(int j=i+1;j<arr.size();j++)
{
vector<int> temp;
if(arr[i]+arr[j]==s)
{
temp.push_back(min(arr[i],arr[j]));
temp.push_back(max(arr[i],arr[j]));
ans.push_back(temp);
}
}
}
sort(ans.begin(),ans.end());
return ans;
}

#Binary Search

#include <iostream>
using namespace std;

int binarysearch(int arr[], int size, int k)


{
int start = 0;
int end = size - 1;
// If we get int as 2^31 then if we do (s+e)/2 it goes beyond range so to avoid
that we use mid as below
int mid = start + (end-start)/2;
while(start<=end)
{
if(arr[mid]==k)
{
return mid;
}

if(k>arr[mid])
{
start = mid+1;
}
else
{
end = mid-1;
}
mid = start + (end-start)/2;
}
return -1;
}

int main() {
// your code goes here
int even[6] = {10,20,30,40,50,60};
int odd[5] = {10,20,30,40,50};
int k;cin>>k;
int index = binarysearch(even,6,k);
cout<<index<<endl;
index = binarysearch(odd,5,k);
cout<<index<<endl;

return 0;
}

Complexity of Binary Search is O(log N)

N -> N/2 -> N/4 -> N/8 ........-> N/2^k

N/2^k is one element => N/2^k = 1 => N = 2^k => k =log N

K is the no of comparisons/iterations performed to search the required element


First and Last Position of an Element In Sorted Array
https://www.codingninjas.com/codestudio/problems/first-and-last-position-of-an-
element-in-sorted-array_1082549?
source=youtube&campaign=love_babbar_codestudio2&utm_source=youtube&utm_medium=affil
iate&utm_campaign=love_babbar_codestudio2&leftPanelTab=0

int firstocc(vector<int>& arr, int n, int k)


{
int s = 0;
int e = n-1;
int mid = s+(e-s)/2;
int ans = -1;
while(s<=e)
{
if(k==arr[mid])
{
ans = mid;
e = mid-1;
}
else if(k>arr[mid])
{
s=mid+1;
}
else if(k<arr[mid])
{
e = mid-1;
}
mid = s+(e-s)/2;
}
return ans;
}

int lastocc(vector<int>& arr, int n, int k)


{
int s = 0;
int e = n-1;
int mid = s+(e-s)/2;
int ans = -1;
while(s<=e)
{
if(k==arr[mid])
{
ans = mid;
s = mid+1;
}
else if(k>arr[mid])
{
s=mid+1;
}
else if(k<arr[mid])
{
e = mid-1;
}
mid = s+(e-s)/2;
}
return ans;
}
pair<int, int> firstAndLastPosition(vector<int>& arr, int n, int k)
{
// Write your code here
pair<int,int> p;
p.first = firstocc(arr,n,k);
p.second = lastocc(arr,n,k);
return p;
}

Find Peak in Mountain Array


https://leetcode.com/problems/peak-index-in-a-mountain-array/submissions/

O(N)
Find maximum element of the array

O(logN)
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int s = 0;
int e = arr.size()-1;
int mid = s+(e-s)/2;
while(s<e)
{
if(arr[mid]<arr[mid+1])
{
s = mid+1;
}
else
{
e = mid;
}
mid = s+(e-s)/2;
}
return s;
}
};

Find Pivot Index


https://leetcode.com/problems/find-pivot-index/

class Solution {
public:
int pivotIndex(vector<int>& nums) {
int tsum = 0;int ans = -1;
for(int i =0;i<nums.size();i++)
{
tsum+=nums[i];
}
int lsum = 0;
for(int i=0;i<nums.size();i++)
{
if(lsum == tsum-nums[i]-lsum)
{
ans= i;
break;
}
lsum+=nums[i];
}
return ans;
}
};

Replace every array element by multiplication of previous and next

Approach 1 Create a copy array and update the elements of the initial array using
copy array
O(n) and extra space O(n)

#include<bits/stdc++.h>
using namespace std;

void print(int A[], int n)


{
for(int i=0;i<n;i++)
{
cout<<A[i]<<" ";
}
}

void modify(int A[], int n)


{
int B[n];
for(int i=0;i<n;i++)
{
B[i]=A[i];
}
int fe = A[0]*A[1];
int le = A[n-2]*A[n-1];
for(int i=1;i<n-1;i++)
{
A[i]=B[i-1]*B[i+1];
}
A[0]=fe;
A[n-1]=le;
}

int main()
{
int A[]={2,3,4,5,6};
int n = sizeof(A)/sizeof(A[0]);
modify(A,n);
print(A,n);

return 0;
}

Approach 2 Store the value of prev element in loop and update array using prev
element
O(n) and O(1) space
#include<bits/stdc++.h>
using namespace std;

void print(int A[], int n)


{
for(int i=0;i<n;i++)
{
cout<<A[i]<<" ";
}
}

void modify(int A[], int n)


{
int first = A[0]*A[1];
int last = A[n-2]*A[n-1];
int y = A[0];
for(int i=1;i<n-1;i++)
{
int x = A[i];
A[i]= y*A[i+1];
y=x;
}
A[0]=first;
A[n-1]=last;
}

int main()
{
int A[]={2,3,4,5,6};
int n = sizeof(A)/sizeof(A[0]);
modify(A,n);
print(A,n);

return 0;
}

-----------------------------------------------------------------------------------
--------------

Segregate even and odd numbers while maintaining order of elements

Approach 1 Using temporary array and updating a index.


O(n) and O(n) space

#include<bits/stdc++.h>
using namespace std;

void evenodd(int A[], int n)


{
int B[n]; // Empty Array of same size
int c=0; // keeping count of index
for(int i=0;i<n;i++) // Loop only to store even elements
{
if((A[i]%2)==0)
{
B[c]=A[i]; //Storing even element at cth index.
c++; // Incrementing the index to store next element.
}
}
for(int i=0;i<n;i++) // Loop only to store odd elements
{
if((A[i]%2)!=0)
{
B[c]=A[i]; //Storing odd element at cth index(after all even elements).
c++; // Incrementing the index to store next element.
}
}
// We made changes in empty array so we need to print inside the function
itself

for(int i=0;i<n;i++)
{
cout<<B[i]<<" ";
}

int main()
{
int A[]={2,3,4,5,6};
int n = sizeof(A)/sizeof(A[0]);
evenodd(A,n);

return 0;
}

Approach 2 Pending

-----------------------------------------------------------------------------------
---

Write a program to reverse an array or string

Approach Swap elements at 0th and (n-1)th and similar using s and e.
O(n)

#include<bits/stdc++.h>
using namespace std;

void print(int A[],int n)


{
for(int i=0;i<n;i++)
{
cout<<A[i]<<" ";
}
}

void reverse(int A[], int n)


{
int s=0;
int e=n-1;
while(s<=e)
{
swap(A[s],A[e]); // Swapping first and last element
s++;// Incrementing to get to the next element
e--;// To get to the previous element
}
}

int main()
{
int A[]={1,2,3,4,5,6};
int n=sizeof(A)/sizeof(A[0]);
reverse(A,n);
print(A,n);

return 0;
}

---------------------------------------------------------------------------

Move all zeroes to end of array

Approach here we don't need copy array just keeping index of non zero elements and
0's and updating array.

#include<bits/stdc++.h>
using namespace std;

void print(int A[],int n)


{
for(int i=0;i<n;i++)
{
cout<<A[i]<<" ";
}
}

void zero(int A[], int n)


{
int c=0; // Maintaing index to segregate array.
for(int i=0;i<n;i++) //Loop to store non zero elements.
{
if(A[i]!=0)
{
A[c]=A[i];
c++;
}
}

for(int i=0;i<n;i++) //Loop to store 0's.


{
if(A[i]==0)
{
A[c]=A[i];
c++;
}
}
}

int main()
{
int A[]={1, 2, 0, 4, 3, 0, 5, 0};
int n=sizeof(A)/sizeof(A[0]);
zero(A,n);
print(A,n);
return 0;
}

-----------------------------------------------------------------------------------
-----

1 2 0 1 0 2

0 0 1 1 2 2

for(auto x: a)
{
++b[x];
}

2 2 2
b 0 1 2 3 4 5

You might also like