Array Flashcards
Find majority element in array
Use Moore Voting algo. Also can use Binary searh tree
public class Solution{ public int majorityElement(final int[] A) { int count = 0; int maj_element = 0; for(int i = 0; i < A.length; i++){ if(count == 0) maj_element = A[i]; if(A[i] == maj_element) count++; else count--; } count = 0; for(int i = 0; i < A.length; i++){ if(A[i] == maj_element) count++; if(count > A.length/2) return maj_element; } return -1; } }
Find median of sorted array of equal size
Base case:
- n=2, then median is (max(a1,b1) + min(a2,b2))/2
- if n > 2 and m1 == m2, median is m1
based on m1 < m2 or m2 < m1 , change the start and end indices and recurse
Find first and last occurence of number in sorted array with duplicates
if we want in O(n) time, then we parse and keep tab of first and last occurence
if we want in O(log n) time then we do modified binary search.
for last occurence if number is found in mid, then ensure that a[mid+1] is greater than number
Finding missing element or non duplicate element in an array
when the two input arrays are off by just one element which needs to be found, consider XOR operations
XOR : if there is a difference, output is 1
if there is no difference, output in 0
max square formed from a matrix of 1’s and 0’s
dynamic progr
derive it from the min of left, top and left top diagonal
Find the ‘n’th most frequent number in array
revisit this question