mjain

MIsc Problems

Jul 12th, 2019
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.75 KB | None | 0 0
  1. package testrun;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Arrays;
  5. import java.util.Comparator;
  6. import java.util.HashMap;
  7. import java.util.HashSet;
  8. import java.util.List;
  9. import java.util.PriorityQueue;
  10.  
  11. class Program {
  12.  
  13.     public static class Node {
  14.         int x;
  15.         int y;
  16.         int val;
  17.  
  18.         public int getX() {
  19.             return x;
  20.         }
  21.  
  22.         public void setX(int x) {
  23.             this.x = x;
  24.         }
  25.  
  26.         public int getY() {
  27.             return y;
  28.         }
  29.  
  30.         public void setY(int y) {
  31.             this.y = y;
  32.         }
  33.  
  34.         public int getVal() {
  35.             return val;
  36.         }
  37.  
  38.         public void setVal(int val) {
  39.             this.val = val;
  40.         }
  41.  
  42.         public Node(int x, int y, int val) {
  43.             super();
  44.             this.x = x;
  45.             this.y = y;
  46.             this.val = val;
  47.         }
  48.  
  49.     }
  50.  
  51.     public static void KthLargestElem() {
  52.         // matrix is sorted find kth largest,Soltion is klogn
  53.         int mat[][] = { { 1, 5, 9 }, { 10, 11, 13 }, { 12, 13, 15 } };
  54.  
  55.         // create a max heap
  56.         PriorityQueue<Node> minHeap = new PriorityQueue<Program.Node>(new Comparator<Node>() {
  57.             @Override
  58.             public int compare(Node o1, Node o2) {
  59.                 return o2.val - o1.val;
  60.             }
  61.         });
  62.         // take required K
  63.         int k = 7;
  64.         // insert last column in max heap;
  65.         for (int i = 0; i < mat.length; i++) {
  66.             minHeap.offer(new Node(i, mat.length - 1, mat[i][mat.length - 1]));
  67.         }
  68.  
  69.         // replace in max heap from previous column k times
  70.         while (!minHeap.isEmpty()) {
  71.             Node node = minHeap.poll();
  72.             if (k == 1) {
  73.                 // output
  74.                 System.out.print(node.val);
  75.             }
  76.  
  77.             if (node.y - 1 >= 0) {
  78.                 minHeap.offer(new Node(node.x, node.y - 1, mat[node.x][node.y - 1]));
  79.             }
  80.             k--;
  81.         }
  82.  
  83.     }
  84.  
  85.     public static String longestPalindromicSubstring(String str) {
  86.         if (str == null) {
  87.             return null;
  88.         }
  89.         if (str.isEmpty() || str.length() == 1) {
  90.             return str;
  91.         }
  92.         int maxLength = -1;
  93.         String palinDrop = null;
  94.         for (int i = 0; i < str.length(); i++) {
  95.             // even length palindrom check
  96.             int stattingIndex = -1;
  97.             String currentPalindrop = null;
  98.             int low = i - 1;
  99.             int high = i;
  100.             while (low >= 0 && high < str.length() && str.charAt(low) == str.charAt(high)) {
  101.                 if (high - low + 1 > maxLength) {
  102.                     stattingIndex = low;
  103.                     maxLength = high - low + 1;
  104.                 }
  105.                 low--;
  106.                 high++;
  107.             }
  108.  
  109.             // odd length
  110.             low = i - 1;
  111.             high = i + 1;
  112.  
  113.             while (low >= 0 && high < str.length() && str.charAt(low) == str.charAt(high)) {
  114.                 if (high - low + 1 > maxLength) {
  115.                     stattingIndex = low;
  116.                     maxLength = high - low + 1;
  117.                 }
  118.                 low--;
  119.                 high++;
  120.             }
  121.             if (stattingIndex > -1 && maxLength > 0) {
  122.                 currentPalindrop = str.substring(stattingIndex, stattingIndex + maxLength);
  123.                 if (palinDrop == null || currentPalindrop != null && currentPalindrop.length() > palinDrop.length()) {
  124.                     palinDrop = currentPalindrop;
  125.                 }
  126.             }
  127.         }
  128.  
  129.         return palinDrop;
  130.     }
  131.  
  132.     static class MinMaxStack {
  133.         ArrayList<HashMap<String, Integer>> minMaxMap = new ArrayList<HashMap<String, Integer>>();
  134.         ArrayList<Integer>                  stack     = new ArrayList<Integer>();
  135.  
  136.         public Integer peek() {
  137.             return (stack.get(stack.size() - 1));
  138.         }
  139.  
  140.         public Integer pop() {
  141.             minMaxMap.remove(minMaxMap.size() - 1);
  142.             int returned = peek();
  143.             stack.remove(stack.size() - 1);
  144.             return returned;
  145.         }
  146.  
  147.         public void push(Integer number) {
  148.  
  149.             HashMap<String, Integer> newTempMap = new HashMap<String, Integer>();
  150.             newTempMap.put("min", number);
  151.             newTempMap.put("max", number);
  152.             int currentSieOfMap = minMaxMap.size();
  153.             if (currentSieOfMap > 0) {
  154.                 HashMap<String, Integer> lastMinMax = minMaxMap.get(currentSieOfMap - 1);
  155.                 newTempMap.replace("min", Math.min(lastMinMax.get("min"), number));
  156.                 newTempMap.replace("max", Math.max(lastMinMax.get("max"), number));
  157.             }
  158.             minMaxMap.add(newTempMap);
  159.             stack.add(number);
  160.         }
  161.  
  162.         public Integer getMin() {
  163.             return minMaxMap.get(minMaxMap.size() - 1).get("min");
  164.         }
  165.  
  166.         public Integer getMax() {
  167.             return minMaxMap.get(minMaxMap.size() - 1).get("max");
  168.         }
  169.     }
  170.  
  171.     public static ArrayList<ArrayList<Integer>> powerset(ArrayList<Integer> array) {
  172.         ArrayList<ArrayList<Integer>> pSets = new ArrayList<ArrayList<Integer>>();
  173.         // add empty set
  174.         pSets.add(new ArrayList<Integer>());
  175.         // for each number,get currenct poer set add that number in that set,add
  176.         // new set in power set
  177.         for (int curNum : array) {
  178.             int lengthOfCurrentPowerSet = pSets.size();
  179.             for (int index = 0; index < lengthOfCurrentPowerSet; index++) {
  180.                 ArrayList<Integer> curSet = new ArrayList<Integer>(pSets.get(index));
  181.                 curSet.add(curNum);
  182.                 pSets.add(curSet);
  183.             }
  184.         }
  185.         return pSets;
  186.     }
  187.  
  188.     public static ArrayList<ArrayList<Integer>> getPermutations(ArrayList<Integer> array) {
  189.         ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
  190.         generatePerm(array, new ArrayList<Integer>(), list);
  191.         return list;
  192.     }
  193.  
  194.     public static void generatePerm(ArrayList<Integer> array, ArrayList<Integer> currentPer,
  195.             ArrayList<ArrayList<Integer>> finalListOfPermutation) {
  196.         // when current processed array is process and current generated
  197.         // permuation has elements it means we have covered all elements add it
  198.         // in to final list
  199.         if (array.isEmpty() && !currentPer.isEmpty()) {
  200.             finalListOfPermutation.add(currentPer);
  201.         }
  202.  
  203.         for (int i = 0; i < array.size(); i++) {
  204.             // remove Ith elem from current array
  205.             ArrayList<Integer> newarray = new ArrayList<Integer>(array);
  206.             newarray.remove(i);
  207.             // insert the ith elem in current permutation
  208.             ArrayList<Integer> newperm = new ArrayList<Integer>(currentPer);
  209.             newperm.add(array.get(i));
  210.             // call recursion for this new array and current permutation
  211.             generatePerm(newarray, newperm, finalListOfPermutation);
  212.         }
  213.     }
  214.  
  215.     public static ArrayList<Integer> riverSizes(int[][] matrix) {
  216.         ArrayList<Integer> riverSizes = new ArrayList<Integer>();
  217.         boolean[][] isVisited = new boolean[matrix.length][matrix[0].length];
  218.         for (int i = 0; i < matrix.length; i++) {
  219.             for (int j = 0; j < matrix[0].length; j++) {
  220.                 if (isVisited[i][j]) {
  221.                     continue;
  222.                 }
  223.                 int currentRiverSize = 0;
  224.                 ArrayList<Integer[]> currentNodeList = new ArrayList<Integer[]>();
  225.                 currentNodeList.add(new Integer[] { i, j });
  226.                 while (currentNodeList.size() > 0) {
  227.                     Integer[] curNode = currentNodeList.get(currentNodeList.size() - 1);
  228.                     currentNodeList.remove(currentNodeList.size() - 1);
  229.                     int x = curNode[0];
  230.                     int y = curNode[1];
  231.                     if (isVisited[x][y]) {
  232.                         continue;
  233.                     }
  234.                     isVisited[x][y] = true;
  235.                     if (matrix[x][y] == 0) {
  236.                         continue;
  237.                     }
  238.                     currentRiverSize++;
  239.  
  240.                     // get four neighbours
  241.                     if (x > 0 && !isVisited[x - 1][y]) {
  242.                         currentNodeList.add(new Integer[] { x - 1, y });
  243.                     }
  244.                     if (x < matrix.length - 1 && !isVisited[x + 1][y]) {
  245.                         currentNodeList.add(new Integer[] { x + 1, y });
  246.                     }
  247.                     if (y > 0 && !isVisited[x][y - 1]) {
  248.                         currentNodeList.add(new Integer[] { x, y - 1 });
  249.                     }
  250.                     if (y < matrix[0].length - 1 && !isVisited[x][y + 1]) {
  251.                         currentNodeList.add(new Integer[] { x, y + 1 });
  252.                     }
  253.                 }
  254.                 if (currentRiverSize > 0) {
  255.                     riverSizes.add(currentRiverSize);
  256.                 }
  257.  
  258.             }
  259.         }
  260.         return riverSizes;
  261.  
  262.     }
  263.  
  264.     public static ArrayList<Integer[]> threeNumberSum(int[] array, int targetSum) {
  265.         ArrayList<Integer[]> list = new ArrayList<Integer[]>();
  266.         if (array == null || array.length == 0) {
  267.             return list;
  268.         }
  269.         // threeNumberSum(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 15 }, 18);
  270.         Arrays.sort(array);
  271.         int n = array.length;
  272.         int leftPointer = 0, rightPointer = 0, currentPointer = 0;
  273.         for (int i = 0; i < n - 2; i++) {
  274.             currentPointer = i;
  275.             leftPointer = i + 1;
  276.             rightPointer = n - 1;
  277.             while (leftPointer < rightPointer) {
  278.                 if (targetSum == array[rightPointer] + array[currentPointer] + array[leftPointer]) {
  279.                     Integer[] triplet = new Integer[] { array[currentPointer], array[leftPointer], array[rightPointer] };
  280.                     Arrays.sort(triplet);
  281.                     // for (int num : triplet) {
  282.                     // System.out.print(" " + num);
  283.                     // }
  284.                     // System.out.println();
  285.                     list.add(triplet);
  286.                     rightPointer--;
  287.                     leftPointer++;
  288.                 } else if (targetSum > array[rightPointer] + array[currentPointer] + array[leftPointer]) {
  289.                     leftPointer++;
  290.                 } else if (targetSum < array[rightPointer] + array[currentPointer] + array[leftPointer]) {
  291.                     rightPointer--;
  292.                 }
  293.             }
  294.         }
  295.         return list;
  296.     }
  297.  
  298.     public static int[] bubbleSort(int[] array) {
  299.         if (array == null) {
  300.             return null;
  301.         } else if (array.length == 0) {
  302.             return array;
  303.         }
  304.         int n = array.length;
  305.         boolean swapped = false;
  306.         for (int i = 0; i < n - 1; i++) {
  307.             swapped = false;
  308.             for (int j = 0; j < n - i - 1; j++) {
  309.                 if (array[j] > array[j + 1]) {
  310.                     int temp = array[j];
  311.                     array[j] = array[j + 1];
  312.                     array[j + 1] = temp;
  313.                     swapped = true;
  314.                 }
  315.             }
  316.             if (!swapped) {
  317.                 break;
  318.             }
  319.         }
  320.  
  321.         for (int i : array) {
  322.             System.out.print("," + i);
  323.         }
  324.         return array;
  325.  
  326.     }
  327.  
  328.     public static int[] findThreeLargestNumbers(int[] array) {
  329.         if (array == null || array.length == 0) {
  330.             return null;
  331.         }
  332.         int[] largestThree = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE };
  333.         // maintain an array of size 3,which contains max elements traversed so
  334.         // far
  335.         for (int cur : array) {
  336.             // whenever a new element comes and compare this from backward,it is
  337.             // greater than replace it and shift current to previous position
  338.             for (int k = 2; k >= 0; k--) {
  339.                 if (largestThree[k] < cur) {
  340.                     int temp = largestThree[k];
  341.                     largestThree[k] = cur;
  342.                     for (int shift = k - 1; shift >= 0; shift--) {
  343.                         int t = largestThree[shift];
  344.                         largestThree[shift] = temp;
  345.                         temp = t;
  346.                     }
  347.                     break;
  348.                 }
  349.             }
  350.         }
  351.         for (int i : largestThree) {
  352.             System.out.print("," + i);
  353.         }
  354.         return largestThree;
  355.     }
  356.  
  357.     public static int findClosestValueInBst(testrun.BinaryTree.Node tree, int target) {
  358.         if (tree == null) {
  359.             return -1;
  360.         }
  361.         int value = tree.data;
  362.         int rvlaue = 0, lvalue = 0;
  363.         if (tree.data < target && tree.right != null) {
  364.             rvlaue = findClosestValueInBst(tree.right, target);
  365.         } else if (tree.data > target && tree.left != null) {
  366.             lvalue = findClosestValueInBst(tree.left, target);
  367.         }
  368.         return Math.max(value, Math.max(rvlaue, lvalue));
  369.     }
  370.  
  371.     static class BST {
  372.         public int value;
  373.         public BST left;
  374.         public BST right;
  375.  
  376.         public BST(int value) {
  377.             this.value = value;
  378.         }
  379.     }
  380.  
  381.     public static int[] twoNumberSum(int[] array, int targetSum) {
  382.         // Write your code here.
  383.         if (array == null || array.length == 0 || targetSum <= 0) {
  384.             return null;
  385.         }
  386.         Arrays.sort(array);
  387.         List<Integer> list = new ArrayList<Integer>();
  388.         int k = array.length - 1;
  389.         int i = 0;
  390.         int count = 0;
  391.         while (i < array.length && k >= 0 && k > i) {
  392.             if (array[i] + array[k] == targetSum) {
  393.                 list.add(array[i]);
  394.                 list.add(array[k]);
  395.                 i++;
  396.                 k--;
  397.             } else if (array[i] + array[k] > targetSum) {
  398.                 k--;
  399.             } else {
  400.                 i++;
  401.             }
  402.         }
  403.         int[] output = new int[list.size()];
  404.         for (int num : list) {
  405.             System.out.print(" " + num);
  406.             output[count++] = num;
  407.         }
  408.         Arrays.sort(output);
  409.         return output;
  410.  
  411.     }
  412.  
  413.     public static ArrayList<Integer[]> fourNumberSum(int[] array, int targetSum) {
  414.         ArrayList<Integer[]> sumArray = new ArrayList<Integer[]>();
  415.         HashSet<HashSet<Integer>> finalReturnSet = new HashSet<HashSet<Integer>>();
  416.         HashMap<Integer, ArrayList<HashSet<Integer>>> mapForSum = new HashMap<Integer, ArrayList<HashSet<Integer>>>();
  417.         if (array == null || array.length == 0) {
  418.             return sumArray;
  419.         }
  420.         //maintain a sum map for two elements
  421.         for (int i = 0; i < array.length; i++) {
  422.             for (int j = i + 1; j < array.length; j++) {
  423.                 HashSet<Integer> set = new HashSet<Integer>();
  424.                 set.add(i);
  425.                 set.add(j);
  426.                 int sum = array[i] + array[j];
  427.                 if (mapForSum.containsKey(sum)) {
  428.                     mapForSum.get(sum).add(set);
  429.                 } else {
  430.                     ArrayList<HashSet<Integer>> l = new ArrayList<HashSet<Integer>>();
  431.                     l.add(set);
  432.                     mapForSum.put(sum, l);
  433.                 }
  434.             }
  435.         }
  436.         //traverse the map fro cur sum and differnce from traget sum.
  437.         for (int curSum : mapForSum.keySet()) {
  438.             if (curSum < targetSum) {
  439.                 int diff = targetSum - curSum;
  440.                 if (mapForSum.containsKey(diff) && mapForSum.get(curSum) != null && mapForSum.get(diff) != null) {
  441.                     for (HashSet<Integer> firstSet : mapForSum.get(curSum)) {
  442.                         for (HashSet<Integer> secondSet : mapForSum.get(diff)) {
  443.                             HashSet<Integer> finalset = new HashSet<Integer>();
  444.                             finalset.addAll(firstSet);
  445.                             finalset.addAll(secondSet);
  446.                             if (finalset.size() == 4) {
  447.                                 finalReturnSet.add(finalset);
  448.                             }
  449.                         }
  450.                     }
  451.                 }
  452.                 mapForSum.put(curSum, null);
  453.             }
  454.         }
  455.  
  456.         for (HashSet<Integer> set : finalReturnSet) {
  457.             int count = 0;
  458.             Integer[] cur = new Integer[4];
  459.             for (int num : set) {
  460.                 cur[count++] = array[num];
  461.             }
  462.             sumArray.add(cur);
  463.         }
  464.         return sumArray;
  465.     }
  466.  
  467.     public static int[] subarraySort(int[] array) {
  468.  
  469.         int[] retArr = new int[] { -1, -1 };
  470.         int minOutOfOrder = Integer.MAX_VALUE;
  471.         int maxOutOfOrder = Integer.MIN_VALUE;
  472.         if (array != null && array.length > 0) {
  473.             for (int i = 0; i < array.length; i++) {
  474.                 boolean isOutOfOrder = false;
  475.                 if (i == 0) {
  476.                     if (array[i] > array[i + 1]) {
  477.                         isOutOfOrder = true;
  478.                     }
  479.                 } else if (i == array.length - 1) {
  480.                     if (array[i] < array[i - 1]) {
  481.                         isOutOfOrder = true;
  482.                     }
  483.                 } else if (array[i] > array[i + 1] || array[i - 1] > array[i]) {
  484.                     isOutOfOrder = true;
  485.                 }
  486.                 if (isOutOfOrder) {
  487.                     minOutOfOrder = Math.min(minOutOfOrder, array[i]);
  488.                     maxOutOfOrder = Math.max(maxOutOfOrder, array[i]);
  489.                 }
  490.             }
  491.             if (minOutOfOrder == Integer.MAX_VALUE) {
  492.                 return retArr;
  493.             }
  494.             int leftIndex = 0;
  495.             while (array[leftIndex] <= minOutOfOrder) {
  496.                 leftIndex++;
  497.             }
  498.             int rightIndex = array.length - 1;
  499.             while (array[rightIndex] >= maxOutOfOrder) {
  500.                 rightIndex--;
  501.             }
  502.             retArr[0] = leftIndex;
  503.             retArr[1] = rightIndex;
  504.  
  505.         }
  506.  
  507.         return retArr;
  508.  
  509.     }
  510.  
  511.     public static int[] largestRange(int[] array) {
  512.         int[] retArr = new int[] { -1, -1 };
  513.         HashMap<Integer, Boolean> numMap = new HashMap<Integer, Boolean>();
  514.         for (int i : array) {
  515.             numMap.put(i, true);
  516.         }
  517.         int maxLength = 0;
  518.         for (int num : array) {
  519.             if (!numMap.containsKey(num)) {
  520.                 continue;
  521.             }
  522.             int curLength = -1;
  523.             int left = num - 1;
  524.             int right = num + 1;
  525.             while (numMap.containsKey(left)) {
  526.                 left--;
  527.                 curLength++;
  528.             }
  529.             while (numMap.containsKey(right)) {
  530.                 right++;
  531.                 curLength++;
  532.             }
  533.  
  534.             if (curLength > maxLength) {
  535.                 maxLength = curLength;
  536.                 retArr = new int[] { left + 1, right - 1 };
  537.             }
  538.         }
  539.         return retArr;
  540.     }
  541.  
  542.     public static int minRewards(int[] scores) {
  543.  
  544.         int reward = 0;
  545.  
  546.         int[] rewards = new int[scores.length];
  547.         Arrays.fill(rewards, 1);
  548.  
  549.         for (int i = 1; i < scores.length; i++) {
  550.             if (scores[i] > scores[i - 1]) {
  551.                 rewards[i] = rewards[i - 1] + 1;
  552.             }
  553.         }
  554.         for (int i = scores.length - 2; i >= 0; i--) {
  555.             if (scores[i] > scores[i + 1]) {
  556.                 rewards[i] = Math.max(rewards[i], rewards[i + 1] + 1);
  557.             }
  558.         }
  559.         for (int num : rewards) {
  560.             System.out.print(" " + num);
  561.             reward += num;
  562.         }
  563.         return reward;
  564.  
  565.     }
  566.  
  567.     public static void main(String[] args) {
  568.         // minRewards(new int[] { 8, 4, 2, 1, 3, 6, 7, 9, 5 });
  569.         KthLargestElem();
  570.         System.out.println();
  571.     }
  572. }
Add Comment
Please, Sign In to add comment