Arrays


An array is a data structure that is designed to store a group of objects of the same or different types. Arrays can hold primitives as well as references. The array is the most efficient data structure for storing and accessing a sequence of objects.

You can access the below link for the details discussion on Arrays.


Important Questions on Arrays-

Java Program To Find Duplicate Elements In An Array Using Set :

import java.util.HashSet;
/**
 * Test class to find the duplicate element
 * adding in set which wouldn't allow duplicate
 * @author Manoj
 */
public class Test {
   public static void main(String[] args) {
     String[] strArray = { "abc", "def", "mno", "xyz", "pqr", "xyz", "def" };
     HashSet<String> set = new HashSet<>();
     for (String arrayElement : strArray) {
         if (!set.add(arrayElement)) {
              System.out.println("Duplicate Element is : " + arrayElement);
           }
        }
    }
}


Java Program To Find 2nd largest Elements In An Array :

/**
 * Test class to find 2nd largest element
 * @author Manoj
 */
public class Test {
   static int secondLargest(int[] input) {
   int firstLargest, secondLargest;
   if (input[0] > input[1]) {
       firstLargest = input[0];
       secondLargest = input[1];
     } else {
       firstLargest = input[1];
       secondLargest = input[0];
     }
   for (int i = 2; i < input.length; i++) {
       if (input[i] > firstLargest) {
           secondLargest = firstLargest;
           firstLargest = input[i];
        } else if (input[i] < firstLargest && input[i] > secondLargest) {
              secondLargest = input[i];
        }
     }
    return secondLargest;
   }
   public static void main(String[] args) {
       System.out.println(secondLargest(new int[] { 45, 51, 28, 75, 51, 42 }));
   }
}

Find all pairs of element whose sum is equal to given number:

/**
 * Test class to find pairs of element with given sum
 * @author Manoj
 */
public class Test {
    static void findThePairs(int inputArray[], int inputNumber) {
    // Sorting the given array
    Arrays.sort(inputArray);
    System.out.println("Pairs of elements whose sum is " + inputNumber + " are : ");
    int i = 0;
    int j = inputArray.length - 1;
    while (i < j) {
      if (inputArray[i] + inputArray[j] == inputNumber) {
       System.out.println(inputArray[i] + " + " + inputArray[j] + " = " + inputNumber);
       i++;
       j--;
      }
      else if (inputArray[i] + inputArray[j] < inputNumber) {
        i++;
      }
      else if (inputArray[i] + inputArray[j] > inputNumber) {
        j--;
       }
     }
   }

  public static void main(String[] args) {
    findThePairs(new int[] { 4, 6, 5, -10, 8, 5, 20 }, 10);
    findThePairs(new int[] { 4, -5, 9, 11, 25, 13, 12, 8 }, 20);
  }
}

How To Bring Zeros To The Front or End Of An Array?

import java.util.Arrays;
/**
 * Test class to move all zero in front
 * @author Manoj
 */
public class Test {
  static void moveZerosToFront(int inputArray[]) {
  int counter = inputArray.length - 1;
  for (int i = inputArray.length - 1; i >= 0; i--) {
     if (inputArray[i] != 0) {
         inputArray[counter] = inputArray[i];
         counter--;
       }
     }
    while (counter >= 0) {
         inputArray[counter] = 0;
         counter--;
      }
    System.out.println(Arrays.toString(inputArray));
   }

  public static void main(String[] args) {
     moveZerosToFront(new int[] { 12, 0, 7, 0, 8, 0, 3 });
     moveZerosToFront(new int[] { -4, 1, 0, 0, 2, 21, 4 });
   }
}

Java Program To Find Continuous Sub Array In Array Whose Sum Is Equal To Number:

import java.util.Arrays;
/**
 * Test class to find subarray of given sum
 * @author Manoj
 */
public class Test {
  static void findSubArray(int[] inputArray, int inputNumber) {
  int sum = inputArray[0];
  int start = 0;
  for (int i = 1; i < inputArray.length; i++) {
     sum = sum + inputArray[i];
     while (sum > inputNumber && start <= i - 1) {
       sum = sum - inputArray[start];
       start++;
      }
      if (sum == inputNumber) {
      System.out.println("Continuous sub array of " + Arrays.toString(inputArray) + " whose sum is "+ inputNumber + " is ");
      for (int j = start; j <= i; j++) {
        System.out.print(inputArray[j] + " ");
       }
       System.out.println();
     }
    }
  }

 public static void main(String[] args) {
   findSubArray(new int[] { 42, 15, 12, 8, 6, 32 }, 26);
   findSubArray(new int[] { 12, 5, 31, 13, 21, 8 }, 49);
  }
}

Find missing number between 1-N sequence

Explaination -  Sum of n numbers is (n*(n+1))/2 so subtract the sum of array from actual sum and we will get the mising number

/**
 * Test class to find missing number in a series
 * @author Manoj
 */
public class Test {
   public static void main(String[] args) {
      int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      System.out.println(findMissingNumber(array));
   }

  private static int findMissingNumber(int array[]) {
     int arrSum = 0;
     for (int count = 0; count < array.length; count++) {
         arrSum = arrSum + array[count];
       }
      return (findSumOfNnum(10) - arrSum);
     }

   private static int findSumOfNnum(int num) {
      int sum = (num * (num + 1)) / 2;
       return sum;
   }
}

Find all missing number between 1-N sequence

/**
 * Test class to find all missing number in a series
 * @author Manoj
 */
public class Test {

   public static int count = 0;
   public static int arrayIndex = 0;
   public static boolean flag = false;

   public static void main(String[] args) {
        int a[] = { 0, 2, 3, 5, 7, 9, 10, 12, 14 };
        findMissingNumbers(a, arrayIndex);
     }

   private static void findMissingNumbers(int a[], int arrayIndex) {
      if (arrayIndex == a.length - 1) {
          return;
      }
      for (; arrayIndex < a[a.length - 1]; arrayIndex++) {
          if ((a[arrayIndex] - count) != arrayIndex) {
                System.out.println("Missing Number: " + (arrayIndex + count));
                flag = true;
                count++;
                break;
             }
         }
       if (flag) {
          flag = false;
          findMissingNumbers(a, arrayIndex);
       }
    }
}


1 comment: