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.

  1. Peak Element
  2. Find the minimum and maximum element in an array
  3. Write a program to reverse the array
  4. Write a program to sort the given array
  5. Find the Kth largest and Kth smallest number in an array
  6. Find the occurrence of an integer in the array
  7. Sort the array of 0s, 1s, and 2s
  8. Subarray with given Sum
  9. Move all the negative elements to one side of the array
  10. Find the Union and Intersection of the two sorted arrays

Solution

  1. 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;``

    }
  1. 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]);

    }
  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();

    }
  1. Sort the array: using the arrays.sort method

  2. find the kth mimum element

public static int kthSmallest(int[] arr, int l, int r, int k) 
    { 
        Arrays.sort(arr);    
        return arr[k-1];
    }
  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.