Add

Top 10 Array Coding Problems for Interviews

 

Find minimum and maximum element in an array


Here is the collection of the Top 10 list of frequently asked interviews question on arrays. Problems in this Article is divided into three Levels so that readers can practice according to the difficulty level step by step.

Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array.

 Example 1:

Input:

N = 6

A[] = {3, 2, 1, 56, 10000, 167}

Output:

min = 1, max =  10000

 

long max=a[0];
       long min=a[0];
       for(int i=0;i<n;i++)
       {
           max=Math.max(max,a[i]);
           min=Math.min(min,a[i]);
       }
       return (new pair(min,max));

Python Code; 

def getMinMax( a, n):
   max=a[0]
   for i in a:
       if i>max:
           max=i
       else:
           continue
   min=a[0]
   for i in a:
       if i<min:
           min=i
       else:
           continue
   return max,min;

Reverse a String;

You are given a string s. You need to reverse the string.

Example 1:

Input:
s = lerankro
Output: soronarel
 

 

string reverseWord(string str)

{
  
 int first=0, last=str.length()-1;
 while(first<last){
   swap(str[first], str[last]);
     first++;
     last--;
 }
 return str;
}

  char temp;
 for(int i=0,j=str.length()-1;i<j;i++,j--){
     temp=str[i];
     str[i]=str[j];
     str[j]=temp;
 }
 return str;

Sort The Array 

Given a random set of numbers, Print them in sorted order.

Example 1:

Input:
N = 4
arr[] = {1, 5, 3, 2}
Output: {1, 2, 3, 5}
Explanation: After sorting array will 
be like {1, 2, 3, 5}.

 

int[] sortArr(int[] arr, int n) { 
 int[] res = new int[n];
 int max = Arrays.stream(arr).max().getAsInt();
 int[] temp = new int[max + 1];
 // populating count array of each element count in org
 for (int i = 0; i < n; i++) {
  temp[arr[i]]++;
 }
 // doing cumulative sum
 for (int i = 1; i < temp.length; i++) {
  temp[i] = temp[i - 1] + temp[i];
 }
 // putting final values into final res
 for (int i = 0; i < n; i++) {
  res[temp[arr[i]] - 1] = arr[i];
  temp[arr[i]]--;
 }
 return res;
   }

vector<int> sortArr(vector<int>arr, int n){
       sort(arr.begin(), arr.end());
       
       return arr;

Kth smallest element 

Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.

Example 1:

Input:
N = 6
arr[] = 7 10 4 3 20 15
K = 3
Output : 7
Explanation :
3rd smallest element in the given 
array is 7.0

int kthSmallest(int arr[], int l, int r, int k)
   {
      int i, j, position, swap;
  for (i = 0; i < (r - 1); i++) {
     position = i;
     for (j = i + 1; j < r; j++) {
        if (arr[position] > arr[j])
           position = j;
     }
     if (position != i) {
        swap = arr[i];
        arr[i] = arr[position];
        arr[position] = swap;
     }
  }
        return arr[k-1];
   }

I am not getting the correct output for all test cases. I sorted the array in ascending order and then intended to retrieve the kth element

int kthSmallest(int arr[], int l, int r, int k) {
    
    priority_queue<int> pq;
    
    for(int i=0;i<=r;i++)
    {
        pq.push(arr[i]);
        while(pq.size()>k)pq.pop();
    }
      
      return pq.top();
   }

Find the Frequency

Given a vector of N positive integers and an integer X. The task is to find the frequency of X in vector.

 Example 1:

Input:
N = 5
vector = {1, 1, 1, 1, 1}
X = 1
Output: 
5
Explanation: Frequency of 1 is 5.

 

static int findTotalOccurence(int[] arr, int n, int occurenceOf) {
 int max = Arrays.stream(arr).max().getAsInt();
 int[] occurArr = new int[max + 1];
 for (int i = 0; i < n; i++) {
  occurArr[arr[i]]++;
 }
 return occurArr[occurenceOf];
}

 

 


 const findFrequency = (array, frequencyNumber) => {

const size = array.length;

let counter = 0;

// for (let i = 0; i< size; i++) {

// if (array[i] === frequencyNumber) {

// counter = counter + 1;

// }

// }


 array.forEach(element => {

if (element === frequencyNumber) {

counter = counter + 1;

}                                      

});


 return counter;

};

 
 Sort an array of 0s, 1s and

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.

Example 1:

Input: 
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated 
into ascending order.

Example 2:

Input: 
N = 3
arr[] = {0 1 0}
Output:
0 0 1
Explanation:
0s 1s and 2s are segregated 
into ascending order.

  void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

  int low = 0, mid = 0, high = n-1;
   

 while(mid <= high)
   {
       switch(a[mid])
       {
           case 0:
               swap(&a[low],&a[mid]);
               low++;
               mid++;
               break;
               
           case 1:
               mid++;
               break;

case 2:
               swap(&a[mid],&a[high]);
               high--;
               break;
       }
   }

void sort012(int arr[], int n)
   {
       // coode here 
        int zero=0;
   int one=0;int two=0;
   for(int i=0;i<n;i++)
   {
       if(arr[i]==0)
       {
           zero++;
       }
       if(arr[i]==1)
{
           one++;
       }
       if(arr[i]==2)
       {
           two++;
       }
   }
   int i=0;
  while(zero--)
   {
      arr[i]=0;
      i++;
   }
  while(one--)
{
      arr[i]=1;
      i++;
   }
  while(two--)
   {
      arr[i]=2;
      i++;
   }
   }
   
 

Subarray with given sum 

Given an unsorted array of size N that contains only non-negative integers, find a continuous sub-array which adds to a given number S.

 

Example 1:

Input:
N = 5, S = 12
A[] = {1,2,3,7,5}
Output: 2 4
Explanation: The sum of elements 
from 2nd position to 4th position 
is 12.

Example 2:

Input:
N = 10, S = 15
A[] = {1,2,3,4,5,6,7,8,9,10}
Output: 1 5
Explanation: The sum of elements 
from 1st position to 5th position
is 15.
vector<int> subarraySum(int arr[], int n, int s)
    {
        vector<int>v;
        int start=0,last=0,cs=0;
        while(start<=n and last<=n){
            if(cs==s)
            {
               v.push_back(start+1);
                v.push_back(last);
                return v;
            }
            if(cs>s){
                cs=cs-arr[start];
start++;
            }
            if(cs<s ){
                cs+=arr[last];
                last++;
            }
        }
        
       v.push_back(-1);
        return v;
    }
 

class Solution
{
   public:
   //Function to find a continuous sub-array which adds up to a given number.
   vector<int> subarraySum(int arr[], int n, int s)
   {
       int l=0,r=0;
       vector<int> vec;

  int sum=0;
       while(l<=n and r<=n){
           if(sum<s){
               sum+=arr[r];
               r++;
           }
           else if(sum>s){
               sum-=arr[l];
               l++;
           }
           else{
               vec.push_back(l+1);
               vec.push_back(r);
               return vec;

   }
       }
       vec.push_back(-1);
       return vec;
   }
};

Move all negative elements to end 
 
Given an unsorted array arr[] of size N having both negative and positive integers. The task is place all negative element at the end of array without changing the order of positive element and negative element.

Example 1:

Input : 
N = 8
arr[] = {1, -1, 3, 2, -7, -5, 11, 6 }
Output : 
1  3  2  11  6  -1  -7  -5

Example 2:

Input : 
N=8
arr[] = {-5, 7, -3, -4, 9, 10, -1, 11}
Output :
7  9  10  11  -5  -3  -4  -1

public void segregateElements(int arr[], int n)
   {
       int temp[]=new int[n];
       int c=0;
       for(int i=0;i<n;i++)
       {
           if(arr[i]>=0)
           {
           temp[c++]=arr[i];
           }
       }
       if(c==n|| c==0)
       return;
       for(int i=0;i<n;i++)

  {
           if(arr[i]<0)
           {
               temp[c++]=arr[i];
           }
       }
       for(int i=0;i<n;i++)
       {
           arr[i]=temp[i];
       }
       
   }

Union of two arrays

Given two arrays a[] and b[] of size n and m respectively. The task is to find union between these two arrays.

Union of the two arrays can be defined as the set containing distinct elements from both the arrays. If there are repetitions, then only one occurrence of element should be printed in the union.

Example 1:

Input:
5 3
1 2 3 4 5
1 2 3
Output: 
5
Explanation: 
1, 2, 3, 4 and 5 are the
elements which comes in the union set
of both arrays. So count is 5.

Example 2:

Input:
6 2 
85 25 1 32 54 6
85 2 
Output: 
7
Explanation: 
85, 25, 1, 32, 54, 6, and
2 are the elements which comes in the
union set of both arrays. So count is 7.

int doUnion(int a[], int n, int b[], int m)  {
       set<int> v;
       for(int i=0; i<n; i++){
           v.insert(a[i]);
       }
       for(int i=0; i<m; i++){
           v.insert(b[i]);
       }
       int count=0;
       for(auto s:v)

}

    count++;
       }
       
       return count;
       
       
   }

can anyone tell me whats wrong with this code it works fine with test cases but it is stuck at test case.

public static int doUnion(int a[], int n, int b[], int m) 
   {
       //Your code here
       ArrayList <Integer> al = new ArrayList<>();
       int i = 0 ,j=0;
       while(i!=n||j!=m){
           if(j==m){
              al.add(a[i]);

  i++;
              continue;
           }else if(i==n){
              al.add(b[j]);
              j++;
              continue;
           }
           if(a[i]<b[j]){
               al.add(a[i]);
               i++;
           }else if(a[i]>b[j]){
               al.add(b[j]);
               j++;

 }else if(a[i]==b[j]){
               al.add(a[i]);
               i++;
               j++;
           }
       }
       return al.size();
   }
}

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.