1) Find a Missing number in an integer array of 1 to 100
This class finds the missing number from an array It uses two approaches
a)Using sum of first n numbers which is n(n+1)/2, and
subtract each of the array elements from the sum, which
gives the missing number.
b) Using XOR, Which finds the XOR of all numbers in the
given array, and also the XOR of first n numbers the XOR for these two calculations will give the missing number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the missing number from an array | |
* It uses two approaches | |
* | |
* 1)Using sum of first n numbers which is n(n+1)/2, and | |
* subtract each of the array elements from the sum, which | |
* gives the missing number. | |
* | |
* | |
* 2) using XOR, Which finds the XOR of all numbers in the | |
* given array, and also the XOR of first n numbers | |
* the XOR for these two calculations will give the missing number | |
* | |
*/ | |
public class FindMissingNumberInArray { | |
/** | |
* | |
* @param array | |
* @return | |
*/ | |
private int missingNumberFormula(int array[],int n) { | |
int sumOfNNumbers = n*(n+1)/2; | |
if(array!=null && array.length>0) { | |
for(int elem : array) { | |
sumOfNNumbers -= elem; | |
} | |
} | |
System.out.println(" The missng number from the list is "+sumOfNNumbers); | |
return sumOfNNumbers; | |
} | |
/** | |
* | |
* @param array | |
* @return | |
*/ | |
private int missingNumberUsingXOR(int array[],int n) { | |
int result = 0; | |
int arrayElemsXOR = 0; | |
int firstNNumbersXOR = 0; | |
if(array!=null && array.length>0) { | |
for(int elem:array) { | |
arrayElemsXOR ^=elem; | |
} | |
} | |
for(int i=1;i<=n;i++) { | |
firstNNumbersXOR ^=i; | |
} | |
result = arrayElemsXOR^firstNNumbersXOR; | |
return result; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
FindMissingNumberInArray findMissingNumberInArray = new FindMissingNumberInArray(); | |
int input[] = new int[]{1,2,4,6,7,8,9,10}; | |
int n = 10; | |
int missingNumberFormula = findMissingNumberInArray.missingNumberFormula(input,n); | |
System.out.println(" Missing Number Using Formula is "+ missingNumberFormula); | |
int missingNumberXor = findMissingNumberInArray.missingNumberUsingXOR(input,n); | |
System.out.println(" Missing Number Using XOR is "+ missingNumberXor); | |
} | |
} |
2) Find 2 Missing Numbers from an Array
This class finds two missing numbers from an Array
It uses the XOR approach to find the results, and uses the three step approach
First will do the XOR to find the missing number(which could be the sum of the two numbers, says 3 and 5 are missing from the Array,We get 8, as the Array is sorted 8 can not be the sum of 4 and 4. So 8 has to be the sum of one number less than 4(half of it) and one number more than it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.test.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds two missing numbers from an Array | |
* | |
* It uses the XOR approach to find the results | |
* and uses the three step approach | |
* | |
* First will do the XOR to find the missing number(which could be | |
* the sum of the two numbers, says 3 and 5 are missing from the Array, | |
* We get 8, as the Array is sorted 8 can not be the sum of 4 and 4. | |
* So 8 has to be the sum of one number less than 4(half of it) and | |
* one number more than it | |
* | |
*/ | |
public class FindTwoMissingNumbers { | |
/** | |
* This method finds the missing two numbers from the Array | |
* | |
* @param input | |
* @param n | |
* @return | |
*/ | |
private int[] missingTwoNumbers(int[] input,int n) { | |
int result [] = new int[2]; | |
int XOROfAllNElements = 0; | |
int XOROfAArrayElements = 0; | |
int sumOfMissingNumbers = 0; | |
//Sum of All Array Elements | |
if(input!=null && input.length>0) { | |
for(int element : input ) { | |
XOROfAArrayElements ^=element; | |
} | |
} | |
//Sum of First N Numbers | |
for(int i=1;i<=n;i++) { | |
XOROfAllNElements ^=i; | |
} | |
//Sum of Missing Numbers | |
sumOfMissingNumbers = XOROfAArrayElements^XOROfAllNElements; | |
int middle = sumOfMissingNumbers/2; | |
System.out.println(" middle "+ middle+" sumOfMissingNumbers " | |
+sumOfMissingNumbers); | |
int middleLessXOR = 0; | |
for(int i=1;i<=middle;i++) { | |
middleLessXOR ^=i; | |
} | |
int XOROfArrayElementsUpToMiddle = 0; | |
for(int i=0;i<=n-1;i++) { | |
if(input[i]<=middle) { | |
XOROfArrayElementsUpToMiddle^=input[i]; | |
} else { | |
break; | |
} | |
} | |
result[0] = middleLessXOR^XOROfArrayElementsUpToMiddle; | |
System.out.println(" middleLessXOR "+middleLessXOR | |
+" XOROfArrayElementsUpToMiddle "+XOROfArrayElementsUpToMiddle | |
+" result[0] "+result[0]); | |
int middleMoreXOR = 0; | |
for(int i=middle+1;i<=n;i++) { | |
middleMoreXOR ^=i; | |
} | |
int XOROfAllElementsAfterMiddle = 0; | |
for(int i=0;i<input.length;i++) { | |
if(input[i]>middle) { | |
XOROfAllElementsAfterMiddle^=input[i]; | |
} | |
} | |
result[1] = middleMoreXOR^XOROfAllElementsAfterMiddle; | |
System.out.println(" middleMoreXOR "+middleMoreXOR | |
+" XOROfAllElementsAfterMiddle "+XOROfAllElementsAfterMiddle); | |
return result; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
FindTwoMissingNumbers findTwoMissingNumbers = new FindTwoMissingNumbers(); | |
int[] inputArray = new int[]{1,2,4,6,7,8,9,10}; | |
int n = 10; | |
int [] resultArray = findTwoMissingNumbers.missingTwoNumbers(inputArray, n); | |
System.out.println(" The missing numbers from the Array are as follows "); | |
if(resultArray!=null && resultArray.length>0) { | |
for(int i : resultArray) { | |
System.out.print(" "+i); | |
} | |
} | |
} | |
} |
3) Find First Non-Repeating elements in an array of Integers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.datastructures.array; | |
import java.util.HashSet; | |
import java.util.Set; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the first Non Repeating | |
* element in an Array | |
* | |
* It uses the approach to store the array using a | |
* HashSet, and parses the Array from right to left | |
* once the first(0th index) element is reached, We have | |
* the desired element, whether it is repeated or non-repeated | |
* element. | |
* | |
*/ | |
public class FirstRepeatingAndNonRepeatingElements { | |
/** | |
* | |
* @param elements | |
* @return | |
*/ | |
private int firstRepeatedElement(int[] elements) { | |
int firstRepeatedElement = -1; | |
if(elements!=null && elements.length>0) { | |
Set<Integer> setOfElements = new HashSet<>(); | |
for(int i=elements.length-1;i>=0;i--){ | |
if(setOfElements.contains(elements[i])) { | |
firstRepeatedElement = elements[i]; | |
} else { | |
setOfElements.add(elements[i]); | |
} | |
} | |
} | |
return firstRepeatedElement; | |
} | |
private int firstNonRepeatedHashSet(int [] elements) { | |
int firstNonRepatedElement = -1; | |
Set<Integer> hashOfElements = new HashSet<Integer>(); | |
if(elements!=null && elements.length>0) { | |
for(int i=elements.length-1;i>=0;i--) { | |
if(!hashOfElements.contains(elements[i])) { | |
hashOfElements.add(elements[i]); | |
firstNonRepatedElement = elements[i]; | |
} | |
} | |
} | |
return firstNonRepatedElement; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement = | |
new FirstRepeatingAndNonRepeatingElements(); | |
int[] input = new int[]{1,5,3,4,3,5,6,1}; | |
int firstRepeatedElement = firstNonRepeatingElement. | |
firstRepeatedElement(input); | |
System.out.println(" The First Repating Element is " | |
+ firstRepeatedElement); | |
int firstNonRepeatedElement = firstNonRepeatingElement. | |
firstNonRepeatedHashSet(input); | |
System.out.println(" The First Non Repating Element is " | |
+ firstNonRepeatedElement); | |
} | |
} |
4) Compare two integer arrays efficiently
5) Sort Elements in an Array using Various Sorting Techniques
6) How do You find duplicate number on Integer array in Java
7) Find smallest and Largest numbers in an Integer Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.test.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the Largest and Smallest numbers from the | |
* given Array. | |
* | |
* To implement this in O(n) time we create two temporary variables | |
* and store some array[0] value in them. Next start iterating through the | |
* Array, if any element is found greater than default Max, make the element | |
* as the Max, If any element is found less than the default Min, make the | |
* element as the Min. | |
* | |
* After Iterating through the Array, the Min, and Max will have the | |
* Minimum and Maximum elements from the Array. | |
* | |
*/ | |
public class LargestAndSmallest { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
LargestAndSmallest largestAndSmallest = new LargestAndSmallest(); | |
int[] result = largestAndSmallest.findLargestAndSmallest(new int[]{2,5,6,1,7,10,-1}); | |
for(int a:result) { | |
System.out.println(a); | |
} | |
} | |
/** | |
* | |
* @return | |
*/ | |
//2,5,6,1,7,10 | |
private int[] findLargestAndSmallest(int input[]) { | |
int[] resultArray = new int[2]; | |
int largest=input[0]; | |
int smallest=input[0]; | |
if(input!=null && input.length>0) { | |
for(int element : input) { | |
if(element>largest) { | |
largest = element; | |
} else if(element<smallest) { | |
smallest = element; | |
} | |
} | |
} | |
resultArray[0] = largest; | |
resultArray[1] = smallest; | |
return resultArray; | |
} | |
} |
8) Find repeated numbers in an array, if it contains multiple duplicates
9) Remove duplicates from an array
10) Find intersection of two sorted arrays in Java
11) Find Kth Smallest element in unsorted Array
12) Find Kth Largest element in unsorted Array
13) Find first repeating elements in an array of Integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.datastructures.array; | |
import java.util.HashSet; | |
import java.util.Set; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the first Non Repeating | |
* element in an Array | |
* | |
* It uses the approach to store the array using a | |
* HashSet, and parses the Array from right to left | |
* once the first(0th index) element is reached, We have | |
* the desired element, whether it is repeated or non-repeated | |
* element. | |
* | |
*/ | |
public class FirstRepeatingAndNonRepeatingElements { | |
/** | |
* | |
* @param elements | |
* @return | |
*/ | |
private int firstRepeatedElement(int[] elements) { | |
int firstRepeatedElement = -1; | |
if(elements!=null && elements.length>0) { | |
Set<Integer> setOfElements = new HashSet<>(); | |
for(int i=elements.length-1;i>=0;i--){ | |
if(setOfElements.contains(elements[i])) { | |
firstRepeatedElement = elements[i]; | |
} else { | |
setOfElements.add(elements[i]); | |
} | |
} | |
} | |
return firstRepeatedElement; | |
} | |
private int firstNonRepeatedHashSet(int [] elements) { | |
int firstNonRepatedElement = -1; | |
Set<Integer> hashOfElements = new HashSet<Integer>(); | |
if(elements!=null && elements.length>0) { | |
for(int i=elements.length-1;i>=0;i--) { | |
if(!hashOfElements.contains(elements[i])) { | |
hashOfElements.add(elements[i]); | |
firstNonRepatedElement = elements[i]; | |
} | |
} | |
} | |
return firstNonRepatedElement; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement = | |
new FirstRepeatingAndNonRepeatingElements(); | |
int[] input = new int[]{1,5,3,4,3,5,6,1}; | |
int firstRepeatedElement = firstNonRepeatingElement. | |
firstRepeatedElement(input); | |
System.out.println(" The First Repating Element is " | |
+ firstRepeatedElement); | |
int firstNonRepeatedElement = firstNonRepeatingElement. | |
firstNonRepeatedHashSet(input); | |
System.out.println(" The First Non Repating Element is " | |
+ firstNonRepeatedElement); | |
} | |
} |
14) Check if an array contains numbers in java(if it contains string and integer)
15) Top 2 numbers form an integer array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.test.array; | |
import java.util.Arrays; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the top 2 numbers from an | |
* Array. | |
* | |
* For that purpose it used two variables to store some | |
* default values, and start iterating through the array | |
* once iterating through the array, if an element more | |
* the default max value, that will be replaced with the max, | |
* and max goes to 2ndMax. Otherwise if the element is less | |
* than the Max Element, but more than the 2nd Max Element, | |
* that element will take the 2Max Element place. | |
* | |
* Once the iterations on the Array are completed, We have the | |
* Max, and 2ndMax Elements. | |
* | |
*/ | |
public class TopTwoNumbersInArray { | |
/** | |
* | |
* @param a | |
* @return | |
*/ | |
private int[] twoMaxNumbers(int a[]) { | |
int[] resultArray = new int[2]; | |
int maxElement = Integer.MIN_VALUE; | |
int secondMax = Integer.MIN_VALUE; | |
if(a!=null && a.length>0) { | |
for(int element : a) { | |
if(element>maxElement) { | |
secondMax = maxElement; | |
maxElement = element; | |
} else if(element>secondMax) { | |
secondMax = element; | |
} else { | |
// System.out.println(" The element is neither" | |
// + " less than any of these elements" | |
// + ""+element); | |
} | |
} | |
resultArray[0] = maxElement; | |
resultArray[1] = secondMax; | |
} else { | |
return resultArray; | |
} | |
return resultArray; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
TopTwoNumbersInArray topTwoNumbersInArray = | |
new TopTwoNumbersInArray(); | |
int[] input = new int[]{4,6,9,19,16,15,18,5,6,1,3,-8,-9,10000}; | |
int[] result = topTwoNumbersInArray.twoMaxNumbers(input); | |
System.out.println(" The max Two elements from the Array are "); | |
if(result!=null && result.length>0) { | |
System.out.println(Arrays.toString(result)); | |
} | |
} | |
} |
16) Remove a given element from an array
17) Remove duplicates from an array
18) Merge 2 integer arrays
19) Find PeakElement of An Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class is used to find the Peak Element of an | |
* Array. | |
* | |
* An Array can contain multiple Peak Elements, | |
* We need return one of the Peak Elements. | |
* | |
* We use Binary Search to find the Peak Element, Will | |
* start with middle element, if it has the lest side and | |
* right side elements less than to it, then that is the Peak | |
* Element. | |
* | |
* If the Left side element is greater than the element, the | |
* Peak will be on the left side of the Middle element | |
* | |
* If the Right side element is greater than the element, | |
* the Peak will be on the right side of the Middle element | |
* | |
*/ | |
public class PeakElement { | |
/** | |
* | |
* @param input | |
* @param low | |
* @param high | |
* @return | |
*/ | |
private int findPeakElement(int input[],int low,int high) { | |
int middle = (low+high)/2; | |
int peakElement = -1; | |
if(middle==0 || input[middle]>=input[middle-1] && | |
middle==input.length-1 || input[middle]>=input[middle+1]) { | |
return input[middle]; | |
} else if(middle>0 && input[middle]<input[middle-1]) { | |
peakElement = findPeakElement(input, low, middle-1); | |
} else { | |
peakElement = findPeakElement(input, middle+1, high); | |
} | |
return peakElement; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
PeakElement peakElement = new PeakElement(); | |
int[] input = new int[]{1,2,3,4,5,25,6,8}; | |
int peak = peakElement.findPeakElement(input, 0, input.length-1); | |
System.out.println(" The Peak Element of the Array is "+ peak); | |
} | |
} |
20) Find Fixed Point or Magic Index of an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the fixed Point or Magic Index | |
* of any array such that index of an element becomes | |
* equal to the element., i.e.,i=a[i] | |
* | |
* The Array is sorted and can contain negative numbers as well | |
* | |
* Since the Array is Sorted We can use Binary Search rather than | |
* Linear Search to achieve logN time complexity | |
* | |
*/ | |
public class FixedPointOrMagicIndex { | |
/** | |
* | |
* @return | |
*/ | |
private int findFixedPointOrMagicNumber(int[] array,int low,int high) { | |
int mid = (low+high)/2; | |
int result = 0; | |
if(array[mid]==mid) { | |
return mid; | |
} else { | |
if(mid>array[mid]) { | |
result = findFixedPointOrMagicNumber(array, mid+1, high); | |
} else if(array[mid]>mid) { | |
result = findFixedPointOrMagicNumber(array, low, mid-1); | |
} else { | |
result = -1; | |
} | |
} | |
return result; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
FixedPointOrMagicIndex fixedPointOrMagicIndex = new FixedPointOrMagicIndex(); | |
int[] array = new int[]{-10,-9,1,2,3,7,6,9,10}; | |
int fixedPoint = | |
fixedPointOrMagicIndex. | |
findFixedPointOrMagicNumber(array, 0, array.length-1); | |
System.out.println(" The Fixed Point of the Array is "+fixedPoint); | |
} | |
} |
21) Replace Every Element in the Array with the Greatest element to it's Right.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class replaces Every Element with the greatest | |
* element on it's right. The far right most element does | |
* not have any elements to it's right, so that will be | |
* replaced by -1 | |
* | |
* The approach followed is to traverse the elements from the | |
* right side, and start the update with right most element value set | |
* to -1.Take the current element value(buffer), and continue to traverse from | |
* right to left,keep the current value if no greater value is found, and | |
* replace the subsequent elements with this value, if any greater value | |
* than the current value(buffer) is found, replace the existing value, | |
* use the greater value for replacement | |
* | |
* | |
*/ | |
public class ReplaceElementWithGreatestOnRight { | |
/** | |
* | |
* @param array | |
* @return | |
*/ | |
private int[] replaceElementsWithGreaterValueOnRight(int[] array) { | |
int greaterElement = Integer.MIN_VALUE; | |
int buffer = 0; | |
if(array!=null && array.length>0) { | |
buffer = array[array.length-1]; | |
greaterElement = array[array.length-1]; | |
array[array.length-1] = -1; | |
for(int i=array.length-2;i>=0;i--) { | |
if(array[i]>buffer) { | |
buffer = array[i]; | |
array[i] = greaterElement; | |
} else { | |
array[i] = buffer; | |
greaterElement = buffer; | |
} | |
} | |
} | |
return array; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
ReplaceElementWithGreatestOnRight replaceElementWithGreatestOnRight = | |
new ReplaceElementWithGreatestOnRight(); | |
int[] array = new int[]{16,17,4,3,5,2}; | |
int[] resultArray = | |
replaceElementWithGreatestOnRight.replaceElementsWithGreaterValueOnRight(array); | |
if(resultArray!=null && resultArray.length>0) { | |
for(int resultArrayElem : resultArray) { | |
System.out.print(" "+resultArrayElem); | |
} | |
} | |
} | |
} |
22) Find Odd Number of times Occurring Element in an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class is used to find the number that is present in an array | |
* for odd number of times. | |
* | |
* It uses the XOR logic, as XOR for a number with the same number will | |
* become 0, the last remaining element is the Odd number of times occurring | |
* element | |
* | |
*/ | |
public class NumberWithOddOcuuranceCount { | |
/** | |
* | |
* @return | |
*/ | |
private int findNumberWithOddOccurances(int [] array) { | |
int xorOfAllElements = 0; | |
if(array!=null && array.length>0) { | |
for( int element : array) { | |
xorOfAllElements ^=element; | |
} | |
} | |
return xorOfAllElements; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
NumberWithOddOcuuranceCount numberWithOddOcuuranceCount = new | |
NumberWithOddOcuuranceCount(); | |
int [] array = new int[]{1,1,2,2,3,3,2,2,5,5,3,6,6,4,4}; | |
int result = | |
numberWithOddOcuuranceCount.findNumberWithOddOccurances(array); | |
System.out.println(" The Odd number of times Occuring element is "+result); | |
} | |
} |
23) Find Majority Element in an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
/** | |
* @author kkanaparthi | |
* | |
* This class finds the Majority Element, which occurs | |
* at least n/2 times, if no such element is present return 0 | |
* | |
* First It finds the MajorityElement candidate by using the | |
* Moore's Voting Algorithm, which assumes a default Majority | |
* Element, and iterates through all the elements of the Array. | |
* Increases the count if the same element is found, if same element | |
* is not found, the count is decreased, whenever the count becomes 0 | |
* the majorityElementCandidate is replaced with the current iterating | |
* element, and the count is also reinitialized to 1. After this iteration | |
* is completed, if an element is remaining treat that as the Majority | |
* Element candidate. | |
* | |
* The Next steps finds out if the MajorityElement candidate is actually | |
* a MajorityElement.(It is like Primary and Major elections). Iterate | |
* through all the elements of the Array and look for the MajorityElement | |
* candidate, if the count is greater than or equal to the n/2 then the | |
* MajorityElement candidate is the Majority Element of the Array | |
* | |
*/ | |
public class MajorityElementWithMooresVotingAlgorithm { | |
/** | |
* This method finds the Majority Element from | |
* the Array | |
* | |
* @return | |
*/ | |
private int getMajorityElement(int[] input) { | |
int candidateForMajorityElement = 0; | |
int maxCountForMajorityElement = 0; | |
int elementCount = 1; | |
if(input!=null && input.length>0) { | |
candidateForMajorityElement = input[0]; | |
maxCountForMajorityElement = | |
input.length/2; | |
for(int i=1;i<input.length;i++) { | |
if(input[i]==candidateForMajorityElement) { | |
elementCount++; | |
} else { | |
elementCount--; | |
} | |
if(elementCount==0) { | |
candidateForMajorityElement = input[i]; | |
elementCount = 1; | |
} | |
} | |
} | |
int totalCounts = | |
findMajorityCandidateOccurancesHelper | |
(input, candidateForMajorityElement); | |
System.out.println(" elementCount "+elementCount | |
+" totalCounts "+totalCounts | |
+" maxCountForMajorityElement "+maxCountForMajorityElement); | |
if((totalCounts<maxCountForMajorityElement)) { | |
candidateForMajorityElement = -1; | |
} | |
return candidateForMajorityElement; | |
} | |
/** | |
* This method is a helper method to find | |
* the occurrences of the given number | |
* | |
* @return | |
*/ | |
private int findMajorityCandidateOccurancesHelper(int[] array,int element) { | |
int elementCount = 0; | |
if(array!=null && array.length>0) { | |
for(int elem : array) { | |
if(elem==element) { | |
elementCount++; | |
} | |
} | |
} | |
return elementCount; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
MajorityElementWithMooresVotingAlgorithm majorityElement = | |
new MajorityElementWithMooresVotingAlgorithm(); | |
int [] inputGood = new int[]{1,2,2,4,5,3,2,2,2,6,2}; | |
int resultElement = majorityElement.getMajorityElement(inputGood); | |
System.out.println(" The Majority Element is "+resultElement); | |
int [] inputError = new int[]{1,2,2,4,5,3,2,2,2,6,2,1,3,4}; | |
int resultElementError = majorityElement.getMajorityElement(inputError); | |
System.out.println(" The Majority Element is "+resultElementError); | |
} | |
} |
24) Find Leader Elements in an Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.datastructures.array; | |
import java.util.Arrays; | |
/** | |
* @author kkanaparthi | |
* | |
* This class is used to find the Leader Elements in an Array | |
* Leader Element in an Array is such that all the elements to | |
* the right of it are less than the element, and the right most | |
* element is the Leader by default | |
* | |
*/ | |
public class LeaderElements { | |
/** | |
* This method returns the Leader Elements from | |
* the given array | |
* | |
* @param input | |
* @return | |
*/ | |
private int[] getLeaderElements(int input[]) { | |
int[] leadersArray = null; | |
int j = 1; | |
int currentMaximum = Integer.MIN_VALUE; | |
if(input!=null && input.length>0) { | |
leadersArray = new int[input.length]; | |
Arrays.fill(leadersArray, -1); | |
int rightMostElement = input[input.length-1]; | |
leadersArray[0] = rightMostElement; | |
currentMaximum = rightMostElement; | |
for(int i=input.length-2;i>=0;i--) { | |
if(input[i]>currentMaximum) { | |
leadersArray[j] = input[i]; | |
currentMaximum = input[i]; | |
j++; | |
} | |
} | |
} | |
return leadersArray; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
LeaderElements leaderElements = new LeaderElements(); | |
int[] elements = new int[]{2,3,5,6,11,8,10,1,3}; | |
int[] resultArray = leaderElements.getLeaderElements(elements); | |
if(resultArray!=null && resultArray.length>0) { | |
for(int elem : resultArray) { | |
System.out.print(" "+elem); | |
} | |
} | |
} | |
} |
25) Reverse an array in-place
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
*/ | |
package com.test.array; | |
import java.util.Arrays; | |
/** | |
* @author kkanaparthi | |
* This class is used to reverse an array InPlace | |
* To copy We just need to flip the elements from the beginning | |
* with the elements at the end, until the size reaches the | |
* middle | |
*/ | |
public class ReverseArrayInPlace { | |
private int[] reverseArray(int a[]) { | |
if(a==null || a.length==0) { | |
return a; | |
} else { | |
for(int i=0;i<a.length/2;i++) { | |
int temp = a[i]; | |
a[i] = a[a.length-1-i]; | |
a[a.length-1-i] = temp; | |
} | |
} | |
return a; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
ReverseArrayInPlace reverseArrayInPlace = new ReverseArrayInPlace(); | |
int[] input = new int[]{1,2,4,5,6,7,8,3,9}; | |
int[] reverseArray = reverseArrayInPlace.reverseArray(input); | |
if(reverseArray!=null && reverseArray.length>0) { | |
System.out.println(Arrays.toString(input)); | |
} | |
} | |
} |
Comments
Post a Comment