Algorithm Pattern 1 – Find the target element class Solution { public int search(int[] nums, int target) { int left = 0, right = nums.length – 1; while(left <= right){ int mid = left + (right – left) / 2; if(nums[mid] == target){ return mid; } else if(nums[mid] < target){ left = mid + 1; …
Algorithm Pattern – Sliding Window
Problem Usually if you are asked to find out substring based on one string pattern in another string, it means you have to check all possible substring in one string, so you should maintain a sliding window to check each substring candidate. Thought For convenience, I call two strings as pattern string and explore string. …
Algorithm Pattern – Monotone Stack (LC 496 739 503)
Question Monotone Stack question usually ask you to find the next greater integer in an array. Approach Maintain a monotone stack, which stores index of descending integers, and while you face an element greater than the top of stack, we could assign this element as the next greater integer. Algorithm Pattern Deque<Integer> stack = new …
Continue reading “Algorithm Pattern – Monotone Stack (LC 496 739 503)”
How to reverse String in java
Use the code below: // conversion from String object to StringBuffer StringBuffer sbr = new StringBuffer(str); // To reverse the string sbr.reverse();
How to convert Array to List
Plain Java public void givenUsingCoreJava_whenArrayConvertedToList_thenCorrect() { Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 }; List<Integer> targetList = Arrays.asList(sourceArray); } Commons Collection public void givenUsingCommonsCollections_whenArrayConvertedToList_thenCorrect() { Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 }; List<Integer> targetList = new ArrayList<>(6); CollectionUtils.addAll(targetList, sourceArray); } Guava public void givenUsingGuava_whenListConvertedToArray_thenCorrect() { List<Integer> sourceList = …
Quick Sort
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. Always pick first element as pivot. Always pick last element as pivot (implemented below) Pick a random element as pivot. …
TreeMap in Java
Introduction The TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and …