├── src ├── hackerrank │ └── csharp │ │ ├── hackerrank.csproj │ │ ├── Program.cs │ │ ├── clouds.cs │ │ ├── swaps.cs │ │ ├── bribes.cs │ │ └── repeatedString.cs └── javas │ ├── .classpath │ ├── src │ ├── linkedlists │ │ ├── ListNode.java │ │ ├── MyQueue.java │ │ ├── MyStack.java │ │ ├── StackQueue.java │ │ ├── ReverseLinkedList.java │ │ ├── MyLinkedList.java │ │ ├── MergeKLists.java │ │ ├── MinStack.java │ │ ├── Merge.java │ │ └── MaxStack.java │ ├── trees │ │ ├── TreeNode.java │ │ ├── MaxDepth.java │ │ ├── MinDepth.java │ │ ├── DiameterBinaryTree.java │ │ ├── HasSumRootToLeaf.java │ │ ├── TreeIterator.java │ │ ├── CheckBST.java │ │ ├── MinimalBST.java │ │ ├── TwoSumIV.java │ │ ├── ArithmeticExpressionTree.java │ │ ├── SymmetricTree.java │ │ ├── CodecTree.java │ │ └── ListOfDepths.java │ ├── strings │ │ ├── MyPalindrome.java │ │ ├── ReverseString.java │ │ ├── ReverseWords.java │ │ ├── ValidAnagram.java │ │ ├── JewelsAndStones.java │ │ ├── BeautifulBinaryString.java │ │ ├── Pangram.java │ │ ├── LicenseKeyFormatting.java │ │ ├── FunnyString.java │ │ ├── AlternatingCharacters.java │ │ ├── RobotReturnOrigin.java │ │ ├── ValidPalindrome.java │ │ ├── LongestCommonPrefix.java │ │ ├── Gemstones.java │ │ ├── DetectCapital.java │ │ ├── LongestSubstringWithoutRepeating.java │ │ ├── SuperReduced.java │ │ ├── AddStrings.java │ │ ├── ProgrammerString.java │ │ ├── GenerateParenthesis.java │ │ ├── MinWindowSubstring.java │ │ ├── AllAnagrams.java │ │ ├── DecodeString.java │ │ ├── SubdomainVisitCount.java │ │ ├── FindCommonCharacters.java │ │ ├── WeightedStrings.java │ │ ├── ComparingVersionNumbers.java │ │ └── ReorderLogs.java │ ├── arrays │ │ ├── BuyAndSellStock.java │ │ ├── SumDigitsMinNumber.java │ │ ├── CanAttendMeetings.java │ │ ├── HourglassSum.java │ │ ├── KthLargest.java │ │ ├── MaximumSubarray.java │ │ ├── AllNGramms.java │ │ ├── TwoSum.java │ │ ├── MergeArrays.java │ │ ├── TwoSumSorted.java │ │ ├── MoveZeroes.java │ │ ├── MergeSortedArrays.java │ │ ├── NumIslands.java │ │ ├── MergeSortedArraysInPlace.java │ │ ├── FruitIntoBasket.java │ │ ├── PlusOne.java │ │ ├── ContainerWithMostWater.java │ │ ├── MaxAreaIsland.java │ │ ├── SingleElement.java │ │ ├── EvalReversePolishNotation.java │ │ ├── IslandPerimeter.java │ │ └── MeetingRoomsTwo.java │ ├── searching │ │ └── BinarySearch.java │ ├── misc │ │ ├── Rotate.java │ │ ├── ProductKConsecutive.java │ │ ├── AbsolutePermutation.java │ │ ├── PairBrackets.java │ │ ├── TinyUrl.java │ │ ├── TrappingRainWater.java │ │ ├── AddToAllCollection.java │ │ ├── MergeRanges.java │ │ ├── LexicalSort.java │ │ ├── LRUCache.java │ │ ├── MyHashSet.java │ │ └── MyHashMap.java │ ├── dynamic │ │ ├── TripleStep.java │ │ └── ClimbStairs.java │ ├── graphs │ │ ├── MostFriendsInCommon.java │ │ └── Clone.java │ └── heaps │ │ ├── MyMinHeap.java │ │ └── MyMaxHeap.java │ ├── .project │ └── .settings │ └── org.eclipse.jdt.core.prefs └── README.md /src/hackerrank/csharp/hackerrank.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.2 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /src/hackerrank/csharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Program { 4 | public static void Main(string[] args){ 5 | var a = new int[]{2 ,3 ,4 ,1 ,5}; 6 | 7 | Console.WriteLine(Swaps.minimumSwaps(a)); 8 | } 9 | } -------------------------------------------------------------------------------- /src/javas/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/javas/src/linkedlists/ListNode.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class ListNode { 4 | public Object data; 5 | public ListNode next; 6 | 7 | public ListNode(Object data) { 8 | this.data = data; 9 | } 10 | 11 | public ListNode(Object data, ListNode next) { 12 | this(data); 13 | this.next = next; 14 | } 15 | } -------------------------------------------------------------------------------- /src/javas/src/trees/TreeNode.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | public class TreeNode { 4 | TreeNode left; 5 | TreeNode right; 6 | int value; 7 | 8 | public TreeNode() { 9 | } 10 | public TreeNode(int value) { 11 | this.value = value; 12 | this.left = this.right = null; 13 | } 14 | 15 | boolean isLeaf() {return this.left == null && this.right == null;} 16 | } -------------------------------------------------------------------------------- /src/javas/src/trees/MaxDepth.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | 3 | package trees; 4 | 5 | public class MaxDepth { 6 | public int maxDepth(TreeNode root) { 7 | if (root == null) 8 | return 0; 9 | 10 | int left = maxDepth(root.left) + 1; 11 | int right = maxDepth(root.right) + 1; 12 | 13 | return Math.max(left, right); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/javas/src/strings/MyPalindrome.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class MyPalindrome { 4 | public static Boolean check(String toCheck) { 5 | char[] toCheckCharArray = toCheck.toCharArray(); 6 | int i, j, len = toCheckCharArray.length; 7 | 8 | for (i = 0, j = len - 1; i < j; i++, j--) { 9 | if (toCheckCharArray[i] != toCheckCharArray[j]) 10 | return false; 11 | } 12 | 13 | return true; 14 | } 15 | } -------------------------------------------------------------------------------- /src/javas/src/trees/MinDepth.java: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | 3 | package trees; 4 | 5 | public class MinDepth { 6 | public int minDepth(TreeNode root) { 7 | if (root == null) 8 | return 0; 9 | 10 | int left = minDepth(root.left) + 1; 11 | int right = minDepth(root.right) + 1; 12 | 13 | if (left > 1 && right > 1) 14 | return Math.min(left, right); 15 | 16 | return Math.max(left, right); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /src/javas/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | javas 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/javas/src/arrays/BuyAndSellStock.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | package arrays; 4 | 5 | public class BuyAndSellStock { 6 | public int maxProfit(int[] prices) { 7 | int min = Integer.MAX_VALUE; 8 | int spread = 0; 9 | 10 | for (int i = 0; i < prices.length; i++) { 11 | int p = prices[i]; 12 | min = Math.min(min, p); 13 | 14 | spread = Math.max(spread, p - min); 15 | } 16 | 17 | return spread; 18 | } 19 | } -------------------------------------------------------------------------------- /src/hackerrank/csharp/clouds.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | public class Clouds 5 | { 6 | static int jumpingOnClouds(int[] clouds) 7 | { 8 | int jumps = 0; 9 | Console.WriteLine(clouds); 10 | 11 | for (int i = 0; i < clouds.Count(); i++) 12 | { 13 | jumps++; 14 | Console.WriteLine($"i: {i} jumps: {jumps}"); 15 | 16 | if ((i + 2) <= clouds.Count() && clouds[i + 2] == 0) 17 | i += 1; 18 | } 19 | return jumps; 20 | } 21 | } -------------------------------------------------------------------------------- /src/javas/src/trees/DiameterBinaryTree.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/diameter-of-binary-tree 2 | 3 | package trees; 4 | 5 | public class DiameterBinaryTree{ 6 | int max = 0; 7 | public int diameterOfBinaryTree(TreeNode root) { 8 | height(root); 9 | return max; 10 | } 11 | private int height(TreeNode node){ 12 | if(node == null) return 0; 13 | 14 | int left = height(node.left); 15 | int right = height(node.right); 16 | 17 | max = Math.max(max, left + right); 18 | return Math.max(left, right) + 1; 19 | } 20 | } -------------------------------------------------------------------------------- /src/javas/src/trees/HasSumRootToLeaf.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/path-sum/ 2 | 3 | package trees; 4 | 5 | public class HasSumRootToLeaf { 6 | public boolean hasPathSum(TreeNode root, int sum) { 7 | return traversal(root, sum, 0); 8 | } 9 | 10 | private boolean traversal(TreeNode node, int sum, int currentSum) { 11 | if (node == null) return false; 12 | 13 | currentSum += node.value; 14 | 15 | if (node.isLeaf()) return currentSum == sum; 16 | 17 | return traversal(node.left, sum, currentSum) || traversal(node.right, sum, currentSum); 18 | } 19 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/SumDigitsMinNumber.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class SumDigitsMinNumber{ 4 | public int sum(int[] numbers){ 5 | if(numbers == null || numbers.length == 0) return 0; 6 | 7 | int min = Integer.MAX_VALUE; 8 | for(int n : numbers) 9 | if(n < min) min = n; 10 | 11 | int sum = 0; 12 | while(min > 0){ 13 | sum += min%10; 14 | min/=10; 15 | } 16 | 17 | return sum % 2 == 0 ? 1 : 0; 18 | } 19 | 20 | public static void main(String[] args) { 21 | System.out.println(new SumDigitsMinNumber().sum(new int[]{999,1000})); 22 | } 23 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/CanAttendMeetings.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/meeting-rooms 2 | 3 | package arrays; 4 | 5 | import java.util.Arrays; 6 | 7 | public class CanAttendMeetings { 8 | public boolean canAttendMeetings(int[][] intervals) { 9 | if (intervals == null || intervals.length < 2) 10 | return true; 11 | 12 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 13 | 14 | int ini = 0, end = 1; 15 | 16 | for (int i = 1; i < intervals.length; i++) 17 | if (intervals[i][ini] < intervals[i-1][end]) 18 | return false; 19 | 20 | return true; 21 | } 22 | } -------------------------------------------------------------------------------- /src/javas/src/strings/ReverseString.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/ 2 | 3 | package strings; 4 | 5 | public class ReverseString{ 6 | public void reverseString(char[] s) { 7 | if(s == null || s.length == 0) return; 8 | 9 | int i=0, j=s.length-1; 10 | while(j>i){ 11 | char t = s[j]; 12 | s[j--] = s[i]; 13 | s[i++] = t; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | // String input = "vinicius"; 19 | String input = "impar"; 20 | char[] s = input.toCharArray(); 21 | 22 | new ReverseString().reverseString(s); 23 | } 24 | } -------------------------------------------------------------------------------- /src/javas/src/searching/BinarySearch.java: -------------------------------------------------------------------------------- 1 | package searching; 2 | 3 | public class BinarySearch { 4 | public int search(int[] arr, int key) { 5 | return search(arr, key, 0, arr.length - 1); 6 | } 7 | 8 | private int search(int[] arr, int key, int l, int h) { 9 | System.out.println("l: " + l + " h: " + h); 10 | if (l > h) 11 | return -1; 12 | 13 | int pivot = (l + h) / 2; 14 | 15 | if (arr[pivot] == key) 16 | return pivot; 17 | else { 18 | if (key < arr[pivot]) h = pivot -1; 19 | else l = pivot +1; 20 | 21 | return search(arr, key, l, h); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/javas/src/arrays/HourglassSum.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/2d-array 2 | 3 | package arrays; 4 | 5 | public class HourglassSum { 6 | 7 | public int hourglassSum(int[][] arr) { 8 | int max = Integer.MIN_VALUE; 9 | for (int y = 0; y < 4; y++) { 10 | for (int x = 0; x < 4; x++) { 11 | int hourglass = arr[y][x] + arr[y][x + 1] + arr[y][x + 2] + 12 | arr[y + 1][x + 1] + 13 | arr[y + 2][x] + arr[y + 2][x + 1] + arr[y + 2][x + 2]; 14 | 15 | max = Math.max(hourglass, max); 16 | } 17 | } 18 | 19 | return max; 20 | } 21 | } -------------------------------------------------------------------------------- /src/hackerrank/csharp/swaps.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | public class Swaps 5 | { 6 | public static int minimumSwaps(int[] arr) 7 | { 8 | var visited = new bool[arr.Length]; 9 | int swaps = 0; 10 | 11 | for (int i = 0; i < arr.Length; i++) 12 | { 13 | int j = i, cycles = 0; 14 | while (!visited[j]) 15 | { 16 | visited[j] = true; 17 | j = arr[j] - 1; 18 | cycles++; 19 | } 20 | if (cycles != 0) 21 | swaps += cycles - 1; 22 | } 23 | 24 | return swaps; 25 | } 26 | } -------------------------------------------------------------------------------- /src/javas/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=10 4 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 5 | org.eclipse.jdt.core.compiler.compliance=10 6 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 7 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 8 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 9 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 10 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 11 | org.eclipse.jdt.core.compiler.source=10 12 | -------------------------------------------------------------------------------- /src/javas/src/strings/ReverseWords.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-words-in-a-string/ 2 | 3 | package strings; 4 | 5 | import java.util.*; 6 | 7 | public class ReverseWords { 8 | public String reverseWords(String s) { 9 | if (s == null || s.trim().length() == 0) 10 | return ""; 11 | 12 | List parts = Arrays.asList(s.trim().split(" ")); 13 | Collections.reverse(parts); 14 | 15 | StringBuilder sb = new StringBuilder(); 16 | for (String p : parts) 17 | if (!p.trim().equals("")) { 18 | sb.append(p); 19 | sb.append(" "); 20 | } 21 | 22 | return sb.toString().substring(0, sb.length() - 1); 23 | } 24 | } -------------------------------------------------------------------------------- /src/javas/src/strings/ValidAnagram.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-anagram/ 2 | 3 | package strings; 4 | 5 | public class ValidAnagram{ 6 | public boolean isAnagram(String s, String t) { 7 | if(s == null || t == null) return false; 8 | if(s.length() != t.length()) return false; 9 | 10 | char[] chars = new char[26]; 11 | int missing = s.length(); 12 | 13 | for(char c : s.toCharArray()) 14 | chars[c-97]++; 15 | 16 | for(char c: t.toCharArray()) 17 | { 18 | if(chars[c-97] == 0) return false; 19 | else{ 20 | chars[c-97]--; 21 | missing--; 22 | } 23 | } 24 | 25 | return missing == 0; 26 | } 27 | } -------------------------------------------------------------------------------- /src/javas/src/misc/Rotate.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.LinkedList; 4 | import java.util.Queue; 5 | 6 | public class Rotate { 7 | public static int[] rotLeft(int[] a, int d) { 8 | int len = a.length; 9 | if (len == d) 10 | return a; 11 | 12 | Queue q = new LinkedList<>(); 13 | for (int i = 0; i < d; i++) 14 | q.add(a[i]); 15 | 16 | int diff = len - d; 17 | for (int i = d; i < len; i++) { 18 | int newPos = i + diff; 19 | if (newPos >= len) 20 | newPos = newPos - len; 21 | 22 | a[newPos] = a[i]; 23 | } 24 | for (int i = (len - d); i < len; i++) 25 | a[i] = q.poll(); 26 | 27 | return a; 28 | } 29 | } -------------------------------------------------------------------------------- /src/javas/src/strings/JewelsAndStones.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jewels-and-stones 2 | 3 | package strings; 4 | 5 | public class JewelsAndStones { 6 | public int numJewelsInStones(String J, String S) { 7 | int total = 0; 8 | 9 | if(J == null || J.isEmpty()) return total; 10 | if(S == null || S.isEmpty()) return total; 11 | 12 | for(Character c : S.toCharArray()) 13 | if(J.contains(c.toString())) 14 | total++; 15 | 16 | return total; 17 | } 18 | 19 | public static void main(String[] args) { 20 | String j = "aA"; 21 | String s = "aAAbbbb"; 22 | 23 | System.out.println(new JewelsAndStones().numJewelsInStones(j, s)); 24 | } 25 | } -------------------------------------------------------------------------------- /src/javas/src/strings/BeautifulBinaryString.java: -------------------------------------------------------------------------------- 1 | //https://www.hackerrank.com/challenges/beautiful-binary-string/ 2 | 3 | package strings; 4 | 5 | public class BeautifulBinaryString { 6 | public int beautifulBinaryString(String s) { 7 | if (s == null || s.isEmpty()) 8 | return 0; 9 | 10 | int i = 0, j = i + 1, k = j + 1; 11 | int changes = 0; 12 | while (k < s.length()) { 13 | if (s.charAt(i) == '0' && s.charAt(j) == '1' && s.charAt(k) == '0') { 14 | changes++; 15 | i = k + 1; 16 | j = i + 1; 17 | k = j + 1; 18 | } else { 19 | i++; 20 | j++; 21 | k++; 22 | } 23 | } 24 | 25 | return changes; 26 | } 27 | } -------------------------------------------------------------------------------- /src/javas/src/strings/Pangram.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.*; 4 | 5 | public class Pangram { 6 | public String pangrams(String s) { 7 | if (s == null || s.length() < 26) 8 | return "not pangram"; 9 | 10 | HashSet hash = new HashSet<>(26); 11 | for (int i = 97; i < 97 + 26; i++) 12 | hash.add((char) i); 13 | 14 | for (char c : s.toLowerCase().toCharArray()) 15 | if (hash.remove(c) && hash.size() == 0) 16 | return "pangram"; 17 | 18 | return "not pangram"; 19 | } 20 | 21 | public static void main(String[] args) { 22 | System.out.println(new Pangram().pangrams("We promptly judged antique ivory buckles for the next prize")); 23 | } 24 | } -------------------------------------------------------------------------------- /src/javas/src/misc/ProductKConsecutive.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | public class ProductKConsecutive { 4 | public int[] product(int[] nums, int k){ 5 | if(nums == null || nums.length < k) return nums; 6 | 7 | int[] res = new int[nums.length]; 8 | int t = k; 9 | for (int i = 0; i < nums.length; i++){ 10 | int p = nums[i]; 11 | t = k; 12 | while(t > 0 && (i+t) < nums.length){ 13 | p *= nums[ i + t]; 14 | t--; 15 | } 16 | res[i] = p; 17 | } 18 | 19 | return res; 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[] r = new ProductKConsecutive().product(new int[] { 1, 2,3,4,5 }, 2); 24 | for (int p : r) 25 | System.out.print(p + " "); 26 | } 27 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MyQueue.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class MyQueue { 4 | MyLinkedList list; 5 | 6 | public MyQueue() { 7 | this.list = new MyLinkedList(); 8 | } 9 | 10 | public Boolean isEmpty() { 11 | return this.list.isEmpty(); 12 | } 13 | 14 | public void enqueue(Object item) { 15 | this.list.tailAdd(item); 16 | } 17 | 18 | public Object dequeue() { 19 | if (!this.isEmpty()) 20 | return this.list.removeHead(); 21 | 22 | return null; 23 | } 24 | 25 | public static void main(String[] args) { 26 | MyQueue q = new MyQueue(); 27 | for (int i = 1; i <= 35; i++) 28 | q.enqueue(i); 29 | 30 | while (!q.isEmpty()) 31 | System.out.print(q.dequeue() + " "); 32 | } 33 | } -------------------------------------------------------------------------------- /src/javas/src/strings/LicenseKeyFormatting.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class LicenseKeyFormatting{ 4 | public String format(String key, int k){ 5 | int j = k; 6 | StringBuilder res = new StringBuilder(); 7 | 8 | for(int i=key.length()-1;i>=0;i--){ 9 | char c = key.charAt(i); 10 | if(c == '-') continue; 11 | 12 | if(j == 0) 13 | { 14 | res.append("-"); 15 | j = k; 16 | } 17 | 18 | res.append(Character.toUpperCase(c)); 19 | j--; 20 | } 21 | 22 | return res.reverse().toString(); 23 | } 24 | 25 | public static void main(String[] args) { 26 | String key = "2-5g-3-j"; 27 | System.out.println(new LicenseKeyFormatting().format(key, 2)); 28 | } 29 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MyStack.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class MyStack { 4 | MyLinkedList list; 5 | 6 | public MyStack() { 7 | this.list = new MyLinkedList(); 8 | } 9 | 10 | public Boolean isEmpty() { 11 | return this.list.isEmpty(); 12 | } 13 | 14 | public void push(Object data) { 15 | this.list.add(data); 16 | } 17 | 18 | public Object pop() { 19 | if (!this.isEmpty()) 20 | return this.list.removeHead().toString(); 21 | 22 | return null; 23 | } 24 | 25 | public static void main(String[] args) { 26 | MyStack stack = new MyStack(); 27 | for(int i=1;i<=10;i++) 28 | stack.push(i); 29 | 30 | while (!stack.isEmpty()){ 31 | System.out.print(stack.pop()); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/KthLargest.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.PriorityQueue; 4 | 5 | public class KthLargest{ 6 | public int kthLargest(int[] nums, int k){ 7 | if(nums == null || nums.length == 0) return -1; 8 | if(nums.length == 1) return nums[0]; 9 | 10 | PriorityQueue heap = new PriorityQueue<>(k, (a, b) -> a > b ? 1 : -1); 11 | 12 | for(int n : nums){ 13 | if(heap.size() < k) 14 | heap.add(n); 15 | else if(n > heap.peek()){ 16 | heap.poll(); 17 | heap.add(n); 18 | } 19 | } 20 | 21 | return heap.poll(); 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] nums = new int[]{10,9,8,7,6,5,4,3,2,1}; 26 | System.out.println(new KthLargest().kthLargest(nums, 3)); 27 | } 28 | } -------------------------------------------------------------------------------- /src/javas/src/strings/FunnyString.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class FunnyString { 4 | public String funnyString(String s) { 5 | int[] totalA = new int[s.length()]; 6 | int[] totalB = new int[s.length()]; 7 | 8 | char[] chars = s.toCharArray(); 9 | for (int i = 0, j = s.length() - 1; i < s.length(); i++, j--) { 10 | totalA[i] = (int) chars[i]; 11 | totalB[i] = (int) chars[j]; 12 | } 13 | 14 | for (int i = 0, j = i + 1; i < totalA.length - 1; i++, j++) { 15 | if (Math.abs(totalA[i] - totalA[j]) != Math.abs(totalB[i] - totalB[j])) 16 | return "Not Funny"; 17 | } 18 | 19 | return "Funny"; 20 | } 21 | 22 | public static void main(String[] args) { 23 | System.out.println(new FunnyString().funnyString("ivvkx")); 24 | } 25 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MaximumSubarray.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray 2 | 3 | package arrays; 4 | 5 | public class MaximumSubarray { 6 | public int maxSubArray(int[] nums) { 7 | if (nums == null || nums.length == 0) 8 | return 0; 9 | 10 | int max = nums[0]; 11 | int current = nums[0]; 12 | 13 | for(int i=1;i " + new AlternatingCharacters().alternatingCharacters(s)); 25 | } 26 | } -------------------------------------------------------------------------------- /src/javas/src/strings/RobotReturnOrigin.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/robot-return-to-origin/ 2 | 3 | package strings; 4 | 5 | public class RobotReturnOrigin { 6 | public boolean judgeCircle(String moves) { 7 | if (moves == null || moves.isEmpty()) 8 | return true; 9 | 10 | int x = 0, y = 0; 11 | for (char c : moves.toCharArray()) { 12 | switch (c) { 13 | case 'U': 14 | y++; 15 | break; 16 | case 'R': 17 | x++; 18 | break; 19 | case 'D': 20 | y--; 21 | break; 22 | default: 23 | x--; 24 | } 25 | } 26 | 27 | return x == 0 && y == 0; 28 | } 29 | 30 | public static void main(String[] args) { 31 | String input = "UD"; 32 | // String input = "LL"; 33 | System.out.println(new RobotReturnOrigin().judgeCircle(input)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/StackQueue.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class StackQueue { 4 | private MyStack stack1, stack2; 5 | 6 | public StackQueue() { 7 | stack1 = new MyStack(); 8 | stack2 = new MyStack(); 9 | } 10 | 11 | public void enqueu(Integer n){ 12 | stack1.push(n); 13 | } 14 | 15 | public Integer dequeue(){ 16 | if(stack2.isEmpty()){ 17 | while(!stack1.isEmpty()) 18 | stack2.push(stack1.pop()); 19 | } 20 | 21 | if(stack2.isEmpty()) return null; 22 | 23 | return Integer.parseInt(stack2.pop().toString()); 24 | } 25 | 26 | public static void main(String[] args){ 27 | StackQueue sq = new StackQueue(); 28 | 29 | for(int i=1;i<10;i++) 30 | sq.enqueu(i); 31 | 32 | Integer v = null; 33 | 34 | while((v=sq.dequeue())!=null){ 35 | System.out.println(v); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/AllNGramms.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.*; 4 | 5 | public class AllNGramms { 6 | public List> nGramms(String[] input, int n) { 7 | List> result = new ArrayList<>(); 8 | List partial = new ArrayList<>(); 9 | 10 | int len = input.length; 11 | int k = 0; 12 | 13 | while(k < n){ 14 | for(int i = 0; i < len - k; i++){ 15 | for(int j = i; j <= k+i; j++){ 16 | partial.add(input[j]); 17 | } 18 | 19 | result.add(partial); 20 | partial = new ArrayList<>(); 21 | } 22 | k++; 23 | } 24 | return result; 25 | } 26 | 27 | public static void main(String[] args) { 28 | String[] input = {"a", "b", "c", "d"}; 29 | List> res = new AllNGramms().nGramms(input, 4); 30 | 31 | for(List l : res) 32 | System.out.println(l); 33 | } 34 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/TwoSum.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum 2 | 3 | package arrays; 4 | 5 | import java.util.Hashtable; 6 | 7 | public class TwoSum { 8 | public int[] twoSum(int[] nums, int target) { 9 | Hashtable seen = new Hashtable(); 10 | 11 | int[] res = new int[2]; 12 | 13 | for(int i=0; i"); 35 | rev = rev.next; 36 | } 37 | System.out.print("NULL"); 38 | } 39 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MergeArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class MergeArrays { 4 | public int[] merge(int[] arr1, int m, int[] arr2, int n) { 5 | return merge(arr1, m, arr2, n, 0, 0); 6 | } 7 | 8 | private int[] merge(int[] a1, int m, int[] a2, int n, int i1, int i2) { 9 | if (i2 >= n) 10 | return a1; 11 | 12 | if (a1[i1] > a2[i2]) { 13 | for (int i = (m + i2 - 1); i >= i1; i--) 14 | a1[i + 1] = a1[i]; 15 | 16 | a1[i1] = a2[i2++]; 17 | } else if (a1.length - i1 <= n - i2) 18 | a1[i1++] = a2[i2++]; 19 | else 20 | i1++; 21 | 22 | return merge(a1, m, a2, n, i1, i2); 23 | } 24 | 25 | public static void main(String[] args) { 26 | int[] a1 = new int[] { -1, 0, 0, 3, 3, 3, 0, 0, 0 }; 27 | int[] a2 = new int[] { 1, 2, 2, }; 28 | int[] r = new MergeArrays().merge(a1, 6, a2, 3); 29 | for (int i = 0; i < r.length; i++) 30 | System.out.print(r[i] + " "); 31 | } 32 | } -------------------------------------------------------------------------------- /src/javas/src/strings/ValidPalindrome.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-palindrome/ 2 | 3 | package strings; 4 | 5 | public class ValidPalindrome{ 6 | public boolean isPalindrome(String s){ 7 | if(s==null || s.isEmpty()) return true; 8 | 9 | int i=0,j=s.length()-1; 10 | while(i= w.length()) 16 | return prefix; 17 | if (c == '\0') 18 | c = w.charAt(i); 19 | else if (c != w.charAt(i)) 20 | return prefix; 21 | } 22 | prefix = prefix + c; 23 | i++; 24 | } 25 | } 26 | 27 | public static void main(String[] args) { 28 | // String[] input = {"flower", "flow", "flight"}; 29 | String[] input = { "dog", "racecar", "car" }; 30 | System.out.println(new LongestCommonPrefix().longestCommonPrefix(input)); 31 | } 32 | } -------------------------------------------------------------------------------- /src/javas/src/trees/TreeIterator.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | import java.util.Iterator; 6 | 7 | public class TreeIterator implements Iterator { 8 | Deque stack; 9 | 10 | public TreeIterator(TreeNode root) { 11 | stack = new ArrayDeque<>(); 12 | stack.addFirst(root); 13 | } 14 | 15 | public boolean hasNext() { 16 | return !stack.isEmpty(); 17 | } 18 | 19 | public TreeNode next() { 20 | TreeNode next = stack.pop(); 21 | if (next.right != null) 22 | stack.addFirst(next.right); 23 | 24 | if (next.left != null) 25 | stack.addFirst(next.left); 26 | 27 | return next; 28 | } 29 | 30 | public static void main(String[] args) { 31 | TreeNode tree = new CodecTree().deserialize("1,2,3,n,n,4,5"); 32 | 33 | TreeIterator it = new TreeIterator(tree); 34 | while(it.hasNext()) 35 | System.out.println(it.next().value); 36 | } 37 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/TwoSumSorted.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 2 | 3 | package arrays; 4 | 5 | public class TwoSumSorted{ 6 | public int[] twoSum(int[] numbers, int target) { 7 | int[] res = new int[]{-1,-1}; 8 | if(numbers == null || numbers.length == 0) return res; 9 | 10 | int i = 0, j = numbers.length - 1; 11 | while(i target) j--; 17 | else i++; 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] input = new int[]{2, 7, 11, 15}; 26 | // int[] input = new int[]{0, 1, 2, 7, 11, 15, 16, 50, 55, 61}; 27 | int target = 9; 28 | int[] res = new TwoSumSorted().twoSum(input, target); 29 | 30 | System.out.println("[" + res[0] + "," + res[1] + "]"); 31 | } 32 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MoveZeroes.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/ 2 | 3 | package arrays; 4 | 5 | public class MoveZeroes{ 6 | public void moveZeroes(int[] nums){ 7 | if(nums == null || nums.length == 0) return; 8 | 9 | int s = 0, f = s; 10 | while(f < nums.length-1){ 11 | if(nums[s] == 0){ 12 | while(nums[f] == 0 && f < nums.length - 1) f++; 13 | 14 | if(f >= nums.length) break; 15 | 16 | nums[s] = nums[f]; 17 | nums[f] = 0; 18 | } 19 | else 20 | if(++s > f) f = s; 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] input = {0,1,0,3,12}; 26 | // int[] input = {0,0,0,1,2,3}; 27 | // int[] input = {0,1}; 28 | // int[] input = {0}; 29 | // int[] input = {1,0,0,0,4}; 30 | // int[] input = {0,0}; 31 | // int[] input = {1,1}; 32 | new MoveZeroes().moveZeroes(input); 33 | 34 | for(int n : input) 35 | System.out.print(n + ","); 36 | } 37 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Algos 2 | 3 | This repo is just a _sketchbook_ I'm using while/when studying some algorithms and data structures. 4 | 5 | Even though I am trying to get a correct implementation of the algorithms and data structures, the code here isn't intended to be neither optimal nor the most performant ever - as I said it is just a sketchbook. 6 | 7 | ### Why am I doing this? 8 | 9 | You can read a little on this twitter thread: [https://twitter.com/vquaiato/status/1153074713234681857](https://twitter.com/vquaiato/status/1153074713234681857) 10 | 11 | ### Quick Access 12 | 13 | To quick access the exercises by category: 14 | 15 | - [dynamic programming](/src/javas/src/dynamic) 16 | - [graphs](/src/javas/src/graphs) 17 | - [heaps](/src/javas/src/heaps) 18 | - [linked lists](/src/javas/src/linkedlists) 19 | - [misc](/src/javas/src/misc) 20 | - [arrays](/src/javas/src/arrays) 21 | - [searching](src/javas/src/searching) 22 | - [strings](src/javas/src/strings) 23 | - [trees](src/javas/src/trees) 24 | 25 | -------------------------------------------------------------------------------- /src/hackerrank/csharp/bribes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | public class Bribes 5 | { 6 | public static void minimumBribes(int[] q){ 7 | int bribes = 0; 8 | int len = q.Count(); 9 | 10 | int i=0; 11 | while(i 3){ 15 | Console.WriteLine("Too chaotic"); 16 | return; 17 | } 18 | else 19 | if(e > ix){ 20 | int temp = q[i+1]; 21 | if(temp == ix || temp < e){ 22 | q[i+1] = e; 23 | q[i] = temp; 24 | i -= i > 0 ? 1 : 0; 25 | bribes++; 26 | } 27 | else 28 | i++; 29 | } 30 | else 31 | i++; 32 | } 33 | 34 | Console.WriteLine(bribes); 35 | } 36 | } -------------------------------------------------------------------------------- /src/javas/src/misc/AbsolutePermutation.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.HashSet; 4 | 5 | public class AbsolutePermutation { 6 | static int[] absolutePermutation(int n, int k) { 7 | if(n == 1) return new int[]{1}; 8 | if(n%2 != 0 && k != 0) return new int[] {-1}; 9 | 10 | int[] res = new int[n]; 11 | int i=0; 12 | 13 | if(k == 0){ 14 | for(i=0;i seen = new HashSet(); 19 | while(i= n) return new int[] {-1}; 26 | 27 | res[i] = num; res[dest] = i+1; 28 | seen.add(i+1); seen.add(num); 29 | i++; 30 | } 31 | 32 | return res; 33 | } 34 | 35 | public static void main(String[] args){ 36 | for(int i : absolutePermutation(10, 1)) 37 | System.out.print(i + " "); 38 | } 39 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MergeSortedArrays.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class MergeSortedArrays { 4 | public int[] Merge(int[] arr1, int[] arr2){ 5 | int index1 = 0, index2 = 0, indexm = 0; 6 | int totalSize = arr1.length + arr2.length; 7 | int[] merged = new int[totalSize]; 8 | 9 | while(indexm < totalSize) { 10 | if(index1 < arr1.length) { 11 | if(index2 > arr2.length - 1 || arr1[index1] <= arr2[index2]) 12 | { 13 | merged[indexm++] = arr1[index1++]; 14 | } 15 | else 16 | { 17 | merged[indexm++] = arr2[index2++]; 18 | } 19 | } 20 | else 21 | { 22 | merged[indexm++] = arr2[index2++]; 23 | } 24 | } 25 | 26 | return merged; 27 | } 28 | 29 | public static void main(String[] args){ 30 | int[] a = new int[] {}; 31 | int[] b = new int[] {1, 2, 3, 5}; 32 | 33 | int[] merged = new MergeSortedArrays().Merge(a,b); 34 | for (int i : merged) { 35 | System.out.println(i); 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /src/javas/src/strings/Gemstones.java: -------------------------------------------------------------------------------- 1 | // https://www.hackerrank.com/challenges/gem-stones 2 | package strings; 3 | 4 | import java.util.*; 5 | 6 | public class Gemstones { 7 | public int gemstones(String[] arr) { 8 | if (arr == null || arr.length == 0) 9 | return 0; 10 | if (arr.length == 1) 11 | return arr[0].length(); 12 | 13 | Set s = new HashSet(arr[0].length()); 14 | for (int i = 0; i < arr[0].length(); i++) 15 | s.add(arr[0].charAt(i)); 16 | 17 | for (int i = 1; i < arr.length; i++) { 18 | String st = arr[i]; 19 | Set ts = new HashSet(s.size()); 20 | for (int j = 0; j < st.length(); j++) { 21 | if (s.contains(st.charAt(j))) 22 | ts.add(st.charAt(j)); 23 | } 24 | s = ts; 25 | } 26 | 27 | return s.size(); 28 | } 29 | 30 | public static void main(String[] args) { 31 | String[] input = new String[] { "abcdde", "baccd", "eeabg" }; 32 | System.out.println(new Gemstones().gemstones(input)); 33 | } 34 | } -------------------------------------------------------------------------------- /src/javas/src/misc/PairBrackets.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | import linkedlists.*; 3 | 4 | public class PairBrackets { 5 | private static String correctPair(String fromStack){ 6 | switch(fromStack){ 7 | case "{": return "}"; 8 | case "[": return "]"; 9 | case "(": return ")"; 10 | default: return ""; 11 | } 12 | } 13 | public static Boolean matches(String exp) { 14 | MyStack stack = new MyStack(); 15 | char[] expToChars = exp.toCharArray(); 16 | 17 | for (Character c : expToChars) { 18 | if (c == '{' || c == '[' || c == '(') 19 | stack.push(c.toString()); 20 | else if (c == '}' || c == ']' || c == ')') { 21 | var item = stack.pop(); 22 | 23 | if (!c.toString().equalsIgnoreCase(correctPair(item.toString()))) 24 | return false; 25 | } 26 | } 27 | 28 | return stack.isEmpty(); 29 | } 30 | 31 | public static void main(String[] args) { 32 | String exp = "{1+2[(5+$)]]}"; 33 | 34 | System.out.println("Should be false: " + matches(exp)); 35 | } 36 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/NumIslands.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class NumIslands { 4 | public int numIslands(String[][] grid) { 5 | int lines = grid.length; 6 | if(lines == 0) return 0; 7 | 8 | int columns = grid[0].length; 9 | if(columns == 0) return 0; 10 | 11 | int islands = 0; 12 | for(int i=0;i= grid.length || i < 0 || 20 | j >= grid[0].length || j < 0 || 21 | grid[i][j]!="1") return 0; 22 | 23 | grid[i][j] = "0"; 24 | visitIsland(grid, i+1, j); 25 | visitIsland(grid, i-1, j); 26 | visitIsland(grid, i, j+1); 27 | visitIsland(grid, i, j-1); 28 | return 1; 29 | } 30 | 31 | public static void main(String[] args) { 32 | NumIslands n = new NumIslands(); 33 | System.out.print(n.numIslands(new String[][]{{"1","0","1","1","1"},{"1","0","1","0","1"},{"1","1","1","0","1"}})); 34 | } 35 | } -------------------------------------------------------------------------------- /src/javas/src/strings/DetectCapital.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | //https://leetcode.com/problems/detect-capital/ 4 | 5 | public class DetectCapital{ 6 | public boolean detectCapitalUse(String word){ 7 | if(word == null || word.isEmpty()) return true; 8 | 9 | boolean firstIsCapital = Character.isUpperCase(word.charAt(0)); 10 | boolean hadLowerCase = !firstIsCapital; 11 | boolean hadUpperCase = false; 12 | 13 | for(int i=1;i map = new HashMap<>(s.length()); 13 | map.put(s.charAt(i), 0); 14 | 15 | while(j < s.length()){ 16 | if(map.containsKey(s.charAt(j))) 17 | map.remove(s.charAt(i++)); 18 | else{ 19 | map.put(s.charAt(j), j++); 20 | max = Math.max(max, map.size()); 21 | } 22 | } 23 | 24 | return max; 25 | } 26 | public static void main(String[] args) { 27 | String input = "abcabcbb"; 28 | // String input = "pwwkew"; 29 | // String input = "bbbbb"; 30 | // String input = "aabbccc"; 31 | // String input = "aabbcccefghabc"; 32 | // String input = "fghabcaabbccce"; 33 | System.out.println(new LongestSubstringWithoutRepeating().lengthOfLongestSubstring(input)); 34 | } 35 | } -------------------------------------------------------------------------------- /src/javas/src/strings/SuperReduced.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class SuperReduced { 4 | public static String superReducedString(String original, String actual) { 5 | StringBuffer res = new StringBuffer(); 6 | int i = 0; 7 | char[] input = (actual == null ? original : actual).toCharArray(); 8 | 9 | while (i < input.length) { 10 | if (i == (input.length - 1) || input[i] != input[i + 1]) { 11 | res.append(input[i]); 12 | i++; 13 | } else 14 | i += 2; 15 | } 16 | 17 | String result = ""; 18 | if (res.length() == 0) 19 | return "Empty String"; 20 | else 21 | result = res.toString(); 22 | 23 | if (actual != null && result.equals(actual)) 24 | return actual; 25 | else 26 | return superReducedString(original, result); 27 | } 28 | 29 | public static String superReducedString(String s) { 30 | return superReducedString(s, null); 31 | } 32 | 33 | public static void main(String[] args) { 34 | String r = SuperReduced.superReducedString("aaabccddd"); 35 | System.out.println(r); 36 | } 37 | } -------------------------------------------------------------------------------- /src/javas/src/trees/CheckBST.java: -------------------------------------------------------------------------------- 1 | // From Cracking the code interview 2 | // 4.5 Check if a BTree is a valid BST 3 | 4 | package trees; 5 | 6 | public class CheckBST { 7 | public boolean check(TreeNode root) { 8 | return check(root, null, null); 9 | } 10 | 11 | public boolean check(TreeNode node, Integer min, Integer max) { 12 | if (node == null) 13 | return true; 14 | 15 | int val = node.value; 16 | if (min!=null && val <= min) return false; 17 | if (max!=null && val >= max) return false; 18 | 19 | if(!check(node.right, val, max)) return false; 20 | if(!check(node.left, min, val)) return false; 21 | 22 | return true; 23 | } 24 | 25 | public static void main(String[] args) { 26 | var root = new TreeNode(1); 27 | var l = new TreeNode(1); 28 | // l.left = new TreeNode(3); 29 | // l.right = new TreeNode(7); 30 | root.left = l; 31 | 32 | // var r = new TreeNode(3); 33 | // r.left = new TreeNode(11); 34 | // r.right = new TreeNode(20); 35 | // root.right = r; 36 | 37 | System.out.println(new CheckBST().check(root)); 38 | } 39 | } -------------------------------------------------------------------------------- /src/hackerrank/csharp/repeatedString.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class RepeatedString 4 | { 5 | static long repeatedString(string s, long n) 6 | { 7 | long len = s.Length; 8 | int countInS = 0; 9 | foreach (var c in s) 10 | if (c == 'a') 11 | countInS++; 12 | 13 | Console.WriteLine($"countInS: {countInS}"); 14 | 15 | long stringLenDiff = n - len; 16 | Console.WriteLine($"stringLenDiff: {stringLenDiff}"); 17 | 18 | long stringDiff = stringLenDiff / len; 19 | Console.WriteLine($"stringDiff: {stringDiff}"); 20 | 21 | long rem = stringLenDiff % len; 22 | Console.WriteLine($"rem: {rem}"); 23 | 24 | long total = (stringDiff * countInS) + countInS; 25 | Console.WriteLine($"total: {total}"); 26 | 27 | if (rem > 0) 28 | { 29 | int counted = 0; 30 | while (counted < rem) 31 | { 32 | if (s[counted] == 'a') 33 | total++; 34 | 35 | counted++; 36 | } 37 | } 38 | 39 | return total; 40 | } 41 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MergeSortedArraysInPlace.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | public class MergeSortedArraysInPlace { 4 | public void Merge(int[] arr1, int[] arr2) { 5 | int index1 = arr1.length-1; 6 | int index2 = arr2.length-1; 7 | 8 | while(index2 >= 0){ 9 | if(arr2[index2] <= arr1[index1]) 10 | { 11 | int x = arr1[index1]; 12 | arr1[index1] = arr2[index2]; 13 | arr2[index2--] = x; 14 | 15 | while(index1 > 0 && arr1[index1] <= arr1[index1-1]){ 16 | x = arr1[index1-1]; 17 | arr1[index1-1] = arr1[index1]; 18 | arr1[index1--] = x; 19 | } 20 | index1 = arr1.length-1; 21 | } 22 | else 23 | index2--; 24 | } 25 | 26 | for (int i : arr1) { 27 | System.out.println(i); 28 | } 29 | 30 | System.out.println("----"); 31 | 32 | for (int i : arr2) { 33 | System.out.println(i); 34 | } 35 | } 36 | 37 | public static void main(String[] args){ 38 | new MergeSortedArraysInPlace().Merge(new int[] {1,1,1,1}, 39 | new int[]{2,3,4,6,8}); 40 | } 41 | } -------------------------------------------------------------------------------- /src/javas/src/misc/TinyUrl.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/encode-and-decode-tinyurl/ 2 | 3 | package misc; 4 | 5 | import java.util.HashMap; 6 | 7 | public class TinyUrl { 8 | HashMap map; 9 | 10 | public TinyUrl(){ 11 | map = new HashMap<>(); 12 | } 13 | 14 | private long getHash(String url){ 15 | return Math.abs(url.hashCode()); 16 | } 17 | 18 | // Encodes a URL to a shortened URL. 19 | public String encode(String longUrl) { 20 | Long hash = getHash(longUrl); 21 | map.put(hash, longUrl); 22 | 23 | return "http://tinyurl.com/" + hash.toString(); 24 | } 25 | 26 | // Decodes a shortened URL to its original URL. 27 | public String decode(String shortUrl) { 28 | if(shortUrl.endsWith("/")) 29 | shortUrl = shortUrl.substring(shortUrl.length() - 1, 1); 30 | 31 | int lastSlash = shortUrl.lastIndexOf("/"); 32 | String hash = shortUrl.substring(lastSlash + 1, shortUrl.length()); 33 | String longUrl = map.get(Long.parseLong(hash)); 34 | 35 | return longUrl; 36 | } 37 | } -------------------------------------------------------------------------------- /src/javas/src/strings/AddStrings.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class AddStrings { 4 | 5 | public String addStrings(String num1, String num2) { 6 | if (num1 == null || num2 == null || num1.isEmpty() || num2.isEmpty()) 7 | return ""; 8 | 9 | int carry = 0; 10 | int i = num1.length(), j = num2.length(); 11 | int[] result = new int[Math.max(i, j)]; 12 | 13 | while (Math.max(i, j) > 0) { 14 | int n1 = Character.getNumericValue((i > 0) ? num1.charAt(i - 1) : '0'); 15 | int n2 = Character.getNumericValue((j > 0) ? num2.charAt(j - 1) : '0'); 16 | int n = (n1 + n2 + carry); 17 | 18 | result[Math.max(i, j)-1] = n % 10; 19 | carry = n > 9 ? 1 : 0; 20 | 21 | i--; j--; 22 | } 23 | StringBuffer resString = new StringBuffer(result.length + carry); 24 | if (carry > 0) resString.append(1); 25 | 26 | for (i = 0; i < result.length; i++) 27 | resString.append(result[i]); 28 | 29 | return resString.toString(); 30 | } 31 | 32 | public static void main(String[] args) { 33 | AddStrings a = new AddStrings(); 34 | System.out.println(a.addStrings("999", "1")); 35 | } 36 | } -------------------------------------------------------------------------------- /src/javas/src/trees/MinimalBST.java: -------------------------------------------------------------------------------- 1 | // Cracking the code interview 2 | // 4.2 Minimal Tree: Given a sorted (increasing order) array with unique integer elements, 3 | // write an algo­rithm to create a binary search tree with minimal height. 4 | // eg. [1,2,3,4,5,6] 5 | // 4 6 | // / \ 7 | // 3 5 8 | // / \ \ 9 | // 1 2 6 10 | 11 | package trees; 12 | 13 | public class MinimalBST{ 14 | public TreeNode create(int[] arr){ 15 | return create(arr, 0, arr.length - 1); 16 | } 17 | private TreeNode create(int[] arr, int i, int j){ 18 | if(j < i) return null; 19 | 20 | int mid = (i+j)/2; 21 | 22 | TreeNode n = new TreeNode(arr[mid]); 23 | n.left = create(arr, i, mid-1); 24 | n.right = create(arr, mid+1, j); 25 | 26 | return n; 27 | } 28 | 29 | public static void main(String[] args) { 30 | int[] input = {1,2,3,4,5,6}; 31 | TreeNode root = new MinimalBST().create(input); 32 | 33 | inorderPrint(root); 34 | } 35 | private static void inorderPrint(TreeNode node){ 36 | if(node!=null){ 37 | inorderPrint(node.left); 38 | System.out.println(node.value); 39 | inorderPrint(node.right); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/FruitIntoBasket.java: -------------------------------------------------------------------------------- 1 | package arrays; 2 | 3 | import java.util.*; 4 | 5 | public class FruitIntoBasket{ 6 | public int totalFruit(int[] trees){ 7 | int i=0, j=i+1, max = 1, count=1; 8 | if(trees == null || trees.length == 0) return max; 9 | 10 | Map hash = new HashMap<>(3); 11 | hash.put(trees[i], 1); 12 | 13 | while(i < trees.length && j < trees.length){ 14 | hash.put(trees[j], hash.getOrDefault(trees[j], 0) + 1); 15 | 16 | while(hash.size() > 2){ 17 | count = j - i - 1; 18 | hash.put(trees[i], hash.getOrDefault(trees[i], 0) - 1); 19 | hash.remove(trees[i],0); 20 | i++; 21 | } 22 | 23 | max = Math.max(++count, max); 24 | j++; 25 | } 26 | 27 | return max; 28 | } 29 | 30 | public static void main(String[] args) { 31 | // int[] trees = new int[]{1,2,1}; 32 | // int[] trees = new int[]{0,1,2,2}; 33 | // int[] trees = new int[]{1,2,3,2,2}; 34 | // int[] trees = new int[]{3,3,3,1,2,1,1,2,3,3,4}; 35 | // int[] trees = new int[]{0}; 36 | int[] trees = new int[]{0,1,6,6,4,4,6}; 37 | System.out.println(new FruitIntoBasket().totalFruit(trees)); 38 | } 39 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/PlusOne.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/plus-one/ 2 | 3 | package arrays; 4 | 5 | public class PlusOne{ 6 | public int[] plusOne(int[] digits){ 7 | if(digits[digits.length-1] < 9) 8 | { 9 | digits[digits.length-1]++; 10 | }else 11 | { 12 | int carry = 1; 13 | digits[digits.length-1] = 0; 14 | 15 | for(int i=digits.length-2;i>=0;i--) 16 | { 17 | digits[i] = (digits[i]+carry)%10; 18 | carry = (carry == 1 && digits[i]==0) ? 1 : 0; 19 | } 20 | 21 | if(carry == 1) 22 | { 23 | int[] n = new int[digits.length + 1]; 24 | n[0] = 1; 25 | for(int i=0,j=1;i -1) { 21 | check[index] = '0'; 22 | lettersFound++; 23 | 24 | if (lettersFound == 10) 25 | return findDistance(new StringBuffer(s.substring(i+1)).reverse().toString(), lettersFound); 26 | else if (lettersFound == 20) 27 | return s.length() - i - 1; 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | 34 | public static void main(String[] args) { 35 | String input = "adsdssprogrammerproghfghfhfhfhfhfhhfgfghrammer"; 36 | System.out.println("Input: " + input + " -> " + new ProgrammerString().findDistance(input)); 37 | } 38 | } -------------------------------------------------------------------------------- /src/javas/src/strings/GenerateParenthesis.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/generate-parentheses/ 2 | 3 | package strings; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class GenerateParenthesis { 9 | public List generateParenthesis(int k) { 10 | StringBuilder curr = new StringBuilder(); 11 | int open = k, close = k; 12 | List res = new ArrayList<>(); 13 | 14 | generate(res, open, close, curr, k); 15 | 16 | return res; 17 | } 18 | 19 | //backtracking 20 | private void generate(List res, int open, int close, StringBuilder curr, int k) { 21 | if (open == 0 && close == 0) { 22 | res.add(curr.toString()); 23 | return; 24 | } 25 | 26 | if (open > 0) { 27 | curr.append("("); 28 | generate(res, open - 1, close, curr, k); 29 | curr.deleteCharAt(curr.length() - 1); 30 | } 31 | if (close > 0 && close > open) { 32 | curr.append(")"); 33 | generate(res, open, close - 1, curr, k); 34 | curr.deleteCharAt(curr.length() - 1); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | int k = 2; 40 | System.out.println(new GenerateParenthesis().generateParenthesis(k)); 41 | } 42 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MyLinkedList.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class MyLinkedList { 4 | ListNode head = null; 5 | ListNode tail = null; 6 | 7 | public MyLinkedList() { 8 | } 9 | 10 | public MyLinkedList(ListNode first) { 11 | this.tail = this.head = first; 12 | } 13 | 14 | public MyLinkedList(Object firstValue) { 15 | this(new ListNode(firstValue)); 16 | } 17 | 18 | public void add(Object data) { 19 | ListNode node = new ListNode(data, this.head); 20 | this.head = node; 21 | 22 | if (this.tail == null) 23 | this.tail = node; 24 | } 25 | 26 | public void tailAdd(Object data) { 27 | ListNode node = new ListNode(data); 28 | if (this.tail == null) 29 | this.tail = this.head = node; 30 | else { 31 | this.tail.next = node; 32 | this.tail = node; 33 | } 34 | } 35 | 36 | public Object removeHead() { 37 | var data = this.head.data; 38 | this.head = this.head.next; 39 | return data; 40 | } 41 | 42 | public Boolean isEmpty(){ 43 | return this.head == null; 44 | } 45 | 46 | public void print() { 47 | var node = this.head; 48 | while (node != null) { 49 | System.out.println(node.data); 50 | node = node.next; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /src/javas/src/dynamic/TripleStep.java: -------------------------------------------------------------------------------- 1 | package dynamic; 2 | 3 | import java.util.Arrays; 4 | 5 | // From Cracking The Code Interview 8.1 6 | 7 | // Triple Step: A child is running up a staircase with n steps 8 | // and can hop either 1, 2 or 3 steps at a time. 9 | // Implement a method to count how many possible ways 10 | // the child can run up the stairs. 11 | 12 | public class TripleStep { 13 | public int count(int stairSize) { 14 | int[] memo = new int[stairSize]; 15 | Arrays.fill(memo, -1); 16 | memo[0] = 1; 17 | if (stairSize > 1) 18 | memo[1] = 2; 19 | if (stairSize > 2) 20 | memo[2] = 4; 21 | return count(stairSize, memo); 22 | } 23 | 24 | private int count(int stairSize, int[] memo) { 25 | if (stairSize == 1 || stairSize == 2 || stairSize == 3) 26 | return memo[stairSize - 1]; 27 | 28 | if (memo[stairSize - 1] < 0) 29 | memo[stairSize - 1] = count(stairSize - 1, memo) + count(stairSize - 2, memo) + count(stairSize - 3, memo); 30 | 31 | return memo[stairSize - 1]; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[] inputs = { 3, 4, 5, 6, 7, 8, 9, 10 }; 36 | 37 | for (int n : inputs) 38 | System.out.println("n: " + n + " -> " + new TripleStep().count(n)); 39 | } 40 | } -------------------------------------------------------------------------------- /src/javas/src/dynamic/ClimbStairs.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/climbing-stairs/ 2 | //You are climbing a stair case. It takes n steps to reach to the top. 3 | // Each time you can either climb 1 or 2 steps. 4 | // In how many distinct ways can you climb to the top? 5 | 6 | // A follow up problem could be: Triple Step 7 | // From Cracking The Code Interview 8.1 8 | 9 | // Triple Step: A child is running up a staircase with n steps 10 | // and can hop either 1, 2 or 3 steps at a time. 11 | // Implement a method to count how many possible ways 12 | // the child can run up the stairs. 13 | 14 | package dynamic; 15 | 16 | import java.util.*; 17 | 18 | public class ClimbStairs { 19 | public int climbStairsMemo(int n) { 20 | int[] memo = new int[n+1]; 21 | Arrays.fill(memo, -1); 22 | 23 | memo[0] = 1; 24 | if(n>0) memo[1] = 1; 25 | if(n>1) memo[2] = 2; 26 | 27 | for(int i = 3;i<=n;i++) 28 | memo[i] = memo[i-1] + memo[i-2]; 29 | 30 | return memo[n]; 31 | } 32 | public int climbStairsFib(int n) { 33 | int a = 1, b=2; 34 | 35 | if(n==0 || n==1) return a; 36 | if(n==2) return b; 37 | 38 | for(int i = 3;i<=n;i++){ 39 | int c = b; 40 | b = a + b; 41 | a=c; 42 | } 43 | 44 | return b; 45 | } 46 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/ContainerWithMostWater.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water 2 | 3 | package arrays; 4 | 5 | public class ContainerWithMostWater{ 6 | public int maxArea(int[] h) { 7 | int max = 0; 8 | 9 | if(h == null || h.length < 2) return max; 10 | 11 | int i = 0, j=h.length - 1; 12 | 13 | while(i < j){ 14 | max = Math.max(max, Math.min(h[i], h[j]) * (j - i)); 15 | if(h[i] > h[j]) j--; 16 | else i++; 17 | } 18 | 19 | return max; 20 | } 21 | 22 | public static void main(String[] args) { 23 | // int[] input = {1,2,3,2,1,2}; 24 | // int[] input = {1,8,6,2,5,4,8,3,7}; 25 | // int[] input = {0,1,8,6,2,5,4,8,3,7}; 26 | // int[] input = {1,8}; 27 | // int[] input = {8,1}; 28 | // int[] input = {8,7,9,8}; 29 | // int[] input = {1,2,3,4,5,6,7,8,9,10}; 30 | // int[] input = {10,9,8,7,6,5,4,3,2,1}; 31 | // int[] input = {10,10,1,1,1,1,1,1,1,1,1,1,1,1}; 32 | // int[] input = {10,10,1,1,1,1,1,1,1,1,100,100}; 33 | // int[] input = {10,10,1,1,1,1,1,1,1,100,100}; 34 | // int[] input = {10,10,50,100,100}; 35 | // int[] input = {1,1,2,1,2,2}; 36 | int[] input = {2,3,10,5,7,8,9}; 37 | 38 | System.out.println(new ContainerWithMostWater().maxArea(input)); 39 | } 40 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/MaxAreaIsland.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/max-area-of-island/ 2 | 3 | package arrays; 4 | 5 | public class MaxAreaIsland{ 6 | public int maxAreaOfIsland(int[][] grid){ 7 | if(grid.length == 0) return 0; 8 | if(grid[0].length == 0) return 0; 9 | 10 | int max = 0; 11 | for(int i=0;i= grid.length || i < 0) return 0; 20 | if(j >= grid[i].length || j < 0) return 0; 21 | if(grid[i][j] != 1) return 0; 22 | 23 | grid[i][j] = 0; 24 | 25 | return 1 + 26 | area(grid, i+1, j) + area(grid, i-1, j) + area(grid, i, j+1) + area(grid, i, j-1); 27 | } 28 | public static void main(String[] args) { 29 | // int[][] input = { {0,1,0,0}, 30 | // {1,1,1,0}, 31 | // {0,0,0,1}, 32 | // {1,1,1,1}}; 33 | 34 | int[][] input = { {1,1,0,0,0}, 35 | {1,1,0,0,0}, 36 | {0,0,0,1,1}, 37 | {0,0,0,1,1}}; 38 | 39 | System.out.println(new MaxAreaIsland().maxAreaOfIsland(input)); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /src/javas/src/misc/TrappingRainWater.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.ArrayDeque; 4 | import java.util.Deque; 5 | 6 | public class TrappingRainWater { 7 | public int trap(int[] h) { 8 | if (h.length < 3) return 0; 9 | 10 | Deque s = new ArrayDeque(); 11 | int current = h[0]; 12 | int total = 0; 13 | 14 | for (int i = 1; i < h.length; i++) { 15 | if (h[i] < current) { 16 | s.push(h[i]); 17 | } else { 18 | while (!s.isEmpty()) { total += (current - s.pop()); } 19 | current = h[i]; 20 | } 21 | } 22 | 23 | if (!s.isEmpty()) { 24 | int ch = s.pop(); 25 | if(ch < current) 26 | current = ch; 27 | 28 | while(!s.isEmpty()){ 29 | ch = s.pop(); 30 | if(current - ch > 0){ total += current - ch; } 31 | else { current = ch; } 32 | } 33 | } 34 | 35 | return total; 36 | } 37 | 38 | public static void main(String[] args) { 39 | TrappingRainWater t = new TrappingRainWater(); 40 | //0, 1, 0, 2, 1, 0, 1, 1, 2, 1, 2, 1 41 | //3,0,0,1 42 | //3,0,1,0,3 43 | //0,1,2,3,4,5 44 | //5,4,3,2,1 45 | //5,4,3,2,1,5 46 | 47 | int r = t.trap(new int[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}); 48 | System.out.println(r); 49 | } 50 | } -------------------------------------------------------------------------------- /src/javas/src/strings/MinWindowSubstring.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.HashMap; 4 | 5 | public class MinWindowSubstring{ 6 | public String minWindow(String s, String t){ 7 | HashMap table = new HashMap<>(); 8 | 9 | for(char c : t.toCharArray()) 10 | table.put(c, table.getOrDefault(c, 0) + 1); 11 | 12 | String res = ""; 13 | int begin=0, end=0; 14 | int counter = table.size(); 15 | int maxLen = Integer.MAX_VALUE; 16 | 17 | while(end < s.length()){ 18 | char c = s.charAt(end); 19 | 20 | if(table.containsKey(c)) 21 | if(table.put(c, table.get(c) - 1) == 1) 22 | counter--; 23 | 24 | end++; 25 | 26 | while(counter == 0){ 27 | maxLen = Math.max(maxLen, end - begin); 28 | res = s.substring(begin, end); 29 | 30 | c = s.charAt(begin); 31 | if(table.containsKey(c)) 32 | if(table.put(c, table.get(c) + 1) == 0) 33 | counter++; 34 | 35 | begin++; 36 | } 37 | } 38 | 39 | return res; 40 | } 41 | 42 | public static void main(String[] args) { 43 | MinWindowSubstring m = new MinWindowSubstring(); 44 | String s = "ADOBECODEBANC"; 45 | String t = "ABC"; 46 | 47 | System.out.println("Min: " + m.minWindow(s, t)); 48 | } 49 | } -------------------------------------------------------------------------------- /src/javas/src/misc/AddToAllCollection.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.HashMap; 4 | 5 | public class AddToAllCollection { 6 | int addedToAll = 0, currentIndex = 0; 7 | HashMap numbers; 8 | public AddToAllCollection() { 9 | numbers = new HashMap<>(); 10 | } 11 | 12 | public void append(int val){ 13 | this.numbers.put(currentIndex++, val - addedToAll); 14 | } 15 | public int getAt(int index){ 16 | return numbers.get(index) + addedToAll; 17 | } 18 | public void addToAll(int val){ 19 | this.addedToAll += val; 20 | } 21 | 22 | public static void main(String[] args) { 23 | AddToAllCollection ata = new AddToAllCollection(); 24 | ata.append(1); 25 | print("Added 1"); 26 | ata.append(2); 27 | print("Added 2"); 28 | ata.append(3); 29 | print("Added 3"); 30 | 31 | print("Get 0" + ata.getAt(0)); 32 | print("Get 1" + ata.getAt(1)); 33 | print("Get 2" + ata.getAt(2)); 34 | 35 | ata.addToAll(5); 36 | print("Added to all 5"); 37 | 38 | ata.append(5); 39 | print("Added 3"); 40 | 41 | print("Get 0" + ata.getAt(0)); 42 | print("Get 1" + ata.getAt(1)); 43 | print("Get 2" + ata.getAt(2)); 44 | print("Get 3" + ata.getAt(3)); 45 | } 46 | static void print(Object o){ 47 | System.out.print(o + " "); 48 | } 49 | } -------------------------------------------------------------------------------- /src/javas/src/trees/TwoSumIV.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum-iv-input-is-a-bst/ 2 | 3 | // could have done it using an array/list and a in-order traversal 4 | // getting a sorted array/list. Then running pointers on the sorted list. 5 | 6 | package trees; 7 | 8 | import java.util.*; 9 | 10 | public class TwoSumIV{ 11 | public boolean findTarget(TreeNode root, int k){ 12 | if(root == null) return false; 13 | HashSet need = new HashSet<>(); 14 | Queue queue = new LinkedList<>(); 15 | 16 | queue.add(root); 17 | need.add(k - root.value); 18 | 19 | while(!queue.isEmpty()){ 20 | TreeNode n = queue.poll(); 21 | if(n == null) continue; 22 | 23 | if(need.contains(n.value)) return true; 24 | 25 | need.add(k - n.value); 26 | queue.add(n.left); 27 | queue.add(n.right); 28 | } 29 | 30 | return false; 31 | } 32 | public static void main(String[] args) { 33 | var root = new TreeNode(5); 34 | var l = new TreeNode(3); 35 | l.left = new TreeNode(2); 36 | l.right = new TreeNode(4); 37 | root.left = l; 38 | 39 | var r = new TreeNode(6); 40 | // r.left = new TreeNode(11); 41 | r.right = new TreeNode(7); 42 | root.right = r; 43 | 44 | System.out.println(new TwoSumIV().findTarget(root, 17)); 45 | } 46 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/SingleElement.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/single-element-in-a-sorted-array/ 2 | 3 | // at first I solved in O(n) using a single while loop to check the pairs 4 | // then I realised it should be solved in O(logn) 5 | // the idea I used was to "binary search" the elements 6 | 7 | package arrays; 8 | 9 | import java.util.*; 10 | 11 | public class SingleElement { 12 | public int singleNonDuplicate(int[] nums) { 13 | int size = nums.length; 14 | if (size == 1) 15 | return nums[0]; 16 | 17 | int pivot = size / 2; 18 | if (nums[pivot] != nums[pivot + 1] && nums[pivot] != nums[pivot - 1]) 19 | return nums[pivot]; 20 | 21 | int ini = 0, end = size; 22 | if (nums[pivot] == nums[pivot - 1]) { 23 | if (pivot % 2 == 0) 24 | end = pivot + 1; 25 | else 26 | ini = pivot + 1; 27 | } else { 28 | if ((size - pivot) % 2 != 0) 29 | ini = pivot; 30 | else 31 | end = pivot; 32 | } 33 | return singleNonDuplicate(Arrays.copyOfRange(nums, ini, end)); 34 | } 35 | 36 | public static void main(String[] args) { 37 | // int[] input = {1,1,2,3,3,4,4,8,8}; 38 | // int[] input = {3,3,7,7,10,11,11}; 39 | int[] input = { 3, 3, 7, 7, 4, 4, 5, 5, 8, 8, 13, 11, 11 }; 40 | System.out.println(new SingleElement().singleNonDuplicate(input)); 41 | } 42 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/EvalReversePolishNotation.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/evaluate-reverse-polish-notation/ 2 | 3 | package arrays; 4 | 5 | import java.util.ArrayDeque; 6 | import java.util.Deque; 7 | 8 | public class EvalReversePolishNotation { 9 | public int evalRPN(String[] tokens) { 10 | if (tokens == null || tokens.length == 0) 11 | return 0; 12 | 13 | Deque stack = new ArrayDeque<>(); 14 | 15 | for (String token : tokens) { 16 | if (!"+-*/".contains(token)) 17 | stack.addFirst(Integer.parseInt(token)); 18 | else 19 | stack.addFirst(calc(token, stack.pop(), stack.pop())); 20 | } 21 | 22 | return stack.pop(); 23 | } 24 | 25 | private int calc(String op, int operand1, int operand2) { 26 | switch (op) { 27 | case "+": 28 | return operand2 + operand1; 29 | case "-": 30 | return operand2 - operand1; 31 | case "/": 32 | return operand2 / operand1; 33 | default: 34 | return operand2 * operand1; 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | String[] tokens = {"2"}; 40 | // String[] tokens = {"2", "1", "+", "3", "*"}; 41 | // String[] tokens = {"4", "13", "5", "/", "+"}; 42 | // String[] tokens = { "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+" }; 43 | 44 | System.out.println(new EvalReversePolishNotation().evalRPN(tokens)); 45 | } 46 | } -------------------------------------------------------------------------------- /src/javas/src/arrays/IslandPerimeter.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/island-perimeter/ 2 | 3 | package arrays; 4 | 5 | public class IslandPerimeter{ 6 | public int islandPerimeter(int[][] grid) { 7 | return count(grid, 0, 0); 8 | } 9 | private int count(int[][] mapa, int i, int j){ 10 | int linhas = mapa.length; 11 | if(i >= linhas || i < 0) return 0; 12 | int colunas = mapa[i].length; 13 | if(j >= colunas || j < 0) return 0; 14 | 15 | int pos = mapa[i][j]; 16 | if(pos == -1 || pos == 2) return 0; 17 | 18 | int counter = 0; 19 | if(pos == 1){ 20 | if(i+1 >= linhas || mapa[i+1][j] <= 0) counter++; 21 | if(i-1 < 0 || mapa[i-1][j] <= 0) counter++; 22 | if(j+1 >= colunas || mapa[i][j+1] <= 0) counter++; 23 | if(j-1 < 0 || mapa[i][j-1] <= 0) counter++; 24 | } 25 | 26 | mapa[i][j] = mapa[i][j] == 1 ? 2 : -1; 27 | 28 | return counter + 29 | count(mapa, i+1, j)+ 30 | count(mapa, i-1, j)+ 31 | count(mapa, i, j+1)+ 32 | count(mapa, i, j-1); 33 | } 34 | 35 | public static void main(String[] args) { 36 | // int[][] input = { {0,1,0,0}, 37 | // {1,1,1,0}, 38 | // {0,1,0,0}, 39 | // {1,1,0,0}}; 40 | 41 | int[][] input = { {0,0}, 42 | {1,0}}; 43 | System.out.println(new IslandPerimeter().islandPerimeter(input)); 44 | } 45 | } -------------------------------------------------------------------------------- /src/javas/src/strings/AllAnagrams.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | public class AllAnagrams { 8 | public List allAnagrams(String s, String p) { 9 | List res = new ArrayList<>(s.length()); 10 | HashMap table = new HashMap<>(p.length()); 11 | 12 | for (char c : p.toCharArray()) 13 | table.put(c, table.getOrDefault(c, 0) + 1); 14 | 15 | int begin = 0, end = 0, counter = table.size(); 16 | 17 | while (end < s.length()) { 18 | char c = s.charAt(end); 19 | Integer v = table.get(c); 20 | if (v != null) { 21 | table.put(c, v - 1); 22 | if (v - 1 == 0) 23 | counter--; 24 | } 25 | 26 | end++; 27 | 28 | while (counter == 0) { 29 | c = s.charAt(begin); 30 | v = table.get(c); 31 | if (v != null) { 32 | table.put(c, v + 1); 33 | if (v + 1 > 0) { 34 | counter++; 35 | if (end - begin == p.length()) 36 | res.add(begin); 37 | } 38 | } 39 | 40 | begin++; 41 | } 42 | } 43 | 44 | return res; 45 | } 46 | 47 | public static void main(String[] args) { 48 | String s = "baab"; 49 | String t = "ab"; 50 | 51 | System.out.println("S: " + s); 52 | System.out.println("T: " + t); 53 | System.out.println("Min: " + new AllAnagrams().allAnagrams(s, t)); 54 | } 55 | } -------------------------------------------------------------------------------- /src/javas/src/graphs/MostFriendsInCommon.java: -------------------------------------------------------------------------------- 1 | package graphs; 2 | 3 | import java.util.*; 4 | 5 | public class MostFriendsInCommon { 6 | public int find(List friends, int id){ 7 | if(friends == null || friends.isEmpty()) return -1; 8 | 9 | Set friendsOf = new HashSet<>(friends.size()); 10 | HashMap friendsOfCount = new HashMap<>(friends.size()); 11 | 12 | int maxFriendsCount = Integer.MIN_VALUE, maxFriend = Integer.MIN_VALUE; 13 | for(int[] friend : friends) 14 | { 15 | if(friend[0] == id) friendsOf.add(friend[1]); 16 | else if(friend[1] == id) friendsOf.add(friend[0]); 17 | } 18 | 19 | int f = Integer.MIN_VALUE; 20 | Integer v; 21 | for(int[] friend : friends){ 22 | if(friend[0] == id || friend[1] == id) continue; 23 | 24 | if(friendsOf.contains(friend[0])) 25 | f = friend[1]; 26 | else if(friendsOf.contains(friend[1])) 27 | f = friend[0]; 28 | 29 | v = friendsOfCount.put(f, friendsOfCount.getOrDefault(f, 0) + 1); 30 | if((v == null ? 0 : v) +1 > maxFriendsCount) 31 | { 32 | maxFriendsCount = (v == null ? 0 : v) +1; 33 | maxFriend = f; 34 | } 35 | } 36 | 37 | return maxFriend; 38 | } 39 | 40 | public static void main(String[] args) { 41 | MostFriendsInCommon mfic = new MostFriendsInCommon(); 42 | List friends = Arrays.asList(new int[][]{{1, 2}, {1, 3}, {2, 4}, {2, 5}, {3, 4}, {3,5}, {7,5},{8,5}, {1,7}}); 43 | System.out.println(mfic.find(friends, 1)); 44 | } 45 | } -------------------------------------------------------------------------------- /src/javas/src/strings/DecodeString.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/decode-string/ 2 | 3 | package strings; 4 | 5 | import java.util.*; 6 | 7 | public class DecodeString { 8 | public String decodeString(String s) { 9 | Stack stack = new Stack<>(); 10 | 11 | for (Character c : s.toCharArray()) { 12 | if (c == ']') { 13 | String x = stack.pop(); 14 | StringBuilder sb = new StringBuilder(); 15 | while (!Character.isDigit(x.charAt(0))) { 16 | if (!x.equals("[")) 17 | sb.append(x); 18 | 19 | if (!stack.isEmpty()) 20 | x = stack.pop(); 21 | } 22 | 23 | String number = x; 24 | while (!stack.isEmpty() && Character.isDigit(stack.peek().charAt(0))) 25 | number = stack.pop() + number; 26 | 27 | int num = Integer.parseInt(number); 28 | 29 | StringBuilder sbm = new StringBuilder(sb.length() * num); 30 | for (int i = 0; i < num; i++) 31 | sbm.append(sb.toString()); 32 | 33 | stack.add(sbm.toString()); 34 | sbm = sb = null; 35 | } else 36 | stack.add(c.toString()); 37 | } 38 | 39 | StringBuilder res = new StringBuilder(); 40 | while (!stack.isEmpty()) 41 | res.append(stack.pop()); 42 | 43 | return res.reverse().toString(); 44 | } 45 | 46 | public static void main(String[] args) { 47 | String input = "3[z]2[2[y]pq4[2[jk]e1[f]]]ef"; 48 | System.out.println(new DecodeString().decodeString(input)); 49 | } 50 | } -------------------------------------------------------------------------------- /src/javas/src/strings/SubdomainVisitCount.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subdomain-visit-count/ 2 | package strings; 3 | 4 | import java.util.*; 5 | 6 | public class SubdomainVisitCount { 7 | public List subdomainVisits(String[] domains) { 8 | List result = new ArrayList<>(); 9 | if(domains == null || domains.length == 0) return result; 10 | 11 | HashMap map = new HashMap<>(domains.length * 3); 12 | String[] aux, subdomains; 13 | int visits; 14 | String currentDomain; 15 | 16 | for(String item : domains){ 17 | aux = item.split(" "); 18 | visits = Integer.parseInt(aux[0]); 19 | subdomains = aux[1].split("\\."); 20 | 21 | currentDomain = ""; 22 | for(int i=subdomains.length-1;i>=0;i--){ 23 | currentDomain = subdomains[i] + (currentDomain.isEmpty() ? "" : ".") + currentDomain; 24 | map.put(currentDomain, map.getOrDefault(currentDomain, 0) + visits); 25 | } 26 | } 27 | 28 | for(Map.Entry entry : map.entrySet()) 29 | result.add(entry.getValue() + " " + entry.getKey()); 30 | 31 | return result; 32 | } 33 | 34 | 35 | public static void main(String[] args) { 36 | // String[] input = {"1 google.com", "1 mail.google.com"}; 37 | String[] input = {"900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"}; 38 | List res = new SubdomainVisitCount().subdomainVisits(input); 39 | 40 | for(var r : res) 41 | System.out.println(r); 42 | } 43 | } -------------------------------------------------------------------------------- /src/javas/src/graphs/Clone.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/clone-graph/ 2 | 3 | package graphs; 4 | 5 | import java.util.*; 6 | 7 | class Node { 8 | public int val; 9 | public List neighbors; 10 | 11 | public Node() { 12 | } 13 | 14 | public Node(int _val, List _neighbors) { 15 | val = _val; 16 | neighbors = _neighbors; 17 | } 18 | }; 19 | 20 | public class Clone { 21 | public Node cloneGraph(Node node) { 22 | if (node == null) 23 | return node; 24 | 25 | return clone(node, new HashMap()); 26 | } 27 | 28 | private Node clone(Node original, Map clones) { 29 | if (clones.containsKey(original)) 30 | return clones.get(original); 31 | 32 | clones.put(original, new Node(original.val, new ArrayList<>())); 33 | 34 | if (original.neighbors != null) { 35 | for (Node n : original.neighbors) 36 | clones.get(original).neighbors.add(clone(n, clones)); 37 | } 38 | 39 | return clones.get(original); 40 | } 41 | 42 | public static void main(String[] args) { 43 | Node a = new Node(); 44 | a.val = 1; 45 | 46 | Node b = new Node(); 47 | b.val = 2; 48 | 49 | Node c = new Node(); 50 | c.val = 3; 51 | 52 | Node d = new Node(); 53 | d.val = 4; 54 | 55 | a.neighbors = new ArrayList<>(Arrays.asList(b, d)); 56 | b.neighbors = new ArrayList<>(Arrays.asList(a, c)); 57 | c.neighbors = new ArrayList<>(Arrays.asList(b, d)); 58 | d.neighbors = new ArrayList<>(Arrays.asList(a, c)); 59 | 60 | Node clone = new Clone().cloneGraph(a); 61 | } 62 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MergeKLists.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-k-sorted-lists/ 2 | package linkedlists; 3 | 4 | import java.util.PriorityQueue; 5 | 6 | class LNode { 7 | int val; 8 | LNode next; 9 | LNode(int x) { val = x; } 10 | } 11 | public class MergeKLists { 12 | public LNode merge(LNode[] lists){ 13 | if(lists == null || lists.length == 0) return null; 14 | 15 | PriorityQueue heap = new PriorityQueue<>(lists.length, (a, b) -> a.val > b.val ? -1 : 1); 16 | for(LNode l : lists){ 17 | while(l!=null){ 18 | heap.add(l); 19 | l = l.next; 20 | } 21 | } 22 | 23 | LNode tail = heap.poll(); 24 | if(tail!=null){ 25 | tail.next = null; 26 | while(!heap.isEmpty()) 27 | { 28 | LNode h = heap.poll(); 29 | h.next = tail; 30 | tail = h; 31 | } 32 | } 33 | 34 | return tail; 35 | } 36 | public static void main(String[] args) { 37 | LNode l1 = new LNode(1); 38 | l1.next = new LNode(2); 39 | l1.next.next = new LNode(4); 40 | l1.next.next.next = new LNode(5); 41 | l1.next.next.next.next = new LNode(6); 42 | 43 | LNode l2 = new LNode(1); 44 | l2.next = new LNode(3); 45 | l2.next.next = new LNode(10); 46 | 47 | LNode l3 = new LNode(7); 48 | l3.next = new LNode(9); 49 | l3.next.next = new LNode(14); 50 | 51 | LNode[] input = {l2, l3, l1}; 52 | 53 | LNode res = new MergeKLists().merge(input); 54 | while (res != null) { 55 | System.out.println(res.val); 56 | res = res.next; 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/javas/src/strings/FindCommonCharacters.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | 7 | public class FindCommonCharacters{ 8 | public List commonChars(String[] words) { 9 | List res = new ArrayList<>(); 10 | if(words == null || words.length == 0) return res; 11 | 12 | HashMap map = new HashMap<>(26); 13 | for(char c : words[0].toCharArray()) 14 | map.put(c, map.getOrDefault(c, 0) + 1); 15 | 16 | HashMap tempMap; 17 | for(int i=1;i(map.size()); 19 | 20 | for(char c : words[i].toCharArray()){ 21 | if(map.containsKey(c)){ 22 | tempMap.put(c, tempMap.getOrDefault(c, 0) + 1); 23 | map.put(c, map.getOrDefault(c, 0) - 1); 24 | map.remove(c,0); 25 | } 26 | } 27 | map = tempMap; 28 | tempMap = null; 29 | } 30 | 31 | for(char c : map.keySet()) 32 | for(int i=0;i Integer.compare(a[0], b[0])); 16 | 17 | int ini = 0, end = 1; 18 | 19 | PriorityQueue rooms = new PriorityQueue<>(intervals.length, (a, b) -> a < b ? -1 : 1); 20 | rooms.add(intervals[0][end]); 21 | for(int i=1;i= rooms.peek()) 23 | rooms.poll(); 24 | 25 | rooms.add(intervals[i][end]); 26 | } 27 | 28 | return rooms.size(); 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | List> inputs = List.of( 34 | new Pair(new int[][]{{0,30},{15,20},{7,10}},2), 35 | new Pair(new int[][]{{7,10},{2,4}},1), 36 | new Pair(new int[][]{{0,30},{20, 22},{23, 25}},2), 37 | new Pair(new int[][]{{9,10},{4,9},{4,17}},2), 38 | new Pair(new int[][]{{1,2},{2,3},{3,4}},1), 39 | new Pair(new int[][]{{1,2},{2,3},{3,4},{3,5}},2), 40 | new Pair(new int[][]{{2,11},{6,16},{11,16}},2) 41 | ); 42 | 43 | for(Pair input : inputs) 44 | System.out.println(new MeetingRoomsTwo().minMeetingRooms(input.getKey()) + " should be -> " + input.getValue()); 45 | } 46 | } -------------------------------------------------------------------------------- /src/javas/src/strings/WeightedStrings.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | import java.math.BigInteger; 4 | 5 | public class WeightedStrings { 6 | private BigInteger[] internalWeights; 7 | private BigInteger[] weights(){ 8 | if(internalWeights == null){ 9 | internalWeights = new BigInteger[27]; 10 | internalWeights[0] = new BigInteger(Integer.toString(Integer.MIN_VALUE)); 11 | 12 | internalWeights[1] = BigInteger.valueOf(Long.valueOf(1)); 13 | for(int i=2; i<= 26;i++) 14 | internalWeights[i] = BigInteger.valueOf(Long.valueOf(i)) 15 | .multiply(internalWeights[i-1]) 16 | .add(internalWeights[i-1]); 17 | } 18 | 19 | return internalWeights; 20 | } 21 | 22 | public WeightedStrings() { 23 | weights(); 24 | } 25 | 26 | public String calc(BigInteger target) { 27 | return solve(target, 1, ""); 28 | } 29 | 30 | private String solve(BigInteger target, int lastPos, String res) { 31 | if(target.compareTo(new BigInteger("0")) == 0) return res; 32 | 33 | if(weights()[lastPos] == target) 34 | return Character.valueOf((char)(64 + lastPos)) + res; 35 | 36 | while(lastPos < (weights().length - 1) && weights()[lastPos].compareTo(target) <= 0) 37 | lastPos++; 38 | 39 | while(weights()[lastPos].compareTo(target) > 0 && lastPos > 0) 40 | lastPos--; 41 | 42 | return solve(target.subtract(weights()[lastPos]), lastPos, Character.valueOf((char)(64 + lastPos)) + res); 43 | } 44 | public static void main(String[] args) { 45 | WeightedStrings ws = new WeightedStrings(); 46 | BigInteger target = new BigInteger("2520"); 47 | System.out.print("Target: " + target + " = " + ws.calc(target)); 48 | } 49 | } -------------------------------------------------------------------------------- /src/javas/src/strings/ComparingVersionNumbers.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/compare-version-numbers/ 2 | 3 | package strings; 4 | 5 | public class ComparingVersionNumbers { 6 | public int compareVersion(String version1, String version2) { 7 | String[] parts1 = version1.split("\\."); 8 | String[] parts2 = version2.split("\\."); 9 | 10 | for (int i = 0; i < Math.max(parts1.length, parts2.length); i++) { 11 | String p1 = i < parts1.length ? parts1[i] : "0"; 12 | String p2 = i < parts2.length ? parts2[i] : "0"; 13 | 14 | int j = 0, c1 = 0, c2 = 0; 15 | while (j >= 0) { 16 | int k1 = p1.length()-1; 17 | while (k1 >=0) 18 | c1 += (p1.charAt(k1) - '0') * Math.pow(10, p1.length() - k1-- - 1); 19 | 20 | int k2 = p2.length()-1; 21 | while (k2 >= 0) 22 | c2 += (p2.charAt(k2) - '0') * Math.pow(10, p2.length() - k2-- - 1); 23 | 24 | j = Math.max(k1,k2); 25 | 26 | if (c1 != c2) 27 | return c1 > c2 ? 1 : -1; 28 | } 29 | } 30 | 31 | return 0; 32 | } 33 | 34 | public static void main(String[] args) { 35 | String v1 = "1.2"; 36 | String v2 = "1.10"; 37 | 38 | // String v1 = "1.1"; 39 | // String v2 = "1.10"; 40 | 41 | // String v1 = "0.1"; 42 | // String v2 = "1.1"; 43 | 44 | // String v1 = "1.01"; 45 | // String v2 = "1.1"; 46 | 47 | // String v1 = "1"; 48 | // String v2 = "1.1"; 49 | 50 | // String v1 = "1.0"; 51 | // String v2 = "1.0.0"; 52 | 53 | // String v1 = "7.5.2.4"; 54 | // String v2 = "7.5.3"; 55 | 56 | // String v1 = "1.0.1"; 57 | // String v2 = "1"; 58 | 59 | System.out.println(new ComparingVersionNumbers().compareVersion(v1, v2)); 60 | } 61 | } -------------------------------------------------------------------------------- /src/javas/src/trees/ArithmeticExpressionTree.java: -------------------------------------------------------------------------------- 1 | package trees; 2 | 3 | class ExpressionNode { 4 | String value; 5 | ExpressionNode left; 6 | ExpressionNode right; 7 | 8 | public ExpressionNode(String value) { 9 | this.value = value; 10 | } 11 | } 12 | 13 | public class ArithmeticExpressionTree { 14 | public void traverse(ExpressionNode root) { 15 | if (root == null) 16 | return; 17 | 18 | boolean hasLesserPrecedence = precedence(root) > precedence(root.left); 19 | if (hasLesserPrecedence) 20 | System.out.print("("); 21 | traverse(root.left); 22 | if (hasLesserPrecedence) 23 | System.out.print(")"); 24 | 25 | System.out.print(root.value); 26 | 27 | hasLesserPrecedence = precedence(root) >= precedence(root.right); 28 | if (hasLesserPrecedence) 29 | System.out.print("("); 30 | traverse(root.right); 31 | if (hasLesserPrecedence) 32 | System.out.print(")"); 33 | } 34 | 35 | public int precedence(ExpressionNode node) { 36 | if (node == null) 37 | return 4; 38 | 39 | switch (node.value) { 40 | case "+": 41 | case "-": 42 | return 1; 43 | case "/": 44 | case "*": 45 | return 2; 46 | default: 47 | return 3; 48 | } 49 | } 50 | 51 | public static void main(String[] args) { 52 | ExpressionNode root = new ExpressionNode("*"); 53 | ExpressionNode left = new ExpressionNode("+"); 54 | left.left = new ExpressionNode("2"); 55 | left.right = new ExpressionNode("2"); 56 | 57 | ExpressionNode right = new ExpressionNode("-"); 58 | right.left = new ExpressionNode("1"); 59 | right.right = new ExpressionNode("1"); 60 | 61 | root.left = left; 62 | root.right = right; 63 | 64 | new ArithmeticExpressionTree().traverse(root); 65 | } 66 | } -------------------------------------------------------------------------------- /src/javas/src/trees/SymmetricTree.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/symmetric-tree/ 2 | 3 | package trees; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | public class SymmetricTree { 9 | public boolean isSymmetric(TreeNode root) { 10 | List list = new ArrayList<>(); 11 | postOrder(root.right, list); 12 | preOrder(root.left, list); 13 | 14 | int i = 0, j = list.size() - 1; 15 | while (i < j) { 16 | if (list.get(i) != list.get(j)) 17 | return false; 18 | 19 | i++; 20 | j--; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | private void postOrder(TreeNode node, List list) { 27 | if (node == null) { 28 | list.add(null); 29 | return; 30 | } 31 | 32 | if (node.left == null && node.right == null) { 33 | list.add(node.value); 34 | return; 35 | } 36 | postOrder(node.left, list); 37 | postOrder(node.right, list); 38 | list.add(node.value); 39 | } 40 | 41 | private void preOrder(TreeNode node, List list) { 42 | if (node == null) { 43 | list.add(null); 44 | return; 45 | } 46 | 47 | list.add(node.value); 48 | if (node.left == null && node.right == null) 49 | return; 50 | 51 | preOrder(node.left, list); 52 | preOrder(node.right, list); 53 | } 54 | 55 | public static void main(String[] args) { 56 | TreeNode root = new TreeNode(1); 57 | TreeNode left = new TreeNode(2); 58 | left.left = new TreeNode(3); 59 | left.right = new TreeNode(4); 60 | root.left = left; 61 | 62 | TreeNode right = new TreeNode(2); 63 | right.left = new TreeNode(4); 64 | right.right = new TreeNode(3); 65 | root.right = right; 66 | 67 | System.out.println(new SymmetricTree().isSymmetric(root)); 68 | } 69 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MinStack.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/min-stack/ 2 | 3 | package linkedlists; 4 | 5 | class MyNode{ 6 | int data; 7 | MyNode next; 8 | 9 | public MyNode(int data){ 10 | this.data = data; 11 | this.next = null; 12 | } 13 | } 14 | 15 | public class MinStack { 16 | MyNode head; 17 | MyNode mins; 18 | 19 | public MinStack() { 20 | } 21 | 22 | public void push(int x) { 23 | MyNode n = new MyNode(x); 24 | if(this.head == null) 25 | this.head = n; 26 | else{ 27 | n.next = this.head; 28 | this.head = n; 29 | } 30 | 31 | if(this.mins == null || this.mins.data >= n.data) 32 | { 33 | MyNode nMin = new MyNode(x); 34 | nMin.next = this.mins; 35 | this.mins = nMin; 36 | } 37 | } 38 | 39 | public void pop() { 40 | if(this.head == null) 41 | throw new RuntimeException("Stack Underflow"); 42 | 43 | if(this.head.data == this.mins.data) 44 | { 45 | MyNode nextMin = this.mins.next; 46 | this.mins = nextMin; 47 | } 48 | 49 | this.head = this.head.next; 50 | } 51 | 52 | public int top() { 53 | if(this.head == null) 54 | throw new RuntimeException("Stack Underflow"); 55 | 56 | return this.head.data; 57 | } 58 | 59 | public int getMin() { 60 | if(this.head == null) 61 | throw new RuntimeException("Stack Underflow"); 62 | 63 | return this.mins.data; 64 | } 65 | 66 | public static void main(String[] args){ 67 | MinStack m = new MinStack(); 68 | m.push(10); 69 | m.push(1); 70 | m.push(5); 71 | 72 | System.out.println("Top: " + m.top()); 73 | System.out.println("Min: " + m.getMin()); 74 | } 75 | } -------------------------------------------------------------------------------- /src/javas/src/misc/MergeRanges.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-intervals/ 2 | package misc; 3 | 4 | import java.util.*; 5 | 6 | public class MergeRanges { 7 | public int[][] merge(int[][] intervals){ 8 | if(intervals == null || intervals.length == 0) return new int[0][0]; 9 | 10 | Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); 11 | List result = new ArrayList(); 12 | int[] nextRange = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE}; 13 | 14 | for(int[] interval : intervals){ 15 | if(nextRange[0] == Integer.MIN_VALUE && nextRange[1] == Integer.MIN_VALUE) 16 | nextRange = interval; 17 | else{ 18 | if(interval[0] <= nextRange[0]){ 19 | if(interval[1] >= nextRange[1]) 20 | nextRange = interval; 21 | else 22 | nextRange[0] = interval[0]; 23 | } 24 | else{ 25 | if(interval[0] <= nextRange[1]){ 26 | if(interval[1] >= nextRange[1]) 27 | nextRange[1] = interval[1]; 28 | } 29 | else{ 30 | result.add(nextRange); 31 | nextRange = interval; 32 | } 33 | } 34 | } 35 | } 36 | result.add(nextRange); 37 | int[][] r = new int[result.size()][2]; 38 | return result.toArray(r); 39 | } 40 | 41 | public static void main(String[] args) { 42 | // int[][] input = new int[][]{{1,3},{2,6},{8,10}}; 43 | // int[][] input = new int[][]{{1,4},{0,0}}; 44 | // int[][] input = new int[][]{{2,3},{4,5},{6,7},{8,9},{1,10}}; 45 | // int[][] input = new int[][]{{1,4},{5,6}}; 46 | int[][] input = new int[][]{{2,3},{5,5},{2,2},{3,4},{3,4}}; 47 | 48 | int[][] result = new MergeRanges().merge(input); 49 | 50 | for(var r : result) 51 | System.out.print("{" + r[0] + "," + r[1] + "}"); 52 | } 53 | } -------------------------------------------------------------------------------- /src/javas/src/misc/LexicalSort.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.Arrays; 4 | import java.util.Comparator; 5 | import java.util.LinkedList; 6 | import java.util.List; 7 | import java.util.Stack; 8 | 9 | 10 | // give N lists of strings 11 | // keep the order of lists that contains only digits from second chunk 12 | // for the other lists, sort them lexically 13 | 14 | public class LexicalSort { 15 | private boolean isPrimeOrder(List order){ 16 | for (Character c : order.get(1).toCharArray()) 17 | if(!Character.isDigit(c)) 18 | return true; 19 | 20 | return false; 21 | } 22 | public List> Sort(List> orders){ 23 | Stack> nonPrimes = new Stack<>(); 24 | List> primes = new LinkedList<>(); 25 | 26 | for (List o : orders) { 27 | if(isPrimeOrder(o)) primes.add(o); 28 | else nonPrimes.add(o); 29 | } 30 | 31 | Comparator> comparator = (a, b) -> { 32 | for(int i = 0; i < a.size();i++){ 33 | if(b.size() == i) return 1; 34 | int diffResult = a.get(i).compareTo(b.get(i)); 35 | if(diffResult != 0) 36 | return diffResult; 37 | } 38 | 39 | if(b.size() > a.size()) return -1; 40 | else return 0; 41 | }; 42 | primes.sort(comparator); 43 | 44 | for(List n : nonPrimes) 45 | primes.add(n); 46 | 47 | return primes; 48 | } 49 | 50 | public static void main(String[] args){ 51 | List> orders = Arrays.asList( 52 | Arrays.asList(new String[]{"ab1", "123"}), 53 | Arrays.asList(new String[]{"ab0", "999"}), 54 | Arrays.asList(new String[]{"ab0", "zzz"}), 55 | Arrays.asList(new String[]{"ab3", "aaa", "xyz"}), 56 | Arrays.asList(new String[]{"ab3", "aaa"})); 57 | 58 | for (List sorted : new LexicalSort().Sort(orders)) { 59 | System.out.println(sorted.toString()); 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /src/javas/src/strings/ReorderLogs.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reorder-log-files/ 2 | 3 | package strings; 4 | 5 | import java.util.Comparator; 6 | import java.util.LinkedList; 7 | import java.util.PriorityQueue; 8 | import java.util.Queue; 9 | 10 | public class ReorderLogs { 11 | private boolean isNumberLog(String log) { 12 | int spc = log.indexOf(' '); 13 | return Character.isDigit(log.charAt(spc + 1)); 14 | } 15 | 16 | class Lex implements Comparator { 17 | @Override 18 | public int compare(String s1, String s2) { 19 | int spc1 = s1.indexOf(' '); 20 | int spc2 = s2.indexOf(' '); 21 | 22 | return s1.substring(spc1 + 1, s1.length()).compareToIgnoreCase(s2.substring(spc2 + 1, s2.length())) == 0 23 | ? s1.substring(0, spc1 - 1).compareToIgnoreCase(s2.substring(0, spc2 - 1)) 24 | : s1.substring(spc1 + 1, s1.length()).compareToIgnoreCase(s2.substring(spc2 + 1, s2.length())); 25 | } 26 | } 27 | 28 | public String[] reorderLogFiles(String[] logs) { 29 | if (logs == null || logs.length < 2) 30 | return logs; 31 | 32 | Queue numberLogs = new LinkedList<>(); 33 | PriorityQueue letterLogs = new PriorityQueue<>(new Lex()); 34 | 35 | for (String log : logs) { 36 | if (isNumberLog(log)) 37 | numberLogs.add(log); 38 | else 39 | letterLogs.add(log); 40 | } 41 | 42 | String[] res = new String[numberLogs.size() + letterLogs.size()]; 43 | int i = 0; 44 | while (!letterLogs.isEmpty()) 45 | res[i++] = letterLogs.poll(); 46 | 47 | while (!numberLogs.isEmpty()) 48 | res[i++] = numberLogs.poll(); 49 | 50 | return res; 51 | } 52 | 53 | public static void main(String[] args) { 54 | String[] input = { "a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo" }; 55 | var res = new ReorderLogs().reorderLogFiles(input); 56 | 57 | for (var l : res) 58 | System.out.println(l); 59 | } 60 | } -------------------------------------------------------------------------------- /src/javas/src/trees/CodecTree.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/serialize-and-deserialize-binary-tree/ 2 | 3 | package trees; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class CodecTree { 9 | public String serialize(TreeNode root) { 10 | if (root == null) 11 | return "n"; 12 | 13 | StringBuilder serializedTreeBuffer = new StringBuilder(); 14 | Queue q = new LinkedList<>(); 15 | 16 | q.add(root); 17 | while (!q.isEmpty()) { 18 | TreeNode n = q.poll(); 19 | 20 | serializedTreeBuffer.append(n == null ? "n" : n.value); 21 | serializedTreeBuffer.append(","); 22 | 23 | if (n == null) 24 | continue; 25 | 26 | q.add(n.left); 27 | q.add(n.right); 28 | } 29 | 30 | return serializedTreeBuffer.substring(0, serializedTreeBuffer.length() - 1); 31 | } 32 | 33 | public TreeNode deserialize(String data) { 34 | if (data == null || data.length() == 0 || data.equals("n")) 35 | return null; 36 | 37 | String[] nodes = data.split(","); 38 | if (nodes == null || nodes.length == 0) 39 | return null; 40 | 41 | TreeNode root = new TreeNode(Integer.parseInt(nodes[0])); 42 | Queue q = new LinkedList<>(); 43 | q.add(root); 44 | 45 | int i = 1; 46 | while (!q.isEmpty() && i < nodes.length) { 47 | TreeNode n = q.poll(); 48 | if (!nodes[i].equals("n")) { 49 | n.left = new TreeNode(Integer.parseInt(nodes[i])); 50 | q.add(n.left); 51 | } 52 | i++; 53 | if (!nodes[i].equals("n")) { 54 | n.right = new TreeNode(Integer.parseInt(nodes[i])); 55 | q.add(n.right); 56 | } 57 | i++; 58 | } 59 | 60 | return root; 61 | } 62 | 63 | public static void main(String[] args) { 64 | // String input = "1,2,3,null,null,4,5,null,null,null,null,"; 65 | 66 | TreeNode t = new CodecTree().deserialize("5,2,3,n,n,2,4,3,1"); 67 | String r = new CodecTree().serialize(t); 68 | TreeNode n = new CodecTree().deserialize(r); 69 | } 70 | } -------------------------------------------------------------------------------- /src/javas/src/misc/LRUCache.java: -------------------------------------------------------------------------------- 1 | package misc; 2 | 3 | import java.util.HashMap; 4 | 5 | class DLNode { 6 | DLNode prev; 7 | int value; 8 | int key; 9 | DLNode next; 10 | public DLNode(int value, int key) { 11 | this.value = value; 12 | this.key = key; 13 | } 14 | public DLNode() { } 15 | } 16 | public class LRUCache { 17 | int maxCapacity = 0, currentCapacity = 0; 18 | DLNode head, tail; 19 | HashMap hash = new HashMap();; 20 | 21 | public LRUCache(int capacity) { 22 | this.maxCapacity = capacity; 23 | this.head = new DLNode(); this.tail = new DLNode(); 24 | 25 | this.head.next = this.tail; 26 | this.tail.prev = this.head; 27 | } 28 | 29 | public void put(int key, int value){ 30 | DLNode n = hash.get(key); 31 | if(n == null){ 32 | n = new DLNode(value, key); 33 | moveToFront(n); 34 | this.hash.put(key, n); 35 | this.currentCapacity++; 36 | evictLastIfNeeded(); 37 | } 38 | else{ 39 | n.value = value; 40 | n.prev.next = n.next; 41 | n.next.prev = n.prev; 42 | moveToFront(n); 43 | } 44 | } 45 | 46 | public void moveToFront(DLNode n){ 47 | n.prev = this.head; 48 | n.next = this.head.next; 49 | 50 | this.head.next.prev = n; 51 | this.head.next = n; 52 | } 53 | private void evictLastIfNeeded(){ 54 | if(currentCapacity>maxCapacity){ 55 | DLNode deleteNode = this.tail.prev; 56 | deleteNode.prev.next = this.tail; 57 | this.tail.prev = deleteNode.prev; 58 | 59 | this.hash.remove(deleteNode.key); 60 | deleteNode = null; 61 | } 62 | } 63 | int NOT_FOUND = -1; 64 | public int get(int key){ 65 | DLNode n = hash.get(key); 66 | if(n == null) return NOT_FOUND; 67 | 68 | put(n.key, n.value); 69 | return n.value; 70 | } 71 | public static void main (String[] args){ 72 | LRUCache c = new LRUCache(10); 73 | c.put(1, 1); 74 | c.put(2, 2); 75 | c.get(1); 76 | c.put(3, 3); 77 | c.put(1, 10); 78 | c.get(1); 79 | } 80 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/Merge.java: -------------------------------------------------------------------------------- 1 | package linkedlists; 2 | 3 | public class Merge { 4 | public ListNode mergeTwoListsNewList(ListNode l1, ListNode l2) { 5 | return mergeTwoListsNewList(l1, l2, null); 6 | } 7 | 8 | public ListNode mergeTwoListsNewList(ListNode l1, ListNode l2, ListNode res) { 9 | if (l1 == null && l2 == null) 10 | return res; 11 | 12 | if (l1 == null) { 13 | res = insert(l2, res); 14 | l2 = l2.next; 15 | } else if (l2 == null) { 16 | res = insert(l1, res); 17 | l1 = l1.next; 18 | } else { 19 | if ((int)l1.data >= (int)l2.data) { 20 | res = insert(l2, res); 21 | l2 = l2.next; 22 | } else { 23 | res = insert(l1, res); 24 | l1 = l1.next; 25 | } 26 | } 27 | 28 | return mergeTwoListsNewList(l1, l2, res); 29 | } 30 | 31 | private ListNode insert(ListNode o, ListNode dest) { 32 | ListNode n = new ListNode(o.data); 33 | if (dest == null) 34 | dest = n; 35 | else { 36 | ListNode l = dest; 37 | while (l.next != null) 38 | l = l.next; 39 | 40 | l.next = n; 41 | } 42 | 43 | return dest; 44 | } 45 | 46 | public ListNode mergeTwoLists(ListNode l1, ListNode l2){ 47 | if(l1 == null) return l2; 48 | if(l2 == null) return l1; 49 | 50 | if((int)l1.data < (int)l2.data){ 51 | l1.next = mergeTwoLists(l1.next, l2); 52 | return l1; 53 | } 54 | else 55 | { 56 | l2.next = mergeTwoLists(l1, l2.next); 57 | return l2; 58 | } 59 | } 60 | public static void main(String[] args) { 61 | ListNode l1 = new ListNode(1); 62 | l1.next = new ListNode(2); 63 | l1.next.next = new ListNode(4); 64 | l1.next.next.next = new ListNode(5); 65 | l1.next.next.next.next = new ListNode(6); 66 | 67 | ListNode l2 = new ListNode(1); 68 | l2.next = new ListNode(3); 69 | l2.next.next = new ListNode(10); 70 | 71 | ListNode res = new Merge().mergeTwoLists(l1, l2); 72 | while (res != null) { 73 | System.out.println(res.data); 74 | res = res.next; 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/javas/src/trees/ListOfDepths.java: -------------------------------------------------------------------------------- 1 | // from Cracking the code interview 2 | 3 | // 4.3: Given a binary tree, design an algorithm 4 | // which creates a linked list of all the nodes at each depth 5 | // (eg. if you have a tree with depth D, you'll have D linked lists). 6 | 7 | package trees; 8 | 9 | import java.util.*; 10 | 11 | import linkedlists.ListNode; 12 | 13 | public class ListOfDepths{ 14 | public List listFrom(TreeNode root){ 15 | List res = new ArrayList<>(); 16 | 17 | Queue queue = new LinkedList<>(); 18 | queue.add(root); 19 | 20 | int level = 0, visited = 0; 21 | 22 | ListNode h = null, t = null; 23 | while(!queue.isEmpty()){ 24 | var node = queue.poll(); 25 | if(node == null) continue; 26 | 27 | visited++; 28 | var item = new ListNode(node.value); 29 | 30 | if(level == 0){ 31 | res.add(item); 32 | level++; 33 | visited=0; 34 | } 35 | else if(visited == level*2){ 36 | t.next = item; 37 | res.add(h); 38 | h = null; 39 | level++; visited=0; 40 | } 41 | else 42 | { 43 | if(h == null) 44 | h = t = item; 45 | else{ 46 | t.next = item; 47 | t = t.next; 48 | } 49 | } 50 | 51 | queue.add(node.left); 52 | queue.add(node.right); 53 | } 54 | 55 | return res; 56 | } 57 | 58 | public static void main(String[] args) { 59 | var root = new TreeNode(10); 60 | var l = new TreeNode(5); 61 | l.left = new TreeNode(3); 62 | l.right = new TreeNode(7); 63 | root.left = l; 64 | 65 | var r = new TreeNode(12); 66 | r.left = new TreeNode(11); 67 | r.right = new TreeNode(13); 68 | root.right = r; 69 | 70 | var res = new ListOfDepths().listFrom(root); 71 | 72 | for (var h : res) { 73 | while(h!=null){ 74 | System.out.print(h.data + " -> "); 75 | h = h.next; 76 | } 77 | System.out.println(""); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /src/javas/src/linkedlists/MaxStack.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/min-stack/ 2 | 3 | package linkedlists; 4 | 5 | 6 | class MaxStack { 7 | class MyNode{ 8 | int data; 9 | MyNode next; 10 | 11 | public MyNode(int data){ 12 | this.data = data; 13 | this.next = null; 14 | } 15 | } 16 | MyNode head; 17 | MyNode maxs; 18 | 19 | public MaxStack() { } 20 | 21 | public void push(int x) { 22 | MyNode n = new MyNode(x); 23 | if(this.head == null) 24 | this.head = n; 25 | else{ 26 | n.next = this.head; 27 | this.head = n; 28 | } 29 | 30 | int max = this.maxs == null ? n.data : Math.max(this.maxs.data, n.data); 31 | MyNode nMax = new MyNode(max); 32 | 33 | if(this.maxs == null) 34 | this.maxs = nMax; 35 | else { 36 | nMax.next = this.maxs; 37 | this.maxs = nMax; 38 | } 39 | } 40 | 41 | public int pop() { 42 | if(this.head == null) 43 | throw new RuntimeException("Stack Underflow"); 44 | 45 | this.maxs = this.maxs.next; 46 | 47 | int v = this.head.data; 48 | this.head = this.head.next; 49 | 50 | return v; 51 | } 52 | 53 | public int top() { 54 | if(this.head == null) 55 | throw new RuntimeException("Stack is empty"); 56 | 57 | return this.head.data; 58 | } 59 | public int peekMax(){ 60 | if(this.maxs == null) 61 | throw new RuntimeException("Stack is empty"); 62 | 63 | return this.maxs.data; 64 | } 65 | 66 | public int popMax() { 67 | if(this.maxs == null) 68 | throw new RuntimeException("Stack is empty"); 69 | 70 | MyNode temp = null; 71 | while(this.head.data != this.maxs.data){ 72 | MyNode n = new MyNode(this.head.data); 73 | n.next = temp; 74 | temp = n; 75 | pop(); 76 | } 77 | 78 | int max = pop(); 79 | 80 | while(temp!=null){ 81 | push(temp.data); 82 | temp = temp.next; 83 | } 84 | 85 | return max; 86 | } 87 | 88 | public static void main(String[] args){ 89 | MaxStack m = new MaxStack(); 90 | m.push(5); 91 | m.push(1); 92 | m.push(-5); 93 | 94 | 95 | System.out.println("PopMax: " + m.popMax()); 96 | System.out.println("PopMax: " + m.popMax()); 97 | System.out.println("Top: " + m.top()); 98 | } 99 | } -------------------------------------------------------------------------------- /src/javas/src/misc/MyHashSet.java: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/design-hashset/ 2 | 3 | package misc; 4 | 5 | import java.util.ArrayList; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | class HashItem{ 10 | int key; 11 | 12 | public HashItem() { } 13 | public HashItem(int key) { this.key = key; } 14 | } 15 | // hashing 16 | class MyHashSet { 17 | private int growthFactor = 1; 18 | private final double loadFactor = 0.7; 19 | private int capacity = 16; 20 | private List> map = null; 21 | private int items = 0; 22 | 23 | public MyHashSet() { resizeMap(); } 24 | public MyHashSet(int initialCapacity) { capacity = initialCapacity; resizeMap(); } 25 | private void resizeMap() { 26 | map = new ArrayList<>(capacity); 27 | for(int i=0;i()); 29 | } 30 | private int hash(int key){ return key % capacity; } 31 | private void reHashIfNeeded(){ 32 | if((double)items / (double)capacity < loadFactor) 33 | return; 34 | 35 | capacity *= (growthFactor *= 2); 36 | 37 | List> nMap = map; 38 | resizeMap(); 39 | items = 0; 40 | for(LinkedList l : nMap) 41 | for(HashItem n : l) 42 | put(n.key); 43 | } 44 | 45 | public void put(int key){ 46 | int hash = hash(key); 47 | 48 | LinkedList hashedItems = map.get(hash); 49 | 50 | for(HashItem n : hashedItems) 51 | if(n.key == key) return; 52 | 53 | items++; 54 | hashedItems.add(new HashItem(key)); 55 | 56 | reHashIfNeeded(); 57 | } 58 | public boolean contains(int key){ 59 | LinkedList hashedItems = map.get(hash(key)); 60 | for(HashItem n : hashedItems) 61 | if(n.key == key) 62 | return true; 63 | 64 | return false; 65 | } 66 | public void remove(int key){ 67 | LinkedList hashedItems = map.get(hash(key)); 68 | 69 | for(HashItem n : hashedItems) 70 | if(n.key == key){ 71 | hashedItems.remove(n); 72 | items--; 73 | return; 74 | } 75 | } 76 | public int size(){return items;} 77 | 78 | public static void main(String[] args) { 79 | MyHashSet hashMap = new MyHashSet(); 80 | hashMap.put(17); 81 | hashMap.put(7); 82 | hashMap.put(1); 83 | System.out.println(hashMap.contains(17)); 84 | System.out.println(hashMap.contains(7)); 85 | hashMap.remove(7); 86 | System.out.println(hashMap.contains(17)); 87 | System.out.println(hashMap.contains(7)); 88 | for(int i=10;i<100;i++) 89 | hashMap.put(i); 90 | } 91 | } -------------------------------------------------------------------------------- /src/javas/src/heaps/MyMinHeap.java: -------------------------------------------------------------------------------- 1 | package heaps; 2 | 3 | public class MyMinHeap{ 4 | int[] data; 5 | int size = Integer.MIN_VALUE; 6 | 7 | public MyMinHeap() { 8 | data = new int[10]; 9 | } 10 | 11 | public Boolean isEmpty(){ return size == Integer.MIN_VALUE; } 12 | public int peek() throws Exception { 13 | if(isEmpty()) 14 | throw new Exception("Heap is empty!"); 15 | 16 | return data[0]; 17 | } 18 | public void add(int value){ 19 | if(isEmpty()) 20 | size = 0; 21 | 22 | data[size] = value; 23 | size++; 24 | 25 | heapifyUpwards(); 26 | } 27 | public int remove() throws Exception { 28 | if(isEmpty()) 29 | throw new Exception("Heap is empty!"); 30 | 31 | int value = data[0]; 32 | data[0] = data[size-1]; 33 | size--; 34 | 35 | heapifyDownwards(); 36 | 37 | return value; 38 | } 39 | private void heapifyUpwards(){ 40 | int currentIndex = size - 1; 41 | int parentIndex = (currentIndex - 1) / 2; 42 | 43 | while(parentIndex >= 0 && data[parentIndex] > data[currentIndex]) 44 | { 45 | int temp = data[currentIndex]; 46 | data[currentIndex] = data[parentIndex]; 47 | data[parentIndex] = temp; 48 | 49 | currentIndex = parentIndex; 50 | parentIndex = (parentIndex - 1) / 2; 51 | } 52 | } 53 | private void heapifyDownwards(){ 54 | int currentIndex = 0; 55 | int leftIndex = (currentIndex * 2) + 1; 56 | 57 | while(leftIndex < size){ 58 | int smaller = leftIndex; 59 | int rightIndex = (currentIndex * 2) + 2; 60 | 61 | if(rightIndex= 0 && data[parentIndex] < data[currentIndex]) 44 | { 45 | int temp = data[currentIndex]; 46 | data[currentIndex] = data[parentIndex]; 47 | data[parentIndex] = temp; 48 | 49 | currentIndex = parentIndex; 50 | parentIndex = (parentIndex - 1) / 2; 51 | } 52 | } 53 | private void heapifyDownwards(){ 54 | int currentIndex = 0; 55 | int leftIndex = (currentIndex * 2) + 1; 56 | 57 | while(leftIndex < size){ 58 | int greater = leftIndex; 59 | int rightIndex = (currentIndex * 2) + 2; 60 | 61 | if(rightIndex data[leftIndex]) 62 | greater = rightIndex; 63 | 64 | if(data[currentIndex] > data[greater]) 65 | break; 66 | 67 | int temp = data[currentIndex]; 68 | data[currentIndex] = data[greater]; 69 | data[greater] = temp; 70 | 71 | currentIndex = greater; 72 | leftIndex = (currentIndex * 2) + 1; 73 | } 74 | } 75 | 76 | public void printHeap(){ 77 | for(int i=0;i> map = null; 46 | private int items = 0; 47 | 48 | public MyGoodHashMap() { resizeMap(); } 49 | public MyGoodHashMap(int initialCapacity) { capacity = initialCapacity; resizeMap(); } 50 | private void resizeMap() { 51 | map = new ArrayList<>(capacity); 52 | for(int i=0;i()); 54 | } 55 | private int hash(int key){ return key % capacity; } 56 | private void reHashIfNeeded(){ 57 | if((double)items / (double)capacity < loadFactor) 58 | return; 59 | 60 | capacity *= 2; 61 | 62 | List> nMap = map; 63 | resizeMap(); 64 | items = 0; 65 | for(LinkedList l : nMap) 66 | for(MapNode n : l) 67 | put(n.key, n.value); 68 | } 69 | 70 | public void put(int key, int value){ 71 | int hash = hash(key); 72 | 73 | LinkedList hashedItems = map.get(hash); 74 | 75 | for(MapNode n : hashedItems) 76 | if(n.key == key){ 77 | n.value = value; 78 | return; 79 | } 80 | 81 | items++; 82 | hashedItems.add(new MapNode(key, value)); 83 | 84 | reHashIfNeeded(); 85 | } 86 | public int get(int key){ 87 | LinkedList hashedItems = map.get(hash(key)); 88 | for(MapNode n : hashedItems) 89 | if(n.key == key) 90 | return n.value; 91 | 92 | return -1; 93 | } 94 | public void remove(int key){ 95 | LinkedList hashedItems = map.get(hash(key)); 96 | 97 | for(MapNode n : hashedItems) 98 | if(n.key == key){ 99 | hashedItems.remove(n); 100 | items--; 101 | return; 102 | } 103 | } 104 | public int size(){return items;} 105 | 106 | public static void main(String[] args) { 107 | MyGoodHashMap hashMap = new MyGoodHashMap(); 108 | hashMap.put(17, 17); 109 | hashMap.put(7, 7); 110 | hashMap.put(1, 1); 111 | hashMap.remove(7); 112 | hashMap.put(4, 4); 113 | } 114 | } --------------------------------------------------------------------------------