Coding Problem: Array GFG ( Level 1 )
Motivation
In my firm there is a test that we all needs to clear, and this test consists of the competitive coding problems, so to prepare for that i am coding and documenting my preparations.
- Peak Element
- Find the minimum and maximum element in an array
- Write a program to reverse the array
- Write a program to sort the given array
- Find the Kth largest and Kth smallest number in an array
- Find the occurrence of an integer in the array
- Sort the array of 0s, 1s, and 2s
- Subarray with given Sum
- Move all the negative elements to one side of the array
- Find the Union and Intersection of the two sorted arrays
Solution
- To find a peak element index, traverse and find a maxiumum element by comparing and then store the index of the element at a position and then return that index value.
public int peakElement(int[] arr,int n)
{
//add code here.
// Your code here
int maximum=-32000;
int maximumIndex=0;
for(int i=0;i<arr.length;i++) {
if(arr[i]>maximum) {
maximum=arr[i];
maximumIndex=i;
}
}
return maximumIndex;``
}
- To find a minimum and maximum in an array just sort the array and return the starting and ending position from the array
static pair getMinMax(long a[], long n)
{
Arrays.sort(a);
return new pair(a[0],a[a.length-1]);
}
- reverse a string: use stringbuilder to create new object and then use inbuild functions of the stringbuilder to reverse and then call the toString method
public static String reverseWord(String str)
{
StringBuilder reversedBuilder = new StringBuilder(str);
reversedBuilder.reverse();
return reversedBuilder.toString();
}
Sort the array: using the arrays.sort method
find the kth mimum element
public static int kthSmallest(int[] arr, int l, int r, int k)
{
Arrays.sort(arr);
return arr[k-1];
}
- we need to find how many times a single element occured in the array
int findFrequency(int A[], int x){
int counter=0;
for(int a:A) {
if(a==x) {
counter++;
}
}
return counter;
}
7.