From 42636a6153e7eecbe6941d89c37751b32ab863fb Mon Sep 17 00:00:00 2001 From: Pranav Anil Bhole Date: Thu, 14 Jan 2021 17:07:15 -0800 Subject: [PATCH] update --- .../advanced_ds/dp/basic/MinArrayJump.java | 38 +++++++ .../dp/medium/ContinuousSubArraySum.java | 46 ++++++++ .../random/easy/JavaCollectionsExamples.java | 63 +++++++++++ .../advanced_ds/random/easy/KthLargest.java | 34 ++++++ .../random/easy/PrimePermutations.java | 45 ++++++++ .../random/easy/SubDomainVisitCount.java | 46 ++++++++ .../TrailingNumberOfZerosInNFactorial.java | 30 ++++++ .../random/hard/EvalExpression.java | 100 ++++++++++++++++++ .../advanced_ds/random/hard/ListNode.java | 6 ++ .../random/hard/MergeKSortedList.java | 43 ++++++++ .../random/medium/ArrayOfDoubledPairs.java | 74 +++++++++++++ .../advanced_ds/random/medium/HitCounter.java | 44 ++++++++ .../random/medium/MaxScorePickCards.java | 86 +++++++++++++++ .../random/medium/MergeIntervals.java | 99 +++++++++++++++++ .../medium/MinJumpToZerothIndexInArray.java | 49 +++++++++ .../random/medium/MinimumKnightMoves.java | 94 ++++++++++++++++ .../SubStringWithEvenCountOfVowels.java | 39 +++++++ .../random/medium/SumDivisibleByP.java | 41 +++++++ .../advanced_ds/random/medium/Tuple.java | 30 ++++++ .../medium/tree/LowestCommonAncestor.java | 49 +++++++++ .../tree/LowestCommonAncestorOfNodes.java | 40 +++++++ .../medium/tree/SmallestCommonRegionLCA.java | 97 +++++++++++++++++ .../com/bhole/advanced_ds/rmq/TreeNode.java | 6 +- src/main/python/test.py | 8 ++ .../dp/basic/MinArrayJumpTest.java | 12 +++ 25 files changed, 1216 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/bhole/advanced_ds/dp/basic/MinArrayJump.java create mode 100644 src/main/java/com/bhole/advanced_ds/dp/medium/ContinuousSubArraySum.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/easy/JavaCollectionsExamples.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/easy/KthLargest.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/easy/PrimePermutations.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/easy/SubDomainVisitCount.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/easy/TrailingNumberOfZerosInNFactorial.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/hard/EvalExpression.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/hard/ListNode.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/hard/MergeKSortedList.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/ArrayOfDoubledPairs.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/HitCounter.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/MaxScorePickCards.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/MergeIntervals.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/MinJumpToZerothIndexInArray.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/MinimumKnightMoves.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/SubStringWithEvenCountOfVowels.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/SumDivisibleByP.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/Tuple.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/tree/LowestCommonAncestor.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/tree/LowestCommonAncestorOfNodes.java create mode 100644 src/main/java/com/bhole/advanced_ds/random/medium/tree/SmallestCommonRegionLCA.java create mode 100644 src/main/python/test.py create mode 100644 src/test/java/com/bhole/advanced_ds/dp/basic/MinArrayJumpTest.java diff --git a/src/main/java/com/bhole/advanced_ds/dp/basic/MinArrayJump.java b/src/main/java/com/bhole/advanced_ds/dp/basic/MinArrayJump.java new file mode 100644 index 0000000..68446cb --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/dp/basic/MinArrayJump.java @@ -0,0 +1,38 @@ +package com.bhole.advanced_ds.dp.basic; + +public class MinArrayJump { + + /* + DP works in way by traversing the subproblems from end to start. + dp[i] = min jump required to reach end from i. + Starts with base case dp[end] = 0; + we iterate i from end-1 to start; + on every i, if possible jump >0 then + try all j jump and minimize dp[j] + set dp[i] = dp[j]+1; + if jump is not possible at i, set dp[i] = -1; + */ + public int solve(int arr[]) { + if (arr.length==0) return -1; + int dp[] = new int[arr.length]; + int end= arr.length-1; + dp[end] = 0; + for (int i=end-1; i>=0; i--) { + if (arr[i]>0) { + int min = Integer.MAX_VALUE; + for (int k=i+1; k<=(i+arr[i]) && k<=end; k++) { + if (dp[k]>=0) { + min=Math.min(dp[k], min); + } + } + dp[i] = 1+min; + } else { + dp[i] = -1; + } + } + return dp[0]; + } + { + + } +} \ No newline at end of file diff --git a/src/main/java/com/bhole/advanced_ds/dp/medium/ContinuousSubArraySum.java b/src/main/java/com/bhole/advanced_ds/dp/medium/ContinuousSubArraySum.java new file mode 100644 index 0000000..4d3b3b2 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/dp/medium/ContinuousSubArraySum.java @@ -0,0 +1,46 @@ +package com.bhole.advanced_ds.dp.medium; + +import com.bhole.advanced_ds.random.medium.Tuple; + +import java.util.HashMap; +import java.util.Map; + +public class ContinuousSubArraySum { + + /* + Return start and end index tuple of continuous sub array sum + */ + public Tuple continuousSubArraySum(int[] nums, int sum) { + if (nums.length == 0) return new Tuple(-1,-1); + Map map = new HashMap<>(); + int curSum = 0; + int minLength = nums.length; + int start = -1, end =-1; + for (int i=0; i set = new TreeSet(new Comparator() { + @Override + public int compare(CustomNode customNode, CustomNode t1) { + return customNode.val-t1.val; + } + }); + + set.add(new CustomNode(10)); + set.add(new CustomNode(7)); + set.add(new CustomNode(20)); + + set.stream().forEach(System.out::println); + } + + public void treeMap() { + // Log n operations like contains,add,remove, sorted map base on keys + TreeMap treeMap = new TreeMap<>(new Comparator() { + @Override + public int compare(CustomNode customNode, CustomNode t1) { + return customNode.val-t1.val; + } + }); + + treeMap.put(new CustomNode(10), 10); + treeMap.put(new CustomNode(7), 7); + treeMap.put(new CustomNode(20), 20); + java.util.Map.Entry entry = treeMap.pollFirstEntry(); + System.out.println(entry); + }; + + public void linkedHashSet() { + // maintains the order of inserted elements + Set set = new LinkedHashSet(); + } + + + class CustomNode { + int val; + public CustomNode(int val) { + this.val = val; + } + @Override + public String toString() { + return "("+val+")"; + } + } + + public static void main(String args[]) { + JavaCollectionsExamples examples = new JavaCollectionsExamples(); + //examples.treeSet(); + examples.treeMap(); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/easy/KthLargest.java b/src/main/java/com/bhole/advanced_ds/random/easy/KthLargest.java new file mode 100644 index 0000000..6e9d894 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/easy/KthLargest.java @@ -0,0 +1,34 @@ +package com.bhole.advanced_ds.random.easy; + +import java.awt.event.KeyAdapter; +import java.util.Arrays; +import java.util.PriorityQueue; + +public class KthLargest { + + PriorityQueue priorityQueue = new PriorityQueue(); + int k; + + public KthLargest(int k, int[] nums) { + this.k = k; + Arrays.stream(nums).forEach(n-> { + System.out.println(add(n)); + }); + } + + public int add(int val) { + priorityQueue.add(val); + if (priorityQueue.size() > k) { + priorityQueue.poll(); + } + return priorityQueue.peek(); + } + + public static void main(String args[]) { + KthLargest kthLargest = new KthLargest(3, new int[]{4,5,8,2}); + Arrays.stream(new int[]{3,5,10,9,4}).forEach(n-> { + System.out.println(" : "+kthLargest.add(n)); + }); + } + +} diff --git a/src/main/java/com/bhole/advanced_ds/random/easy/PrimePermutations.java b/src/main/java/com/bhole/advanced_ds/random/easy/PrimePermutations.java new file mode 100644 index 0000000..e332c82 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/easy/PrimePermutations.java @@ -0,0 +1,45 @@ +package com.bhole.advanced_ds.random.easy; + +public class PrimePermutations { + public int numPrimeArrangements(int n) { + if (n<=0) return 0; + if (n==1) return 1; + int mod = (int)Math.pow(10,9) +7; + System.out.println("num="+n); + boolean primes[] = new boolean[n+1]; + int c=0; + for (int i=2; i<=n; i++) { + if (primes[i] == false) { + c++; + System.out.println(i+" is prime, count="+c); + for (int k=2; (k*i)<=n; k++) { + primes[k*i] = true; + } + } + } + + long pm = 1; + int primeCount = c; + int nonPrimeCount = (n-c); + System.out.println(String.format("primeCount=%d, n=%d, nonPrimeCount=%d, c=%d",primeCount, n, nonPrimeCount, c)); + + for (int i=1; i<=n; i++) { + if (primes[i]==false) { + if(primeCount>0) pm = pm*primeCount; + primeCount--; + } else { + if (nonPrimeCount>0) pm=pm*nonPrimeCount; + nonPrimeCount--; + } + System.out.println(pm); + pm=pm%mod; + } + return (int)pm; + } + public static void main(String args[]) { + PrimePermutations primePermutations = new PrimePermutations(); + System.out.println(primePermutations.numPrimeArrangements(100)); + double m = 10/0; + } + +} diff --git a/src/main/java/com/bhole/advanced_ds/random/easy/SubDomainVisitCount.java b/src/main/java/com/bhole/advanced_ds/random/easy/SubDomainVisitCount.java new file mode 100644 index 0000000..fe06d5a --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/easy/SubDomainVisitCount.java @@ -0,0 +1,46 @@ +package com.bhole.advanced_ds.random.easy; + +import java.util.*; +import java.util.stream.Collectors; + +/* +input: ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] +output: ["901 mail.com","50 yahoo.com","900 google.mail.com","5 wiki.org","5 org","1 intel.mail.com","951 com"] + */ +public class SubDomainVisitCount { + public List subdomainVisits(String[] cpdomains) { + if (cpdomains.length == 0) { + return new ArrayList<>(); + } + Map res = new HashMap(); + Arrays.stream(cpdomains).forEach(cpdomain-> { + if (cpdomain!=null) { + String arr[] = cpdomain.trim().split("\\s+"); + if (arr.length >= 2) { + try { + int count = Integer.parseInt(arr[0]); + String domain = arr[1]; + for (int i=domain.length()-1; i>=0; i--) { + if (domain.charAt(i) == '.' || i==0) { + String tmp = domain.substring(i==0?0:i+1); + if(res.containsKey(tmp)) { + res.put(tmp, count+res.get(tmp)); + } else { + res.put(tmp, count); + } + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + return res.entrySet().stream().map(e-> e.getValue()+" "+e.getKey()).collect(Collectors.toList()); + } + public static void main(String args[]) { + SubDomainVisitCount subDomainVisitCount = new SubDomainVisitCount(); + List res = subDomainVisitCount.subdomainVisits(new String[] {"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"}); + System.out.println(Arrays.toString(res.toArray())); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/easy/TrailingNumberOfZerosInNFactorial.java b/src/main/java/com/bhole/advanced_ds/random/easy/TrailingNumberOfZerosInNFactorial.java new file mode 100644 index 0000000..d7092a6 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/easy/TrailingNumberOfZerosInNFactorial.java @@ -0,0 +1,30 @@ +package com.bhole.advanced_ds.random.easy; + +public class TrailingNumberOfZerosInNFactorial { + /* + Given an integer n, return the number of trailing zeroes in n!. + idea is count the number of 5 s any i from 0 to n. + that count would be trailing zeros; + */ + public int trailingZeroes(int n) { + int count = 0; + for (int i=1; i<=n; i++) { + int num = i; + while (num>0) { + if (num>=5 && num%5==0) { + System.out.print(", "+i); + count+=1; + num = num/5; + } else { + num = 0; + } + } + + } + return count; + } + public static void main(String args[]) { + TrailingNumberOfZerosInNFactorial zerosInNFactorial = new TrailingNumberOfZerosInNFactorial(); + System.out.println(zerosInNFactorial.trailingZeroes(30)); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/hard/EvalExpression.java b/src/main/java/com/bhole/advanced_ds/random/hard/EvalExpression.java new file mode 100644 index 0000000..3e55b04 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/hard/EvalExpression.java @@ -0,0 +1,100 @@ +package com.bhole.advanced_ds.random.hard; + +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public class EvalExpression { + public int calculate(String exp) { + Stack stack = new Stack(); + StringBuilder sb = new StringBuilder(); + for (int i=0; i 0) { + stack.push(sb.toString()); + sb = new StringBuilder(); + } + String tmp = stack.pop(); + Stack subExp = new Stack(); + while (!"(".equals(tmp)) { + subExp.push(tmp); + if(isOp(stack.peek())) { + subExp.push(stack.pop()); + subExp.push(stack.pop()); + } + tmp = stack.pop(); + } + if (!subExp.isEmpty()) { + stack.push(evalSubExp(subExp)); + } + } else { + if (sb.length() > 0) { + stack.push(sb.toString()); + sb = new StringBuilder(); + } + if(c != ' ') { + stack.push(String.valueOf(c)); + } + + } + } + if (sb.length() > 0) { + stack.push(sb.toString()); + } + if (stack.isEmpty()) { + return 0; + } + Stack rev = new Stack(); + while (!stack.isEmpty()) { + rev.push(stack.pop()); + } + return Integer.parseInt(evalSubExp(rev)); + } + private String evalSubExp(Stack subExp) { + String tmp = subExp.pop(); + while (!subExp.isEmpty()) { + if (isOp(subExp.peek())) { + String op = subExp.pop(); + String operand = subExp.pop(); + subExp.push(compute(tmp, operand, op)); + } + if(!subExp.isEmpty()) { + if(isOp(tmp)) { + tmp = tmp+subExp.pop(); + } else { + tmp = subExp.pop(); + } + } + } + return tmp; + } + + private String compute(String operand1, String operand2, String op) { + if ("+".equals(op)) { + return (cal(operand1, operand2, '+')); + } else { + return (cal(operand1, operand2, '-')); + } + } + private boolean isOp(String c) { + return "+".equals(c) || "-".equals(c); + } + private String cal(String a,String b, char op) { + if (op=='+') { + return String.valueOf((Integer.parseInt(a)+Integer.parseInt(b))); + } + return String.valueOf((Integer.parseInt(a)-Integer.parseInt(b))); + } + public static void main(String args[]) { + EvalExpression evalExpression = new EvalExpression(); + System.out.println(evalExpression.calculate("(1+(4+5+2)-3)+(6+8)")); + System.out.println(evalExpression.calculate(" 2-1 + 2 ")); + System.out.println(evalExpression.calculate("12345 ")); + System.out.println(evalExpression.calculate("1 + 1")); + System.out.println(evalExpression.calculate("-2+ 1")); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/hard/ListNode.java b/src/main/java/com/bhole/advanced_ds/random/hard/ListNode.java new file mode 100644 index 0000000..deeeac0 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/hard/ListNode.java @@ -0,0 +1,6 @@ +package com.bhole.advanced_ds.random.hard; + +public class ListNode { + public int val; + public ListNode next; +} diff --git a/src/main/java/com/bhole/advanced_ds/random/hard/MergeKSortedList.java b/src/main/java/com/bhole/advanced_ds/random/hard/MergeKSortedList.java new file mode 100644 index 0000000..6ff5a81 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/hard/MergeKSortedList.java @@ -0,0 +1,43 @@ +package com.bhole.advanced_ds.random.hard; + +import java.util.Comparator; +import java.util.PriorityQueue; + +public class MergeKSortedList { + + public ListNode mergeKLists(ListNode[] lists) { + + if (lists.length == 0) return null; + if (lists.length == 1) return lists[0]; + Comparator cmp = new Comparator() { + @Override + public int compare(ListNode a, ListNode b) { + return a.val-b.val; + } + }; + PriorityQueue pq = new PriorityQueue(lists.length, cmp); + for (ListNode n: lists) { + if (n != null) { + pq.add(n); + } + } + ListNode head = null; + ListNode cur = null; + while (!pq.isEmpty()) { + ListNode n = pq.poll(); + if (cur == null) { + head = n; + cur = n; + } else { + cur.next = n; + cur = n; + } + + if (n.next!=null) { + pq.add(n.next); + } + } + + return head; + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/ArrayOfDoubledPairs.java b/src/main/java/com/bhole/advanced_ds/random/medium/ArrayOfDoubledPairs.java new file mode 100644 index 0000000..c5f91e3 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/ArrayOfDoubledPairs.java @@ -0,0 +1,74 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.Arrays; + +public class ArrayOfDoubledPairs { + + public boolean canReorderDoubled(int[] A) { + Arrays.sort(A); + System.out.println(Arrays.toString(A)); + boolean visited[] = new boolean[A.length]; + + for (int i=0; i < A.length; i++) { + if (visited[i] == false) { + int small = A[i]; + visited[i] = true; + int lookupValue = small*2; + if (small < 0) { + if (small%2 !=0) { + return false; + } + lookupValue = small/2; + } + int index = Arrays.binarySearch(A,i+1, A.length, lookupValue); + System.out.println("i="+i+", index="+index); + if (index > 0) { + int nonVisitedIndex = linSearch(A, visited, lookupValue, index); + if(nonVisitedIndex> 0) { + visited[nonVisitedIndex] = true; + } else { + return false; + } + } else { + return false; + } + } + } + + for(int i=0; i=0 && arr[i] == ele; i--) { + if(!visited[i]) { + return i; + } + } + return -1; + } + + public static void main(String args[]) { + int arr[] = {1,2,1,-8,8,-4,4,-4,2,-2}; + ArrayOfDoubledPairs pairs = new ArrayOfDoubledPairs(); + pairs.canReorderDoubled(arr); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/HitCounter.java b/src/main/java/com/bhole/advanced_ds/random/medium/HitCounter.java new file mode 100644 index 0000000..4113132 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/HitCounter.java @@ -0,0 +1,44 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; + +public class HitCounter { + + Queue queue; + /** Initialize your data structure here. */ + public HitCounter() { + queue= new LinkedList<>(); + } + + /** Record a hit. + @param timestamp - The current timestamp (in seconds granularity). */ + public void hit(int timestamp) { + queue.add(timestamp); + } + + private void cleanup(int timestamp) { + int keep = timestamp-300; + while (!queue.isEmpty() && queue.peek()<=keep) { + queue.remove(); + } + } + /** Return the number of hits in the past 5 minutes. + @param timestamp - The current timestamp (in seconds granularity). */ + public int getHits(int timestamp) { + cleanup(timestamp); + return queue.size(); + } + + public static void main(String args[]) { + HitCounter obj = new HitCounter(); + obj.hit(1); + obj.hit(2); + obj.hit(3); + System.out.println(obj.getHits(4)); + obj.hit(300); + System.out.println(obj.getHits(300)); + System.out.println(obj.getHits(301)); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/MaxScorePickCards.java b/src/main/java/com/bhole/advanced_ds/random/medium/MaxScorePickCards.java new file mode 100644 index 0000000..8451bf2 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/MaxScorePickCards.java @@ -0,0 +1,86 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.HashMap; + +public class MaxScorePickCards { + HashMap map = new HashMap(); + int[] cardPoints; + public int maxScore(int[] cardPoints, int k) { + this.cardPoints = cardPoints; + //return recurse(k, 0, cardPoints.length-1); + return findSwOpt(cardPoints, k); + } + + private int recurse( int k, int start, int end) { + if(k<=0 || start>end || start>=cardPoints.length || end<0) return 0; + Key key = new Key(k, start, end); + if (map.containsKey(key)) { + return map.get(key); + } + System.out.println(String.format("(%d, %d, %d)", k, start, end)); + int case1 = cardPoints[start] + recurse( k-1, start+1, end); + int case2 = cardPoints[end] + recurse(k-1, start, end-1); + int max = Math.max(case1, case2); + map.put(key, max); + return max; + } + + class Key { + int k , start, end; + public Key( int k, int start, int end) { + this.k = k; + this.start = start; + this.end = end; + } + } + public static void main(String args[]) { + MaxScorePickCards maxScorePickCards = new MaxScorePickCards(); + int res= maxScorePickCards.maxScore(new int[] { + 53,14,91,35,51,9,80,27,6,15,77,86,34,62,55,45,91,45,23,75,66,42,62,13,34,18,89,67,93,83,100,14,92,73,48,2,47,93,99,100,88,84,48 + }, 43); + System.out.println(res); + System.out.println(maxScorePickCards.maxScore(new int[]{9,7,7,9,7,7,9},7)); + + } + private int findSw(int arr[], int k) { + int size = arr.length; + int max = Integer.MIN_VALUE; + for (int w=0; w<=k; w++) { + int leftSum =0, rightSum=0; + for (int l=0; l< k-w; l++) { + leftSum+=arr[l]; + } + for (int r=size-w; r=arr.length) { + return leftSum; + } + + for (int w=0; w<=k; w++) { + max = Math.max(max, leftSum+rightSum); + if (k-1-w>=0) { + leftSum = leftSum-arr[k-1-w]; + } + rightSum +=arr[size-1-w]; + } + return max; + } + + /* + Input: cardPoints = [9,7,7,9,7,7,9], k = 7 + Output: 55 + */ +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/MergeIntervals.java b/src/main/java/com/bhole/advanced_ds/random/medium/MergeIntervals.java new file mode 100644 index 0000000..00f770f --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/MergeIntervals.java @@ -0,0 +1,99 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +public class MergeIntervals { + + public int[][] merge(int[][] intervals) { + if (intervals.length == 0) { + return new int[0][]; + } + int len = intervals.length; + List arr = Arrays.stream(intervals).map(Pair::new).collect(Collectors.toList()); + + Map map = Arrays.stream(intervals).map(Pair::new).collect(Collectors.toMap(Pair::hashCode, p-> p)); + + arr.sort(new Comparator() { + @Override + public int compare(Pair pair, Pair t1) { + return pair.e - t1.e; + } + }); + Pair prev = arr.get(len-1); + List res = new ArrayList<>(); + for (int i=len-2; i>=0; i--) { + Pair cur = arr.get(i); + if (includes(cur, prev)) { + prev = cur.merge(prev); + } + else { + res.add(prev); + prev = cur; + } + } + res.add(prev); + int arrRes[][] = res.stream().map(Pair::toArr).toArray(int[][]::new); + return arrRes; + } + + private boolean includes(Pair a, Pair b) { + if (b.s <= a.e && a.s <= b.s) { + return true; + } + if (a.equals(b)) { + return true; + } + if(a.e == b.e) return true; + if(a.e<= b.e && b.s<= a.s) return true; + return false; + } + + class Pair { + int s; + int e; + public Pair () { + + } + public Pair (int a[]) { + this.s = a[0]; + this.e = a[1]; + } + public int[] toArr() { + int arr[] = new int[2]; + arr[0] = s; + arr[1] = e; + return arr; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Pair pair = (Pair) o; + return s == pair.s && + e == pair.e; + } + + @Override + public int hashCode() { + return Objects.hash(s, e); + } + public Pair merge(Pair b) { + Pair res = new Pair(); + res.s = Math.min(this.s, b.s); + res.e = Math.max(this.e, b.e); + return res; + } + } + + public static void main(String args[]) { + MergeIntervals mergeIntervals = new MergeIntervals(); + int arr[][] = {{1,2}, {1,3}, {4,5}}; + Arrays.stream(mergeIntervals.merge(arr)).forEach(p-> { + System.out.println(Arrays.toString(p)); + }); + + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/MinJumpToZerothIndexInArray.java b/src/main/java/com/bhole/advanced_ds/random/medium/MinJumpToZerothIndexInArray.java new file mode 100644 index 0000000..502e006 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/MinJumpToZerothIndexInArray.java @@ -0,0 +1,49 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.HashSet; +import java.util.Set; + +/* +Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach to any index with value 0. + +Notice that you can not jump outside of the array at any time. + +Input: arr = [4,2,3,0,3,1,2], start = 5 + +Simple DFS + */ +public class MinJumpToZerothIndexInArray { + Set visited = new HashSet<>(); + + public boolean canReach(int[] arr, int start) { + int size = arr.length; + if (size==0) return false; + if (start < 0 || start >= arr.length) return false; + if(arr[start] == 0) return true; + System.out.println("Start="+start); + + if (visited.contains(start)) { + return false; + } + visited.add(start); + int leftStart = start-arr[start]; + boolean moveLeft = false; + if (leftStart >= 0) { + moveLeft = canReach(arr, leftStart); + } + int rightStart = start+arr[start]; + boolean moveRight = false; + if (rightStart >= 0) { + moveRight = canReach(arr, rightStart); + } + + return moveRight || moveLeft; + } + + public static void main(String args[]) { + MinJumpToZerothIndexInArray minJumpToZerothIndexInArray = new MinJumpToZerothIndexInArray(); + //int arr[] = {4,2,3,0,3,1,2}; + int arr[] = {3,0,2,1,2}; + System.out.println(minJumpToZerothIndexInArray.canReach(arr, 2)); + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/MinimumKnightMoves.java b/src/main/java/com/bhole/advanced_ds/random/medium/MinimumKnightMoves.java new file mode 100644 index 0000000..96f17ba --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/MinimumKnightMoves.java @@ -0,0 +1,94 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class MinimumKnightMoves { + HashMap map; + + public int minKnightMoves(int x, int y) { + Coord start = new Coord(0, 0); + map = new HashMap<>(); + map.put(start, 0); + map.put(new Coord(1,2), 1); + map.put(new Coord(2,1), 1); + map.put(new Coord(0,1), 3); + map.put(new Coord(1,0), 3); + + map.put(new Coord(2,0), 2); + map.put(new Coord(1,1), 2); + map.put(new Coord(0,2), 2); + + map.put(new Coord(2,2), 4); + + return minMoves( new Coord(x<0?-x:x,y<0?-y:y)); + } + + private int minMoves(Coord cur) { + if(cur.is3rdQ()) return Integer.MAX_VALUE; + //System.out.println("cur="+cur); + if (cur.x ==0 && cur.y == 0) return 0; + if (map.containsKey(cur)) { + return map.get(cur); + } + List curMoves = getBackMoves(cur); + int min = Integer.MAX_VALUE; + for (Coord move : curMoves) { + min = Math.min(minMoves(move)+1, min); + } + map.put(cur, min); + //System.out.println("cur="+cur+" min"+min); + return min; + } + + private List getBackMoves(Coord dest) { + List res = new ArrayList<>(); + res.add(new Coord(Math.abs(dest.x-1), Math.abs(dest.y-2))); + res.add(new Coord(Math.abs(dest.x-2), Math.abs(dest.y-1))); + return res; + } + + class Coord { + int x=0,y=0; + public Coord(int x, int y) { + this.x = x; + this.y = y; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Coord coord = (Coord) o; + return x == coord.x && + y == coord.y; + } + + @Override + public int hashCode() { + return Objects.hash(x, y); + } + + public boolean isFirstQ(){ + return this.x>=0 && this.y>=0; + } + + public boolean is3rdQ() { + return (this.x)<0 && (this.y)<0; + } + + @Override + public String toString() { + return "Coord{" + + "x=" + x + + ", y=" + y + + '}'; + } + } + public static void main(String args[]) { + MinimumKnightMoves moves = new MinimumKnightMoves(); + System.out.println(moves.minKnightMoves(5,5));; + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/SubStringWithEvenCountOfVowels.java b/src/main/java/com/bhole/advanced_ds/random/medium/SubStringWithEvenCountOfVowels.java new file mode 100644 index 0000000..6f18c05 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/SubStringWithEvenCountOfVowels.java @@ -0,0 +1,39 @@ +package com.bhole.advanced_ds.random.medium; + +import java.util.HashMap; +import java.util.Map; + +public class SubStringWithEvenCountOfVowels { + public int findTheLongestSubstring(String s) { + Map vowels = new HashMap<>(); + vowels.put('a', 1); + vowels.put('e', 2); + vowels.put('i', 4); + vowels.put('o', 8); + vowels.put('u', 16); + int state = 0; + int max = 0; + Map map = new HashMap<>(); + map.put(0, -1); + for (int i=0; i map = new HashMap<>(); + for (int len=0; len path1 = new ArrayList(); + List path2 = new ArrayList(); + tracePath(root, p, path1); + tracePath(root, q, path2); + + //path1.stream().forEach(a-> System.out.println(a.val)); + //path2.stream().forEach(a-> System.out.println(a.val)); + int p1 = 0; + int p2 = 0; + TreeNode lca = null; + while (p1 path) { + if (root==null) return false; + + path.add(root); + if (root == p) { + return true; + } + + boolean res = tracePath(root.left, p, path) || tracePath(root.right, p, path) ; + + if(!res) path.remove(root); + + return res; + } + +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/tree/LowestCommonAncestorOfNodes.java b/src/main/java/com/bhole/advanced_ds/random/medium/tree/LowestCommonAncestorOfNodes.java new file mode 100644 index 0000000..c455db2 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/tree/LowestCommonAncestorOfNodes.java @@ -0,0 +1,40 @@ +package com.bhole.advanced_ds.random.medium.tree; + +import com.bhole.advanced_ds.rmq.TreeNode; + +import java.util.HashSet; +import java.util.Set; + +public class LowestCommonAncestorOfNodes { + Set set; + + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode[] nodes) { + set = new HashSet<>(); + for (TreeNode t : nodes) { + set.add(t.value); + } + return helper(root); + } + + private TreeNode helper(TreeNode node) { // recursive helper function + + if (node == null) { + return null; + } + if (set.contains(node.value)) { // if we've reached a node of interest, return it + return node; + } + TreeNode left = helper(node.left); + TreeNode right = helper(node.right); + + if (left == null && right == null) { // none of this node's descendents are nodes of interest + return null; + } else if ((left != null) && (right != null)) { // this node is a common ancestor of two or more nodes of interest + return node; + } else if (left == null) { // left is null but right isn't + return right; + } else { // if right == null // right is null but left isn't + return left; + } + } +} diff --git a/src/main/java/com/bhole/advanced_ds/random/medium/tree/SmallestCommonRegionLCA.java b/src/main/java/com/bhole/advanced_ds/random/medium/tree/SmallestCommonRegionLCA.java new file mode 100644 index 0000000..a3252b3 --- /dev/null +++ b/src/main/java/com/bhole/advanced_ds/random/medium/tree/SmallestCommonRegionLCA.java @@ -0,0 +1,97 @@ +package com.bhole.advanced_ds.random.medium.tree; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +/* +Input: +regions = [["Earth","North America","South America"], +["North America","United States","Canada"], +["United States","New York","Boston"], +["Canada","Ontario","Quebec"], +["South America","Brazil"]], +region1 = "Quebec", +region2 = "New York" +Output: "North America" + */ +public class SmallestCommonRegionLCA { + + + public String findSmallestRegion(List> regions, String region1, String region2) { + Map map = new HashMap<>(); + Map intToHeadNameMap = new HashMap<>(); + AtomicInteger counter = new AtomicInteger(1); + Map nodeToParentMap = new HashMap<>(); + regions.forEach(regionList-> { + if (!regionList.isEmpty()) { + String head = regionList.get(0); + for (int i=0; i0) nodeToParentMap.put(map.get(curReg), map.get(head)); + } + intToHeadNameMap.put(map.get(head), head); + } + }); + List path1 = new ArrayList<>(); + List path2 = new ArrayList<>(); + tracePath(map, nodeToParentMap, intToHeadNameMap, region1, path1); + tracePath(map, nodeToParentMap, intToHeadNameMap, region2, path2); + + int p1 = path1.size()-1; + int p2 = path2.size()-1; + Integer lca = null; + while (p1>=0 && p2>=0) { + if (path1.get(p1) == path2.get(p2)) { + lca = path1.get(p1); + } else { + break; + } + p1--;p2--; + } + if (lca !=null) { + return intToHeadNameMap.get(lca); + } else { + return null; + } + } + + private void tracePath(Map map,Map nodeToParentMap,Map intToHeadNameMap, String region, List path) { + if (region!=null) { + Integer regionID = map.get(region); + if (intToHeadNameMap.containsKey(regionID)) { + path.add(regionID); + } + if (regionID!=null) { + Integer parent = nodeToParentMap.get(regionID); + while (parent!=null) { + path.add(parent); + parent = nodeToParentMap.get(parent); + } + } else { + //log error + } + } + } + + public static void main(String args[]) { + SmallestCommonRegionLCA lca = new SmallestCommonRegionLCA(); + List> regions = List.of( + List.of("Earth","North America","South America"), + List.of("North America","United States","Canada"), + List.of("United States","New York","Boston"), + List.of("Canada","Ontario","Quebec"), + List.of("South America","Brazil") + ); +// System.out.println(lca.findSmallestRegion(regions,"New York", "Quebec")); +// System.out.println(lca.findSmallestRegion(regions,"Canada", "South America")); + System.out.println(lca.findSmallestRegion(regions,"Canada", "North America")); + + } + + + + +} diff --git a/src/main/java/com/bhole/advanced_ds/rmq/TreeNode.java b/src/main/java/com/bhole/advanced_ds/rmq/TreeNode.java index ca393d6..b23b00f 100644 --- a/src/main/java/com/bhole/advanced_ds/rmq/TreeNode.java +++ b/src/main/java/com/bhole/advanced_ds/rmq/TreeNode.java @@ -3,9 +3,9 @@ import java.util.Objects; public class TreeNode { - Integer value; - TreeNode left; - TreeNode right; + public Integer value; + public TreeNode left; + public TreeNode right; public TreeNode() { } diff --git a/src/main/python/test.py b/src/main/python/test.py new file mode 100644 index 0000000..320069e --- /dev/null +++ b/src/main/python/test.py @@ -0,0 +1,8 @@ + +file1 = open('myfile.txt', 'r') +Lines = file1.readlines() + +count = 0 +# Strips the newline character +for line in Lines: + print("Line{}: {}".format(count, line.strip())) \ No newline at end of file diff --git a/src/test/java/com/bhole/advanced_ds/dp/basic/MinArrayJumpTest.java b/src/test/java/com/bhole/advanced_ds/dp/basic/MinArrayJumpTest.java new file mode 100644 index 0000000..51cd64f --- /dev/null +++ b/src/test/java/com/bhole/advanced_ds/dp/basic/MinArrayJumpTest.java @@ -0,0 +1,12 @@ +package com.bhole.advanced_ds.dp.basic; + +import org.junit.Assert; +import org.junit.Test; + +public class MinArrayJumpTest { + @Test + public void test() { + MinArrayJump jump = new MinArrayJump(); + Assert.assertEquals(jump.solve(new int[] {2,3,1,1,2,4,2,0,1,1}), 4); + } +}