diff --git a/src/main/java/com/ibm/code_pair/bookish_spoon/LRUCache.java b/src/main/java/com/ibm/code_pair/bookish_spoon/LRUCache.java new file mode 100644 index 0000000..8465ef2 --- /dev/null +++ b/src/main/java/com/ibm/code_pair/bookish_spoon/LRUCache.java @@ -0,0 +1,24 @@ +package com.ibm.code_pair.bookish_spoon; + +public class LRUCache { + + /** + * Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. + * + * Implement the LRUCache class: + * + * LRUCache(int capacity) Initializes the LRU cache with positive size capacity. + * int get(int key) Return the value of the key if the key exists, otherwise return -1. + * void put(int key, int value) Update the value of the key if the key exists. + * + * Otherwise, add the key-value pair to the cache. + * If the number of keys exceeds the capacity from this operation, evict the least recently used key. + * + * The functions get and put must each run in O(1) average time complexity. + * @param args + */ + + public static void main(String[] args) { + + } +} diff --git a/src/main/java/com/ibm/code_pair/bookish_spoon/TrappingRainWater.java b/src/main/java/com/ibm/code_pair/bookish_spoon/TrappingRainWater.java new file mode 100644 index 0000000..598ea01 --- /dev/null +++ b/src/main/java/com/ibm/code_pair/bookish_spoon/TrappingRainWater.java @@ -0,0 +1,76 @@ +package com.ibm.code_pair.bookish_spoon; + +/** + *

Trapping Rain Water

+ * + *

+ * Given n non-negative integers representing an elevation map where + * the width of each bar is 1, compute how much water it can trap after raining. + *

+ + * + *

Input Example

+ * + *
+ * height = [0,1,0,2,1,0,1,3,2,1,2,1]
+ * 
+ * + *

Output

+ * + *
+ * 6
+ * 
+ * + *

Constraints

+ * + * + */ +public class TrappingRainWater { + + public static void main(String[] args) { + int[] height = {0,1,0,2,1,0,1,3,2,1,2,1}; + + TrappingRainWater solver = new TrappingRainWater(); + int result = solver.trap(height); + + System.out.println("Trapped water = " + result); + } + + /** + * Two-pointer implementation of the Trapping Rain Water problem. + * + * @param height array representing elevation bars + * @return total water trapped + */ + private int trap(int[] height) { + private static int trap(int[] arr) { + + int n = arr.length; + if(n<=2) return 0; + int[] prefix = new int[n]; + int[] postfix = new int[n]; + + //prefix traversal + prefix[0] = arr[0]; + for(int i = 1; i=0; i--) { + postfix[i] = Math.max(postfix[i+1], arr[i]); + } + + int result = 0; + for(int i=1; i